diff --git a/sdk/agentserver/azure-ai-agentserver-responses/Makefile b/sdk/agentserver/azure-ai-agentserver-responses/Makefile index 488836d2fa9a..bd02d599a739 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/Makefile +++ b/sdk/agentserver/azure-ai-agentserver-responses/Makefile @@ -15,9 +15,9 @@ ROOT_SCHEMAS ?= CreateResponse OVERLAY ?= _scripts/validation-overlay.yaml TEMP_OUTPUT_DIR := $(OUTPUT_DIR)/.tmp_codegen MODEL_PACKAGE_DIR := $(TEMP_OUTPUT_DIR)/azure/ai/agentserver/responses/models -MODEL_SHIMS_DIR := _scripts/generated_shims CONTRACTS_DIR := $(TEMP_TSP_DIR)/sdk-service-agentserver-contracts -MODEL_BASE := $(OUTPUT_DIR)/sdk/models/_utils/model_base.py +SDK_ROOT ?= ../../.. +EXTENSION_OPENAI_DIR ?= $(SDK_ROOT)/sdk/ai/azure-ai-extensions-openai .PHONY: generate-models generate-validators generate-openapi generate-contracts clean install-typespec-deps @@ -95,31 +95,10 @@ generate-contracts: generate-models generate-openapi generate-validators ifeq ($(OS),Windows_NT) generate-models: @where tsp-client >NUL 2>NUL || (echo Error: tsp-client is not installed. 1>&2 && echo Run 'make install-typespec-deps' to install it. 1>&2 && exit /b 1) - @where npm >NUL 2>NUL || (echo Error: npm is required. Install Node.js ^(v18+^) from https://nodejs.org/ 1>&2 && exit /b 1) - @echo Syncing upstream TypeSpec sources... - cd /d $(TYPESPEC_DIR) && tsp-client sync - @echo Installing TypeSpec dependencies from emitter-package.json... - cd /d $(TEMP_TSP_DIR) && npm install --silent - @echo Generating Python models... + @echo Generating extension-owned OpenAI Responses models... + cd /d $(EXTENSION_OPENAI_DIR) && $(MAKE) generate-responses-models @if exist "$(OUTPUT_DIR)" rmdir /s /q "$(OUTPUT_DIR)" - cd /d $(TEMP_TSP_DIR) && npx tsp compile sdk-service-agentserver-contracts\client.tsp --emit @azure-tools/typespec-python --option "@azure-tools/typespec-python.emitter-output-dir=$(abspath $(TEMP_OUTPUT_DIR))" - @if not exist "$(MODEL_PACKAGE_DIR)" (echo Error: generated model package was not found. 1>&2 && exit /b 1) - @if not exist "$(OUTPUT_DIR)\sdk" mkdir "$(OUTPUT_DIR)\sdk" - @xcopy /E /I /Y "$(MODEL_PACKAGE_DIR)" "$(OUTPUT_DIR)\sdk\models" >NUL - @if exist "$(OUTPUT_DIR)\sdk\models\aio" rmdir /s /q "$(OUTPUT_DIR)\sdk\models\aio" - @if exist "$(OUTPUT_DIR)\sdk\models\operations" rmdir /s /q "$(OUTPUT_DIR)\sdk\models\operations" - @if exist "$(OUTPUT_DIR)\sdk\models\_client.py" del /q "$(OUTPUT_DIR)\sdk\models\_client.py" - @if exist "$(OUTPUT_DIR)\sdk\models\_configuration.py" del /q "$(OUTPUT_DIR)\sdk\models\_configuration.py" - @if exist "$(OUTPUT_DIR)\sdk\models\_version.py" del /q "$(OUTPUT_DIR)\sdk\models\_version.py" - @copy /Y "$(MODEL_SHIMS_DIR)\sdk_models__init__.py" "$(OUTPUT_DIR)\sdk\models\__init__.py" >NUL - @copy /Y "$(MODEL_SHIMS_DIR)\__init__.py" "$(OUTPUT_DIR)\__init__.py" >NUL - @copy /Y "$(MODEL_SHIMS_DIR)\_enums.py" "$(OUTPUT_DIR)\_enums.py" >NUL - @copy /Y "$(MODEL_SHIMS_DIR)\_models.py" "$(OUTPUT_DIR)\_models.py" >NUL - @copy /Y "$(MODEL_SHIMS_DIR)\_patch.py" "$(OUTPUT_DIR)\_patch.py" >NUL - @copy /Y "$(MODEL_SHIMS_DIR)\models_patch.py" "$(OUTPUT_DIR)\sdk\models\models\_patch.py" >NUL - @REM Patch _deserialize_sequence: reject plain strings so union falls through to str branch - @powershell -Command "(Get-Content '$(MODEL_BASE)') -replace 'return type\(obj\)\(_deserialize\(deserializer, entry, module\) for entry in obj\)','if isinstance(obj, str):\n raise DeserializationError()\n return type(obj)(_deserialize(deserializer, entry, module) for entry in obj)' | Set-Content '$(MODEL_BASE)'" - @if exist "$(TEMP_OUTPUT_DIR)" rmdir /s /q "$(TEMP_OUTPUT_DIR)" + python _scripts\write_extension_model_shims.py --local-generated-root "$(OUTPUT_DIR)" else generate-models: @command -v tsp-client >/dev/null 2>&1 || { \ @@ -127,37 +106,10 @@ generate-models: echo "Run 'make install-typespec-deps' to install it." >&2; \ exit 1; \ } - @command -v npm >/dev/null 2>&1 || { \ - echo "Error: npm is required. Install Node.js (v18+) from https://nodejs.org/" >&2; \ - exit 1; \ - } - @echo "Syncing upstream TypeSpec sources..." - cd $(TYPESPEC_DIR) && tsp-client sync - @echo "Installing TypeSpec dependencies from emitter-package.json..." - cd $(TEMP_TSP_DIR) && npm install --silent - @echo "Generating Python models..." + @echo "Generating extension-owned OpenAI Responses models..." + $(MAKE) -C $(EXTENSION_OPENAI_DIR) generate-responses-models rm -rf $(OUTPUT_DIR) - cd $(TEMP_TSP_DIR) && npx tsp compile sdk-service-agentserver-contracts/client.tsp --emit @azure-tools/typespec-python --option "@azure-tools/typespec-python.emitter-output-dir=$(abspath $(TEMP_OUTPUT_DIR))" - @test -d $(MODEL_PACKAGE_DIR) || { \ - echo "Error: generated model package was not found." >&2; \ - exit 1; \ - } - mkdir -p $(OUTPUT_DIR)/sdk - cp -R $(MODEL_PACKAGE_DIR) $(OUTPUT_DIR)/sdk/models - rm -rf $(OUTPUT_DIR)/sdk/models/aio - rm -rf $(OUTPUT_DIR)/sdk/models/operations - rm -f $(OUTPUT_DIR)/sdk/models/_client.py - rm -f $(OUTPUT_DIR)/sdk/models/_configuration.py - rm -f $(OUTPUT_DIR)/sdk/models/_version.py - cp $(MODEL_SHIMS_DIR)/sdk_models__init__.py $(OUTPUT_DIR)/sdk/models/__init__.py - cp $(MODEL_SHIMS_DIR)/__init__.py $(OUTPUT_DIR)/__init__.py - cp $(MODEL_SHIMS_DIR)/_enums.py $(OUTPUT_DIR)/_enums.py - cp $(MODEL_SHIMS_DIR)/_models.py $(OUTPUT_DIR)/_models.py - cp $(MODEL_SHIMS_DIR)/_patch.py $(OUTPUT_DIR)/_patch.py - cp $(MODEL_SHIMS_DIR)/models_patch.py $(OUTPUT_DIR)/sdk/models/models/_patch.py - # Patch _deserialize_sequence: reject plain strings so union falls through to str branch - sed -i 's/ return type(obj)(_deserialize(deserializer, entry, module) for entry in obj)/ if isinstance(obj, str):\n raise DeserializationError()\n return type(obj)(_deserialize(deserializer, entry, module) for entry in obj)/' $(MODEL_BASE) - rm -rf $(TEMP_OUTPUT_DIR) + python _scripts/write_extension_model_shims.py --local-generated-root "$(OUTPUT_DIR)" endif # -------------------------------------------------------------------------- diff --git a/sdk/agentserver/azure-ai-agentserver-responses/_scripts/generated_shims/__init__.py b/sdk/agentserver/azure-ai-agentserver-responses/_scripts/generated_shims/__init__.py deleted file mode 100644 index b783bfa73795..000000000000 --- a/sdk/agentserver/azure-ai-agentserver-responses/_scripts/generated_shims/__init__.py +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT license. -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- - -"""Compatibility re-exports for generated models preserved under sdk/models.""" - -from .sdk.models.models import * # type: ignore # noqa: F401,F403 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/_scripts/generated_shims/_enums.py b/sdk/agentserver/azure-ai-agentserver-responses/_scripts/generated_shims/_enums.py deleted file mode 100644 index 481d6d628755..000000000000 --- a/sdk/agentserver/azure-ai-agentserver-responses/_scripts/generated_shims/_enums.py +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT license. -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- - -"""Compatibility shim for generated enum symbols.""" - -from .sdk.models.models._enums import * # type: ignore # noqa: F401,F403 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/_scripts/generated_shims/_models.py b/sdk/agentserver/azure-ai-agentserver-responses/_scripts/generated_shims/_models.py deleted file mode 100644 index 01e649adb824..000000000000 --- a/sdk/agentserver/azure-ai-agentserver-responses/_scripts/generated_shims/_models.py +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT license. -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- - -"""Compatibility shim for generated model symbols.""" - -from .sdk.models.models._models import * # type: ignore # noqa: F401,F403 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/_scripts/generated_shims/_patch.py b/sdk/agentserver/azure-ai-agentserver-responses/_scripts/generated_shims/_patch.py deleted file mode 100644 index 66ee2dea3a63..000000000000 --- a/sdk/agentserver/azure-ai-agentserver-responses/_scripts/generated_shims/_patch.py +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT license. -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- - -"""Compatibility shim for generated patch helpers.""" - -from .sdk.models.models._patch import * # type: ignore # noqa: F401,F403 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/_scripts/generated_shims/models_patch.py b/sdk/agentserver/azure-ai-agentserver-responses/_scripts/generated_shims/models_patch.py deleted file mode 100644 index 9f85da657361..000000000000 --- a/sdk/agentserver/azure-ai-agentserver-responses/_scripts/generated_shims/models_patch.py +++ /dev/null @@ -1,225 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Hand-written customizations injected into the generated models package. - -This file is copied over the generated ``_patch.py`` inside -``sdk/models/models/`` by ``make generate-models``. Anything listed in -``__all__`` is automatically re-exported by the generated ``__init__.py``, -shadowing the generated class of the same name. - -Approach follows the official customization guide: -https://aka.ms/azsdk/python/dpcodegen/python/customize -""" - -from enum import Enum -from typing import TYPE_CHECKING, Any, Optional - -from azure.core import CaseInsensitiveEnumMeta - -from .._utils.model_base import rest_field -from ._models import CreateResponse as CreateResponseGenerated -from ._models import ResponseObject as ResponseObjectGenerated -from ._models import ToolChoiceAllowed as ToolChoiceAllowedGenerated - -if TYPE_CHECKING: - from ._models import OutputItem - -_VISIBILITY = ["read", "create", "update", "delete", "query"] - - -class ResponseIncompleteReason(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Reason a response finished as incomplete. - - The upstream TypeSpec defines this as an inline literal union - (``"max_output_tokens" | "content_filter"``), so the code generator - emits ``Literal[...]`` instead of a named enum. This hand-written - enum provides a friendlier symbolic constant for SDK consumers. - """ - - MAX_OUTPUT_TOKENS = "max_output_tokens" - """The response was cut short because the maximum output token limit was reached.""" - CONTENT_FILTER = "content_filter" - """The response was cut short because of a content filter.""" - - -# --------------------------------------------------------------------------- -# Fix temperature / top_p types: numeric → float (emitter bug workaround) -# -# The upstream TypeSpec defines temperature and top_p as ``numeric | null`` -# (the abstract base scalar for all numbers). The TypeSpec emitter correctly -# maps this to ``double?`` but @azure-tools/typespec-python@0.61.2 maps -# ``numeric`` → ``int``. The OpenAPI 3 spec emits ``type: number`` -# (i.e. float), so ``int`` is wrong. -# -# Per the official customization guide we subclass the generated models and -# re-declare the affected fields with the correct type. The generated -# ``__init__.py`` picks up these subclasses via ``from ._patch import *`` -# which shadows the generated names. -# -# Additionally, we override fields whose generated docstrings contain -# duplicate RST link targets (``Learn more``) or malformed bullet lists -# that break ``sphinx-build -W``. -# --------------------------------------------------------------------------- - -# -- Docstrings for fields with "Learn more" links -------------------------- -# RST named hyperlinks (single trailing ``_``) must be unique per page. -# Because CreateResponse and ResponseObject both share these fields, and -# both appear on the same Sphinx page, the identical "Learn more" targets -# collide. Anonymous hyperlinks (double ``__``) avoid the conflict. - - -class CreateResponse(CreateResponseGenerated): - """Override generated ``CreateResponse`` to correct temperature/top_p types.""" - - temperature: Optional[float] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """Sampling temperature. Float between 0 and 2.""" - top_p: Optional[float] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """Nucleus sampling parameter. Float between 0 and 1.""" - user: Optional[str] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """This field is being replaced by ``safety_identifier`` and - ``prompt_cache_key``. Use ``prompt_cache_key`` instead to maintain - caching optimizations. A stable identifier for your end-users. - Used to boost cache hit rates by better bucketing similar requests - and to help OpenAI detect and prevent abuse. - `Learn more `__.""" - safety_identifier: Optional[str] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """A stable identifier used to help detect users of your application - that may be violating OpenAI's usage policies. The IDs should be a - string that uniquely identifies each user. We recommend hashing - their username or email address, in order to avoid sending us any - identifying information. - `Learn more `__.""" - prompt_cache_key: Optional[str] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """Used by OpenAI to cache responses for similar requests to optimize - your cache hit rates. Replaces the ``user`` field. - `Learn more `__.""" - - -class ResponseObject(ResponseObjectGenerated): - """Override generated ``ResponseObject`` to correct temperature/top_p types - and fix Sphinx docstring warnings.""" - - temperature: Optional[float] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """Sampling temperature. Float between 0 and 2.""" - top_p: Optional[float] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """Nucleus sampling parameter. Float between 0 and 1.""" - output: list["OutputItem"] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """An array of content items generated by the model. - - * The length and order of items in the ``output`` array is dependent - on the model's response. - * Rather than accessing the first item in the ``output`` array and - assuming it's an ``assistant`` message with the content generated by - the model, you might consider using the ``output_text`` property where - supported in SDKs. - - Required.""" - user: Optional[str] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """This field is being replaced by ``safety_identifier`` and - ``prompt_cache_key``. Use ``prompt_cache_key`` instead to maintain - caching optimizations. A stable identifier for your end-users. - Used to boost cache hit rates by better bucketing similar requests - and to help OpenAI detect and prevent abuse. - `Learn more `__.""" - safety_identifier: Optional[str] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """A stable identifier used to help detect users of your application - that may be violating OpenAI's usage policies. The IDs should be a - string that uniquely identifies each user. We recommend hashing - their username or email address, in order to avoid sending us any - identifying information. - `Learn more `__.""" - prompt_cache_key: Optional[str] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """Used by OpenAI to cache responses for similar requests to optimize - your cache hit rates. Replaces the ``user`` field. - `Learn more `__.""" - - -class ToolChoiceAllowed(ToolChoiceAllowedGenerated): - """Override generated ``ToolChoiceAllowed`` to fix Sphinx code-block warning.""" - - tools: list[dict[str, Any]] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """A list of tool definitions that the model should be allowed to call. - For the Responses API, the list of tool definitions might look like: - - .. code-block:: json - - [ - { "type": "function", "name": "get_weather" }, - { "type": "mcp", "server_label": "deepwiki" }, - { "type": "image_generation" } - ] - - Required.""" - - -__all__: list[str] = [ - "ResponseIncompleteReason", - "CreateResponse", - "ResponseObject", - "ToolChoiceAllowed", -] - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ - # Fix IncludeEnum docstring — bullet list continuation lines need proper - # indentation so that Sphinx doesn't emit "Bullet list ends without a - # blank line; unexpected unindent" warnings. - from ._enums import IncludeEnum - - IncludeEnum.__doc__ = ( - "Specify additional output data to include in the model response." - " Currently supported values are:\n" - "\n" - "* ``web_search_call.action.sources``: Include the sources of the" - " web search tool call.\n" - "* ``code_interpreter_call.outputs``: Includes the outputs of python" - " code execution in code interpreter tool call items.\n" - "* ``computer_call_output.output.image_url``: Include image urls" - " from the computer call output.\n" - "* ``file_search_call.results``: Include the search results of the" - " file search tool call.\n" - "* ``message.input_image.image_url``: Include image urls from the" - " input message.\n" - "* ``message.output_text.logprobs``: Include logprobs with assistant" - " messages.\n" - "* ``reasoning.encrypted_content``: Includes an encrypted version" - " of reasoning tokens in reasoning item outputs. This enables" - " reasoning items to be used in multi-turn conversations when using" - " the Responses API statelessly (like when the ``store`` parameter" - " is set to ``false``, or when an organization is enrolled in the" - " zero data retention program).\n" - ) - - # Fix duplicate "Learn more about built-in tools" RST targets. - # Multiple ToolChoice* classes share the same named hyperlink which causes - # "Duplicate explicit target name" warnings. Use anonymous hyperlinks. - from ._models import ( - ToolChoiceCodeInterpreter, - ToolChoiceComputerUsePreview, - ToolChoiceFileSearch, - ToolChoiceImageGeneration, - ToolChoiceWebSearchPreview, - ToolChoiceWebSearchPreview20250311, - ) - - for cls in ( - ToolChoiceCodeInterpreter, - ToolChoiceComputerUsePreview, - ToolChoiceFileSearch, - ToolChoiceImageGeneration, - ToolChoiceWebSearchPreview, - ToolChoiceWebSearchPreview20250311, - ): - # Only patch the first paragraph (class docstring), keep :ivar lines. - original = cls.__doc__ or "" - if "`Learn more about" in original: - cls.__doc__ = original.replace("`_.", "`__.") diff --git a/sdk/agentserver/azure-ai-agentserver-responses/_scripts/generated_shims/sdk_models__init__.py b/sdk/agentserver/azure-ai-agentserver-responses/_scripts/generated_shims/sdk_models__init__.py deleted file mode 100644 index 9abd30ab9c84..000000000000 --- a/sdk/agentserver/azure-ai-agentserver-responses/_scripts/generated_shims/sdk_models__init__.py +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT license. -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- - -"""Model-only generated package surface.""" - -from .models import * # type: ignore # noqa: F401,F403 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/_scripts/validation-overlay.yaml b/sdk/agentserver/azure-ai-agentserver-responses/_scripts/validation-overlay.yaml index 35c649563613..0a23724b57d1 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/_scripts/validation-overlay.yaml +++ b/sdk/agentserver/azure-ai-agentserver-responses/_scripts/validation-overlay.yaml @@ -39,6 +39,11 @@ schemas: Item: default_discriminator: "message" + # OpenAI input function_call items require type/call_id/name/arguments, but + # not the output-item id assigned by the server. + ItemFunctionToolCall: + not_required: ["id"] + # GAP-03: OpenAI spec InputImageContentParamAutoParam only requires [type]. # The "detail" field is nullable/optional and defaults to "auto". MessageContentInputImageContent: diff --git a/sdk/agentserver/azure-ai-agentserver-responses/_scripts/validator_emitter.py b/sdk/agentserver/azure-ai-agentserver-responses/_scripts/validator_emitter.py index a5008b79918d..11b56e6df85a 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/_scripts/validator_emitter.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/_scripts/validator_emitter.py @@ -56,14 +56,26 @@ def build_validator_module(schemas: dict[str, dict[str, Any]], roots: list[str]) ordered_schemas = _ordered(schemas) target_roots = sorted(dict.fromkeys(roots)) if roots else sorted(ordered_schemas) - lines: list[str] = [_header(), "", "from __future__ import annotations", "", "from typing import Any", ""] + lines: list[str] = [_header(), "", "from __future__ import annotations", "", "from typing import Any, get_args", ""] lines.extend( [ + "try:", + " from azure.ai.extensions.openai import responses as _response_types", + "except Exception:", + " _response_types = None", + "", "try:", " from . import _enums as _generated_enums", "except Exception:", " _generated_enums = None", "", + "_LITERAL_ENUM_ALIASES = {", + " 'ServiceTier': 'ServiceTierEnum',", + "}", + "_LITERAL_ENUM_VALUES = {", + " 'Verbosity': ('low', 'medium', 'high'),", + "}", + "", "def _append_error(errors: list[dict[str, str]], path: str, message: str) -> None:", " errors.append({'path': path, 'message': message})", "", @@ -103,6 +115,14 @@ def build_validator_module(schemas: dict[str, dict[str, Any]], roots: list[str]) ' _append_error(errors, path, f"Expected {expected}, got {_type_label(value)}")', "", "def _enum_values(enum_name: str) -> tuple[tuple[str, ...] | None, str | None]:", + " if enum_name in _LITERAL_ENUM_VALUES:", + " return _LITERAL_ENUM_VALUES[enum_name], None", + " if _response_types is not None:", + " alias_name = _LITERAL_ENUM_ALIASES.get(enum_name, enum_name)", + " literal_alias = getattr(_response_types, alias_name, None)", + " literal_values = get_args(literal_alias)", + " if literal_values:", + " return tuple(str(value) for value in literal_values), None", " if _generated_enums is None:", " return None, f'enum type _enums.{enum_name} is unavailable'", " enum_cls = getattr(_generated_enums, enum_name, None)", diff --git a/sdk/agentserver/azure-ai-agentserver-responses/_scripts/write_extension_model_shims.py b/sdk/agentserver/azure-ai-agentserver-responses/_scripts/write_extension_model_shims.py new file mode 100644 index 000000000000..d42103cbd31f --- /dev/null +++ b/sdk/agentserver/azure-ai-agentserver-responses/_scripts/write_extension_model_shims.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. +"""Write local compatibility shims for extension-owned Responses models.""" + +from __future__ import annotations + +import argparse +from pathlib import Path + + +COPYRIGHT = "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n" +EXTENSION_ROOT = "azure.ai.extensions.openai.responses._generated.sdk.models" + + +def _write(path: Path, content: str) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content, encoding="utf-8") + + +def _shim(module: str, description: str = "Compatibility re-export for extension-owned OpenAI Responses models.") -> str: + return ( + COPYRIGHT + + f'"""{description}"""\n\n' + + f"from {EXTENSION_ROOT}{module} import * # type: ignore # noqa: F401,F403\n" + ) + + +def write_shims(local_generated_root: Path) -> None: + _write(local_generated_root / "__init__.py", _shim("", "Compatibility package for extension-owned OpenAI Responses models.")) + _write(local_generated_root / "types.py", _shim(".types")) + _write(local_generated_root / "_unions.py", _shim("._unions")) + _write(local_generated_root / "_types.py", _shim("._types")) + _write(local_generated_root / "_patch.py", _shim("._patch")) + _write(local_generated_root / "_utils" / "__init__.py", _shim("._utils")) + _write(local_generated_root / "_utils" / "model_base.py", _shim("._utils.model_base")) + _write(local_generated_root / "_utils" / "serialization.py", _shim("._utils.serialization")) + _write(local_generated_root / "models" / "_patch.py", _shim(".models._patch")) + _write(local_generated_root / "models" / "_enums.py", _shim(".models._enums")) + _write(local_generated_root / "models" / "_models.py", _shim(".models._models")) + _write( + local_generated_root / "models" / "__init__.py", + COPYRIGHT + + '"""Compatibility re-export for extension-owned OpenAI Responses model classes."""\n\n' + + f"from {EXTENSION_ROOT}.models import * # type: ignore # noqa: F401,F403\n\n" + + "try:\n" + + f" from {EXTENSION_ROOT}.models import __all__ # type: ignore # noqa: F401\n" + + "except ImportError:\n" + + " __all__: list[str] = []\n", + ) + _write(local_generated_root / "py.typed", "") + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--local-generated-root", type=Path, required=True) + args = parser.parse_args() + write_shims(args.local_generated_root) + + +if __name__ == "__main__": + main() diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/_id_generator.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/_id_generator.py index e5f23a74b7b5..6bb86b5d3456 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/_id_generator.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/_id_generator.py @@ -6,9 +6,8 @@ import base64 import secrets -from typing import Callable, Sequence - -from .models import _generated as generated_models +from collections.abc import Mapping +from typing import Any, Sequence class IdGenerator: # pylint: disable=too-many-public-methods @@ -349,55 +348,56 @@ def new_output_message_item_id(partition_key_hint: str | None = "") -> str: return IdGenerator.new_id("om", partition_key_hint) @staticmethod - def new_item_id(item: generated_models.Item, partition_key_hint: str | None = "") -> str | None: - """Generate a type-specific ID for a generated Item subtype. + def new_item_id(item: Mapping[str, Any], partition_key_hint: str | None = "") -> str | None: + """Generate a type-specific ID for an item wire payload. - Dispatches to the appropriate ``new_*_item_id`` factory method based on the - runtime type of *item*. Returns None for ``ItemReferenceParam`` or unrecognized types. + Dispatches to the appropriate ``new_*_item_id`` factory method based on + the item ``type`` discriminator. Returns ``None`` for item references or + unrecognized payloads. - :param item: The generated Item instance to create an ID for. - :type item: generated_models.Item + :param item: The item wire payload to create an ID for. + :type item: Mapping[str, Any] :param partition_key_hint: An existing ID from which to extract the partition key for co-location. Defaults to an empty string. :type partition_key_hint: str | None :returns: A new unique ID string, or None if the item type is a reference or unrecognized. :rtype: str | None """ - dispatch_map: tuple[tuple[type[object], Callable[..., str]], ...] = ( - (generated_models.ItemMessage, IdGenerator.new_message_item_id), - (generated_models.ItemOutputMessage, IdGenerator.new_output_message_item_id), - (generated_models.ItemFunctionToolCall, IdGenerator.new_function_call_item_id), - (generated_models.FunctionCallOutputItemParam, IdGenerator.new_function_call_output_item_id), - (generated_models.ItemCustomToolCall, IdGenerator.new_custom_tool_call_item_id), - (generated_models.ItemCustomToolCallOutput, IdGenerator.new_custom_tool_call_output_item_id), - (generated_models.ItemComputerToolCall, IdGenerator.new_computer_call_item_id), - (generated_models.ComputerCallOutputItemParam, IdGenerator.new_computer_call_output_item_id), - (generated_models.ItemFileSearchToolCall, IdGenerator.new_file_search_call_item_id), - (generated_models.ItemWebSearchToolCall, IdGenerator.new_web_search_call_item_id), - (generated_models.ItemImageGenToolCall, IdGenerator.new_image_gen_call_item_id), - (generated_models.ItemCodeInterpreterToolCall, IdGenerator.new_code_interpreter_call_item_id), - (generated_models.ItemLocalShellToolCall, IdGenerator.new_local_shell_call_item_id), - (generated_models.ItemLocalShellToolCallOutput, IdGenerator.new_local_shell_call_output_item_id), - (generated_models.FunctionShellCallItemParam, IdGenerator.new_function_shell_call_item_id), - (generated_models.FunctionShellCallOutputItemParam, IdGenerator.new_function_shell_call_output_item_id), - (generated_models.ApplyPatchToolCallItemParam, IdGenerator.new_apply_patch_call_item_id), - (generated_models.ApplyPatchToolCallOutputItemParam, IdGenerator.new_apply_patch_call_output_item_id), - (generated_models.ItemMcpListTools, IdGenerator.new_mcp_list_tools_item_id), - (generated_models.ItemMcpToolCall, IdGenerator.new_mcp_call_item_id), - (generated_models.ItemMcpApprovalRequest, IdGenerator.new_mcp_approval_request_item_id), - (generated_models.MCPApprovalResponse, IdGenerator.new_mcp_approval_response_item_id), - (generated_models.ItemReasoningItem, IdGenerator.new_reasoning_item_id), - (generated_models.CompactionSummaryItemParam, IdGenerator.new_compaction_item_id), - (generated_models.StructuredOutputsOutputItem, IdGenerator.new_structured_output_item_id), - ) - - for model_type, generator in dispatch_map: - if isinstance(item, model_type): - return generator(partition_key_hint) - - if isinstance(item, generated_models.ItemReferenceParam): + discriminator_dispatch = { + "message": IdGenerator.new_message_item_id, + "output_message": IdGenerator.new_output_message_item_id, + "function_call": IdGenerator.new_function_call_item_id, + "function_call_output": IdGenerator.new_function_call_output_item_id, + "custom_tool_call": IdGenerator.new_custom_tool_call_item_id, + "custom_tool_call_output": IdGenerator.new_custom_tool_call_output_item_id, + "computer_call": IdGenerator.new_computer_call_item_id, + "computer_call_output": IdGenerator.new_computer_call_output_item_id, + "file_search_call": IdGenerator.new_file_search_call_item_id, + "web_search_call": IdGenerator.new_web_search_call_item_id, + "image_generation_call": IdGenerator.new_image_gen_call_item_id, + "code_interpreter_call": IdGenerator.new_code_interpreter_call_item_id, + "local_shell_call": IdGenerator.new_local_shell_call_item_id, + "local_shell_call_output": IdGenerator.new_local_shell_call_output_item_id, + "shell_call": IdGenerator.new_function_shell_call_item_id, + "shell_call_output": IdGenerator.new_function_shell_call_output_item_id, + "apply_patch_call": IdGenerator.new_apply_patch_call_item_id, + "apply_patch_call_output": IdGenerator.new_apply_patch_call_output_item_id, + "mcp_list_tools": IdGenerator.new_mcp_list_tools_item_id, + "mcp_call": IdGenerator.new_mcp_call_item_id, + "mcp_approval_request": IdGenerator.new_mcp_approval_request_item_id, + "mcp_approval_response": IdGenerator.new_mcp_approval_response_item_id, + "reasoning": IdGenerator.new_reasoning_item_id, + "compaction": IdGenerator.new_compaction_item_id, + "compaction_summary": IdGenerator.new_compaction_item_id, + "structured_outputs": IdGenerator.new_structured_output_item_id, + } + if not isinstance(item, Mapping): return None - return None + item_type = item.get("type") + if item_type is None and ("role" in item or "content" in item): + item_type = "message" + generator = discriminator_dispatch.get(str(item_type or "")) + return generator(partition_key_hint) if generator else None @staticmethod def extract_partition_key(id_value: str) -> str: diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/_response_context.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/_response_context.py index 3072bc3c5488..321e67886726 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/_response_context.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/_response_context.py @@ -7,17 +7,11 @@ from datetime import datetime, timezone from typing import TYPE_CHECKING, Any, Sequence -from azure.ai.agentserver.responses.models._generated.sdk.models._types import InputParam - -from .models._generated import ( - CreateResponse, - Item, - ItemMessage, - ItemReferenceParam, - MessageContentInputTextContent, - OutputItem, -) -from .models._helpers import get_input_expanded, to_item, to_output_item +from azure.ai.extensions.openai import get_field as _get_field +from azure.ai.extensions.openai import is_type as _is_wire_type +from azure.ai.extensions.openai.responses import CreateResponse, InputParam, Item, ItemReferenceParam, OutputItem + +from .models._helpers import get_input_expanded, is_item_reference, to_item, to_output_item from .models.runtime import ResponseModeFlags if TYPE_CHECKING: @@ -144,12 +138,11 @@ async def get_input_text(self, *, resolve_references: bool = True) -> str: items = await self.get_input_items(resolve_references=resolve_references) texts: list[str] = [] for item in items: - if isinstance(item, ItemMessage): - for part in getattr(item, "content", None) or []: - if isinstance(part, MessageContentInputTextContent): - text = getattr(part, "text", None) - if text is not None: - texts.append(text) + if _is_wire_type(item, "message") or _get_field(item, "content") is not None: + for part in _get_field(item, "content") or []: + text = _get_field(part, "text") + if text is not None: + texts.append(text) return "\n".join(texts) async def _get_input_items_for_persistence(self) -> Sequence[OutputItem]: @@ -190,8 +183,8 @@ async def _get_input_items_resolved(self) -> Sequence[Item]: results: list[Item | None] = [] for item in expanded: - if isinstance(item, ItemReferenceParam): - reference_ids.append(item.id) + if is_item_reference(item): + reference_ids.append(str(item["id"])) reference_positions.append(len(results)) results.append(None) # placeholder else: diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_endpoint_handler.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_endpoint_handler.py index 0f9cbfe39ee6..3ec05af18dfb 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_endpoint_handler.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_endpoint_handler.py @@ -21,6 +21,8 @@ from starlette.requests import Request from starlette.responses import JSONResponse, Response, StreamingResponse +from azure.ai.extensions.openai import to_wire_dict + from azure.ai.agentserver.core import ( # pylint: disable=import-error,no-name-in-module FoundryAgentRequestContext, flush_spans, @@ -34,7 +36,7 @@ USER_ID, ) from azure.ai.agentserver.core._request_id import REQUEST_ID_STATE_KEY # pylint: disable=import-error,no-name-in-module -from azure.ai.agentserver.responses.models._generated import ( +from azure.ai.extensions.openai.responses import ( AgentReference, CreateResponse, ResponseStreamEventType, @@ -104,6 +106,10 @@ logger = logging.getLogger("azure.ai.agentserver") +def _json_snapshot(snapshot: dict[str, Any]) -> dict[str, Any]: + return to_wire_dict(snapshot) + + def _extract_platform_context(request: Request) -> PlatformContext: """Build a ``PlatformContext`` from platform-injected request headers. @@ -323,7 +329,7 @@ def _session_headers(self, session_id: str | None = None) -> dict[str, str]: :rtype: dict[str, str] """ sid = session_id or (getattr(getattr(self._host, "config", None), "session_id", "") or "") - headers = dict(self._response_headers) + headers = self._response_headers.copy() if sid: headers[SESSION_ID] = sid return headers @@ -387,15 +393,15 @@ def _build_execution_context( ``context`` field already set. :rtype: _ExecutionContext """ - stream = bool(getattr(parsed, "stream", False)) - store = True if getattr(parsed, "store", None) is None else bool(parsed.store) - background = bool(getattr(parsed, "background", False)) - model = getattr(parsed, "model", None) or "" + stream = bool(parsed.get("stream", False)) + store = True if parsed.get("store") is None else bool(parsed["store"]) + background = bool(parsed.get("background", False)) + model = parsed.get("model") or "" _expanded = get_input_expanded(parsed) input_items = [out for item in _expanded if (out := to_output_item(item, response_id)) is not None] previous_response_id: str | None = ( - parsed.previous_response_id - if isinstance(parsed.previous_response_id, str) and parsed.previous_response_id + parsed["previous_response_id"] + if isinstance(parsed.get("previous_response_id"), str) and parsed.get("previous_response_id") else None ) conversation_id = _resolve_conversation_id(parsed) @@ -712,7 +718,11 @@ async def _iter_with_context(): # type: ignore[return] snapshot.get("status"), len(snapshot.get("output", [])), ) - return JSONResponse(snapshot, status_code=200, headers=self._session_headers(agent_session_id)) + return JSONResponse( + _json_snapshot(snapshot), + status_code=200, + headers=self._session_headers(agent_session_id), + ) except _HandlerError as exc: logger.error( "Handler error in sync create (response_id=%s)", @@ -744,7 +754,11 @@ async def _iter_with_context(): # type: ignore[return] ctx.response_id, snapshot.get("status"), ) - return JSONResponse(snapshot, status_code=200, headers=self._session_headers(agent_session_id)) + return JSONResponse( + _json_snapshot(snapshot), + status_code=200, + headers=self._session_headers(agent_session_id), + ) except _HandlerError as exc: logger.error("Handler error in create (response_id=%s)", ctx.response_id, exc_info=exc.original) # Handler errors are server-side faults, not client errors @@ -843,7 +857,7 @@ async def handle_get(self, request: Request) -> Response: # pylint: disable=too snapshot.get("status"), len(snapshot.get("output", [])), ) - return JSONResponse(snapshot, status_code=200, headers=_hdrs) + return JSONResponse(_json_snapshot(snapshot), status_code=200, headers=_hdrs) def _handle_get_stream( self, @@ -919,14 +933,14 @@ async def _handle_get_fallback( # pylint: disable=too-many-return-statements # (e.g., after a process restart). try: response_obj = await self._provider.get_response(response_id, context=_context) - snapshot = response_obj.as_dict() + snapshot = to_wire_dict(response_obj) logger.info( "Retrieved response %s: status=%s output_count=%d", response_id, snapshot.get("status"), len(snapshot.get("output", [])), ) - return JSONResponse(snapshot, status_code=200, headers=_hdrs) + return JSONResponse(_json_snapshot(snapshot), status_code=200, headers=_hdrs) except FoundryResourceNotFoundError: pass # Fall through to 404 below except FoundryBadRequestError as exc: @@ -960,9 +974,8 @@ async def _handle_get_fallback( # pylint: disable=too-many-return-statements # so use a combined message. try: persisted = await self._provider.get_response(response_id, context=_context) - persisted_dict = persisted.as_dict() # B2: SSE replay requires background mode. - if persisted_dict.get("background") is not True: + if persisted.get("background") is not True: return _invalid_mode( "This response cannot be streamed because it was not created with background=true.", _hdrs, @@ -1288,7 +1301,7 @@ async def handle_cancel(self, request: Request) -> Response: record.set_response_snapshot( build_cancelled_response(record.response_id, record.agent_reference, record.model) ) - return JSONResponse(_RuntimeState.to_snapshot(record), status_code=200, headers=_hdrs) + return JSONResponse(_json_snapshot(_RuntimeState.to_snapshot(record)), status_code=200, headers=_hdrs) return terminal_error # B11: initiate cancellation winddown @@ -1307,7 +1320,7 @@ async def handle_cancel(self, request: Request) -> Response: # Stamp mode flags so the provider fallback can enforce B1/B2 checks # after eager eviction removes the in-memory record. if record.response is not None: - record.response.background = record.mode_flags.background + record.response["background"] = record.mode_flags.background record.transition_to("cancelled") # Persist cancelled state to durable store (B11: cancellation always wins) @@ -1324,7 +1337,7 @@ async def handle_cancel(self, request: Request) -> Response: await self._runtime_state.try_evict(record.response_id) logger.info("Cancelled response %s, status=%s", response_id, snapshot.get("status")) - return JSONResponse(snapshot, status_code=200, headers=_hdrs) + return JSONResponse(_json_snapshot(snapshot), status_code=200, headers=_hdrs) async def _handle_cancel_fallback( self, @@ -1349,7 +1362,7 @@ async def _handle_cancel_fallback( """ try: response_obj = await self._provider.get_response(response_id, context=_context) - persisted = response_obj.as_dict() + persisted = to_wire_dict(response_obj) # B1: background check comes first — non-bg responses always # get the "synchronous" message regardless of terminal status. @@ -1364,7 +1377,7 @@ async def _handle_cancel_fallback( terminal_error = _check_cancel_terminal_status(stored_status, _hdrs) if terminal_error is not None: if stored_status == "cancelled": - return JSONResponse(persisted, status_code=200, headers=_hdrs) + return JSONResponse(_json_snapshot(persisted), status_code=200, headers=_hdrs) return terminal_error except FoundryResourceNotFoundError: pass # Fall through to 404 below @@ -1448,12 +1461,9 @@ async def handle_input_items(self, request: Request) -> Response: return _deleted_response(response_id, _hdrs) except KeyError: return _not_found(response_id, _hdrs) - ordered_items = items if order == "asc" else list(reversed(items)) - ordered_dicts: list[dict[str, Any]] = [ - item.as_dict() if hasattr(item, "as_dict") else cast("dict[str, Any]", item) for item in ordered_items - ] - scoped_items = _apply_item_cursors(ordered_dicts, after=after, before=before) + ordered_items = list(items) if order == "asc" else list(reversed(items)) + scoped_items = _apply_item_cursors(cast("list[dict[str, Any]]", ordered_items), after=after, before=before) page = scoped_items[:limit] has_more = len(scoped_items) > limit diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_event_subject.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_event_subject.py index 122aff1b2c4f..4c19cca444fd 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_event_subject.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_event_subject.py @@ -7,7 +7,7 @@ import asyncio # pylint: disable=do-not-import-asyncio from typing import AsyncIterator -from ..models._generated import ResponseStreamEvent +from azure.ai.extensions.openai.responses import ResponseStreamEvent class _ResponseEventSubject: @@ -37,7 +37,7 @@ def __init__(self) -> None: async def publish(self, event: ResponseStreamEvent) -> None: """Push a new event to all current subscribers and append it to the replay buffer. - :param event: The normalised event (``ResponseStreamEvent`` model instance). + :param event: The normalised event wire payload. :type event: ResponseStreamEvent """ async with self._lock: @@ -84,7 +84,7 @@ async def subscribe(self, cursor: int = -1) -> AsyncIterator[ResponseStreamEvent item = await q.get() if item is self._DONE: return - assert isinstance(item, ResponseStreamEvent) + assert isinstance(item, dict) and isinstance(item.get("type"), str) yield item finally: # Clean up subscription on client disconnect or normal completion diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_execution_context.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_execution_context.py index 89e18252d305..49bcda4b7859 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_execution_context.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_execution_context.py @@ -7,8 +7,9 @@ import asyncio # pylint: disable=do-not-import-asyncio from typing import TYPE_CHECKING, Any +from azure.ai.extensions.openai.responses import AgentReference, CreateResponse, OutputItem + from .._response_context import ResponseContext -from ..models._generated import AgentReference, CreateResponse, OutputItem if TYPE_CHECKING: from ._observability import CreateSpan diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_observability.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_observability.py index 78fe4ef1f5e1..f7b3a5a969ce 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_observability.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_observability.py @@ -115,7 +115,7 @@ def end(self, error: BaseException | None = None) -> None: self._ended = True if self._hook is None: return - self._hook.on_span_end(self.name, dict(self.tags), error) + self._hook.on_span_end(self.name, self.tags.copy(), error) def start_create_span(name: str, tags: dict[str, Any], hook: CreateSpanHook | None = None) -> CreateSpan: @@ -130,9 +130,9 @@ def start_create_span(name: str, tags: dict[str, Any], hook: CreateSpanHook | No :return: The started ``CreateSpan`` instance. :rtype: CreateSpan """ - span = CreateSpan(name=name, tags=dict(tags), _hook=hook) + span = CreateSpan(name=name, tags=tags.copy(), _hook=hook) if hook is not None: - hook.on_span_start(name, dict(span.tags)) + hook.on_span_start(name, span.tags.copy()) return span @@ -316,7 +316,7 @@ def on_span_start(self, name: str, tags: dict[str, Any]) -> None: self.spans.append( RecordedSpan( name=name, - tags=dict(tags), + tags=tags.copy(), started_at=datetime.now(timezone.utc), ) ) @@ -337,6 +337,6 @@ def on_span_end(self, name: str, tags: dict[str, Any], error: BaseException | No self.on_span_start(name, tags) span = self.spans[-1] - span.tags = dict(tags) + span.tags = tags.copy() span.error = error span.ended_at = datetime.now(timezone.utc) diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_orchestrator.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_orchestrator.py index 999d5d641105..f45094d04737 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_orchestrator.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_orchestrator.py @@ -21,7 +21,7 @@ from azure.ai.agentserver.core._platform_headers import PLATFORM_ERROR_TAG # pylint: disable=import-error,no-name-in-module from .._options import ResponsesServerOptions -from ..models import _generated as generated_models +from azure.ai.extensions.openai import responses as response_models from ..models.runtime import ( ResponseExecution, ResponseModeFlags, @@ -49,7 +49,7 @@ if TYPE_CHECKING: from .._response_context import ResponseContext - from ..models._generated import AgentReference, CreateResponse + from azure.ai.extensions.openai.responses import AgentReference, CreateResponse logger = logging.getLogger("azure.ai.agentserver") @@ -62,8 +62,8 @@ async def _resolve_input_items_for_persistence( context: "ResponseContext | None", - fallback_items: list[generated_models.OutputItem] | None, -) -> list[generated_models.OutputItem] | None: + fallback_items: list[response_models.OutputItem] | None, +) -> list[response_models.OutputItem] | None: """Resolve ``item_reference`` inputs via the provider before persisting. When the caller's input includes ``ItemReferenceParam`` entries (references @@ -94,7 +94,7 @@ async def _resolve_input_items_for_persistence( return list(fallback_items) if fallback_items else None -def _check_first_event_contract(normalized: generated_models.ResponseStreamEvent, response_id: str) -> str | None: +def _check_first_event_contract(normalized: response_models.ResponseStreamEvent, response_id: str) -> str | None: """Return an error message if the first handler event violates FR-006/FR-007, else None. - FR-006: The first event MUST be ``response.created`` with matching ``id``. @@ -166,8 +166,8 @@ async def _iter_with_winddown( _OUTPUT_ITEM_EVENT_TYPES: frozenset[str] = frozenset( { - generated_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_ADDED.value, - generated_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_DONE.value, + response_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_ADDED.value, + response_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_DONE.value, } ) @@ -175,16 +175,16 @@ async def _iter_with_winddown( # Used by FR-008a output manipulation detection. _RESPONSE_SNAPSHOT_TYPES: frozenset[str] = frozenset( { - generated_models.ResponseStreamEventType.RESPONSE_IN_PROGRESS.value, - generated_models.ResponseStreamEventType.RESPONSE_COMPLETED.value, - generated_models.ResponseStreamEventType.RESPONSE_FAILED.value, - generated_models.ResponseStreamEventType.RESPONSE_INCOMPLETE.value, - generated_models.ResponseStreamEventType.RESPONSE_QUEUED.value, + response_models.ResponseStreamEventType.RESPONSE_IN_PROGRESS.value, + response_models.ResponseStreamEventType.RESPONSE_COMPLETED.value, + response_models.ResponseStreamEventType.RESPONSE_FAILED.value, + response_models.ResponseStreamEventType.RESPONSE_INCOMPLETE.value, + response_models.ResponseStreamEventType.RESPONSE_QUEUED.value, } ) -def _validate_handler_event(coerced: generated_models.ResponseStreamEvent) -> str | None: +def _validate_handler_event(coerced: response_models.ResponseStreamEvent) -> str | None: """Return an error message if a coerced handler event has invalid structure, else None. Lightweight structural checks (B30): @@ -208,7 +208,7 @@ def _validate_handler_event(coerced: generated_models.ResponseStreamEvent) -> st async def _run_background_non_stream( # pylint: disable=too-many-locals,too-many-branches *, - create_fn: Callable[..., AsyncIterator[generated_models.ResponseStreamEvent]], + create_fn: Callable[..., AsyncIterator[response_models.ResponseStreamEvent]], parsed: CreateResponse, context: ResponseContext, cancellation_signal: asyncio.Event, @@ -261,7 +261,7 @@ async def _run_background_non_stream( # pylint: disable=too-many-locals,too-man :rtype: None """ record.transition_to("in_progress") - handler_events: list[generated_models.ResponseStreamEvent] = [] + handler_events: list[response_models.ResponseStreamEvent] = [] validator = EventStreamValidator() output_item_count = 0 _provider_created = False # tracks whether create_response was called @@ -317,7 +317,7 @@ async def _run_background_non_stream( # pylint: disable=too-many-locals,too-man agent_session_id=agent_session_id, conversation_id=conversation_id, ) - record.set_response_snapshot(generated_models.ResponseObject(_initial_snapshot)) + record.set_response_snapshot(_initial_snapshot) # Honour the handler's initial status (e.g. "queued") so the # POST response body reflects what the handler actually set. _handler_initial_status = _initial_snapshot.get("status") @@ -327,7 +327,7 @@ async def _run_background_non_stream( # pylint: disable=too-many-locals,too-man if store and provider is not None: try: _context = context.platform_context if context else None - _response_obj = generated_models.ResponseObject(_initial_snapshot) + _response_obj = _initial_snapshot _history_ids = ( await provider.get_history_item_ids( record.previous_response_id, @@ -368,7 +368,7 @@ async def _run_background_non_stream( # pylint: disable=too-many-locals,too-man await asyncio.sleep(0) else: # Track output_item.added events for FR-008a - _item_added = generated_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_ADDED + _item_added = response_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_ADDED if normalized.get("type") == _item_added.value: output_item_count += 1 @@ -468,7 +468,7 @@ async def _run_background_non_stream( # pylint: disable=too-many-locals,too-man resolved_status = response_payload.get("status") if record.status != "cancelled": - record.set_response_snapshot(generated_models.ResponseObject(response_payload)) + record.set_response_snapshot(response_payload) target = resolved_status if isinstance(resolved_status, str) else "completed" # If still queued, transition through in_progress first so the # state machine stays valid (queued can only reach terminal @@ -483,7 +483,7 @@ async def _run_background_non_stream( # pylint: disable=too-many-locals,too-man # after eager eviction removes the in-memory record. This covers # all code paths (normal completion, handler failure, cancellation). if record.response is not None: - record.response.background = record.mode_flags.background + record.response["background"] = record.mode_flags.background # Persist terminal state update via provider (bg non-stream: update after runner completes) # §3.5: Persistence failure sets persistence_failed on the record and # replaces the snapshot with storage_error so GET returns the failure. @@ -631,12 +631,12 @@ class _PipelineState: ) def __init__(self) -> None: - self.handler_events: list[generated_models.ResponseStreamEvent] = [] + self.handler_events: list[response_models.ResponseStreamEvent] = [] self.bg_record: ResponseExecution | None = None self.captured_error: BaseException | None = None self.validator: EventStreamValidator = EventStreamValidator() self.stream_interrupted: bool = False - self.pending_terminal: generated_models.ResponseStreamEvent | None = None + self.pending_terminal: response_models.ResponseStreamEvent | None = None self.provider_created: bool = False @@ -652,16 +652,16 @@ class _ResponseOrchestrator: # pylint: disable=too-many-instance-attributes _TERMINAL_SSE_TYPES: frozenset[str] = frozenset( { - generated_models.ResponseStreamEventType.RESPONSE_COMPLETED.value, - generated_models.ResponseStreamEventType.RESPONSE_FAILED.value, - generated_models.ResponseStreamEventType.RESPONSE_INCOMPLETE.value, + response_models.ResponseStreamEventType.RESPONSE_COMPLETED.value, + response_models.ResponseStreamEventType.RESPONSE_FAILED.value, + response_models.ResponseStreamEventType.RESPONSE_INCOMPLETE.value, } ) def __init__( self, *, - create_fn: Callable[..., AsyncIterator[generated_models.ResponseStreamEvent]], + create_fn: Callable[..., AsyncIterator[response_models.ResponseStreamEvent]], runtime_state: _RuntimeState, runtime_options: ResponsesServerOptions, provider: ResponseProviderProtocol, @@ -694,8 +694,8 @@ async def _normalize_and_append( self, ctx: _ExecutionContext, state: _PipelineState, - handler_event: generated_models.ResponseStreamEvent | dict[str, Any], - ) -> generated_models.ResponseStreamEvent: + handler_event: response_models.ResponseStreamEvent | dict[str, Any], + ) -> response_models.ResponseStreamEvent: """Coerce, validate, normalise, and append a handler event to the pipeline state. Also propagates the event into the background record and its subject when active. @@ -738,7 +738,7 @@ async def _normalize_and_append( return normalized @staticmethod - def _has_terminal_event(handler_events: list[generated_models.ResponseStreamEvent]) -> bool: + def _has_terminal_event(handler_events: list[response_models.ResponseStreamEvent]) -> bool: """Return ``True`` if any terminal event has been emitted. :param handler_events: List of normalised handler events. @@ -750,7 +750,7 @@ def _has_terminal_event(handler_events: list[generated_models.ResponseStreamEven async def _cancel_terminal_sse_dict( self, ctx: _ExecutionContext, state: _PipelineState - ) -> generated_models.ResponseStreamEvent: + ) -> response_models.ResponseStreamEvent: """Build, normalise, append, and return a cancel-terminal event. Returns the normalised event (model instance) so that it can be consumed @@ -764,14 +764,14 @@ async def _cancel_terminal_sse_dict( :rtype: ResponseStreamEvent """ cancel_event: dict[str, Any] = { - "type": generated_models.ResponseStreamEventType.RESPONSE_FAILED.value, - "response": _build_cancelled_response(ctx.response_id, ctx.agent_reference, ctx.model).as_dict(), + "type": response_models.ResponseStreamEventType.RESPONSE_FAILED.value, + "response": _build_cancelled_response(ctx.response_id, ctx.agent_reference, ctx.model), } return await self._normalize_and_append(ctx, state, cancel_event) async def _make_failed_event( self, ctx: _ExecutionContext, state: _PipelineState - ) -> generated_models.ResponseStreamEvent: + ) -> response_models.ResponseStreamEvent: """Build, normalise, append, and return a ``response.failed`` event. Used for S-035 (handler exception after ``response.created``) and @@ -785,7 +785,7 @@ async def _make_failed_event( :rtype: ResponseStreamEvent """ failed_event: dict[str, Any] = { - "type": generated_models.ResponseStreamEventType.RESPONSE_FAILED.value, + "type": response_models.ResponseStreamEventType.RESPONSE_FAILED.value, "response": { "id": ctx.response_id, "object": "response", @@ -820,8 +820,8 @@ def _apply_storage_error_replacement( error_message=_STORAGE_ERROR_MESSAGE, ) replacement_event: dict[str, Any] = { - "type": generated_models.ResponseStreamEventType.RESPONSE_FAILED.value, - "response": storage_error_response.as_dict(), + "type": response_models.ResponseStreamEventType.RESPONSE_FAILED.value, + "response": storage_error_response, } # Determine the sequence_number: reuse the original pending terminal's @@ -859,7 +859,7 @@ def _apply_storage_error_replacement( async def _persist_and_resolve_terminal( self, ctx: _ExecutionContext, state: _PipelineState, record: ResponseExecution - ) -> generated_models.ResponseStreamEvent: + ) -> response_models.ResponseStreamEvent: """Attempt persistence and resolve the terminal event to yield. This method implements the buffer-then-persist-then-yield pattern: @@ -909,7 +909,7 @@ async def _persist_and_resolve_terminal( ) # Update snapshot on record before persistence attempt - record.set_response_snapshot(generated_models.ResponseObject(response_payload)) + record.set_response_snapshot(response_payload) record.transition_to(status) # Attempt persistence @@ -918,7 +918,7 @@ async def _persist_and_resolve_terminal( # Phase 1 already failed — skip persistence attempt, emit storage error directly. self._apply_storage_error_replacement(ctx, state, record) else: - record.response.background = record.mode_flags.background + record.response["background"] = record.mode_flags.background _context = ctx.context.platform_context if ctx.context else None try: if state.provider_created: @@ -939,7 +939,7 @@ async def _persist_and_resolve_terminal( ) _resolved_items = await _resolve_input_items_for_persistence(ctx.context, ctx.input_items) await self._provider.create_response( - generated_models.ResponseObject(response_payload), + response_payload, _resolved_items, _history_ids, context=_context, @@ -965,7 +965,7 @@ async def _persist_and_resolve_terminal( return state.pending_terminal async def _register_bg_execution( - self, ctx: _ExecutionContext, state: _PipelineState, first_normalized: generated_models.ResponseStreamEvent + self, ctx: _ExecutionContext, state: _PipelineState, first_normalized: response_models.ResponseStreamEvent ) -> None: """Create, seed, and register the background+stream execution record. @@ -1005,7 +1005,7 @@ async def _register_bg_execution( conversation_id=ctx.conversation_id, user_id_key=ctx.user_id, ) - execution.set_response_snapshot(generated_models.ResponseObject(initial_payload)) + execution.set_response_snapshot(initial_payload) execution.subject = _ResponseEventSubject() state.bg_record = execution assert state.bg_record.subject is not None @@ -1013,7 +1013,7 @@ async def _register_bg_execution( await self._runtime_state.add(execution) if ctx.store: _context = ctx.context.platform_context if ctx.context else None - _initial_response_obj = generated_models.ResponseObject(initial_payload) + _initial_response_obj = initial_payload _history_ids = ( await self._provider.get_history_item_ids( ctx.previous_response_id, @@ -1046,8 +1046,8 @@ async def _process_handler_events( # pylint: disable=too-many-return-statements self, ctx: _ExecutionContext, state: _PipelineState, - handler_iterator: AsyncIterator[generated_models.ResponseStreamEvent], - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + handler_iterator: AsyncIterator[response_models.ResponseStreamEvent], + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Shared event pipeline: coerce → normalise → apply_event → subject publish. This async generator is the single authoritative event pipeline consumed by @@ -1252,7 +1252,7 @@ async def _process_handler_events( # pylint: disable=too-many-return-statements # appended to the state machine before we emit response.failed. _pre_coerced = _coerce_handler_event(raw) _pre_type = _pre_coerced.get("type", "") - if _pre_type == generated_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_ADDED.value: + if _pre_type == response_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_ADDED.value: output_item_count += 1 if _pre_type in _RESPONSE_SNAPSHOT_TYPES: _pre_response = _pre_coerced.get("response") or {} @@ -1421,7 +1421,7 @@ async def _finalize_stream(self, ctx: _ExecutionContext, state: _PipelineState) conversation_id=ctx.conversation_id, user_id_key=ctx.user_id, ) - execution.set_response_snapshot(generated_models.ResponseObject(response_payload)) + execution.set_response_snapshot(response_payload) # Copy persistence_failed from the ephemeral record if one was used if state.bg_record is not None: execution.persistence_failed = state.bg_record.persistence_failed @@ -1722,7 +1722,7 @@ async def run_sync(self, ctx: _ExecutionContext) -> dict[str, Any]: conversation_id=ctx.conversation_id, user_id_key=ctx.user_id, ) - record.set_response_snapshot(generated_models.ResponseObject(response_payload)) + record.set_response_snapshot(response_payload) # Always register in runtime state so that cancel/GET can find the record # and return the correct status code (e.g., 400 for non-bg cancel). @@ -1734,7 +1734,7 @@ async def run_sync(self, ctx: _ExecutionContext) -> dict[str, Any]: # §3.1: Persistence failure replaces the response body with storage_error. try: _context = ctx.context.platform_context if ctx.context else None - _response_obj = generated_models.ResponseObject(response_payload) + _response_obj = response_payload _history_ids = ( await self._provider.get_history_item_ids( ctx.previous_response_id, diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_request_parsing.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_request_parsing.py index fb6aa0dbbb22..310e0c968906 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_request_parsing.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_request_parsing.py @@ -9,8 +9,10 @@ from copy import deepcopy from typing import Any, Mapping +from azure.ai.extensions.openai import get_field +from azure.ai.extensions.openai.responses import AgentReference, CreateResponse + from .._id_generator import IdGenerator -from ..models._generated import AgentReference, CreateResponse from ..models.errors import RequestValidationError _X_AGENT_RESPONSE_ID_HEADER = "x-agent-response-id" @@ -117,7 +119,7 @@ def _validate_response_id(response_id: str) -> None: def _normalize_agent_reference(value: Any) -> AgentReference | dict[str, Any]: - """Normalize an agent reference value into a validated model or empty dict. + """Normalize an agent reference value into a validated wire payload or empty dict. If *value* is ``None``, an empty dict is returned as a sentinel for "no agent_reference was provided". Callers use truthiness to detect @@ -125,7 +127,7 @@ def _normalize_agent_reference(value: Any) -> AgentReference | dict[str, Any]: :param value: Raw agent reference from the request (dict, model, or ``None``). :type value: Any - :return: An :class:`AgentReference` model instance, + :return: An :class:`AgentReference` wire payload, or ``{}`` when no agent_reference was provided. :rtype: AgentReference | dict[str, Any] :raises RequestValidationError: If the value is not a valid agent reference. @@ -133,17 +135,14 @@ def _normalize_agent_reference(value: Any) -> AgentReference | dict[str, Any]: if value is None: return {} - if hasattr(value, "as_dict"): - candidate = value.as_dict() - elif isinstance(value, dict): - candidate = dict(value) - else: + if not isinstance(value, dict): raise RequestValidationError( "agent_reference must be an object", code="invalid_request", param="agent_reference", ) + candidate = value.copy() candidate.setdefault("type", "agent_reference") name = candidate.get("name") reference_type = candidate.get("type") @@ -231,7 +230,7 @@ def _resolve_identity_fields( ``IdGenerator.new_response_id()``, using the ``previous_response_id`` or ``conversation`` ID as partition-key hint when available. - :param parsed: Parsed ``CreateResponse`` model instance. + :param parsed: Parsed ``CreateResponse`` wire payload. :type parsed: CreateResponse :keyword request_headers: HTTP request headers mapping. :keyword type request_headers: Mapping[str, str] | None @@ -248,12 +247,10 @@ def _resolve_identity_fields( if isinstance(raw_header, str) and raw_header.strip(): header_response_id = raw_header.strip() - parsed_mapping = parsed.as_dict() if hasattr(parsed, "as_dict") else {} - if header_response_id: response_id = header_response_id else: - explicit_response_id = parsed_mapping.get("response_id") or getattr(parsed, "response_id", None) + explicit_response_id = parsed.get("response_id") if isinstance(explicit_response_id, str) and explicit_response_id.strip(): response_id = explicit_response_id.strip() else: @@ -261,37 +258,30 @@ def _resolve_identity_fields( # for co-locating related response IDs in the same partition. # previous_response_id takes priority because it directly chains # responses, while conversation ID groups them more loosely. - partition_hint = parsed_mapping.get("previous_response_id") or _resolve_conversation_id(parsed) or "" + partition_hint = parsed.get("previous_response_id") or _resolve_conversation_id(parsed) or "" response_id = IdGenerator.new_response_id(partition_hint) _validate_response_id(response_id) - agent_reference = _normalize_agent_reference( - parsed_mapping.get("agent_reference") - if isinstance(parsed_mapping, dict) - else getattr(parsed, "agent_reference", None) - ) + agent_reference = _normalize_agent_reference(parsed.get("agent_reference")) return response_id, agent_reference def _resolve_conversation_id(parsed: CreateResponse) -> str | None: """Extract the conversation ID from a parsed ``CreateResponse`` request. - Handles both a plain string value and a ``ConversationParam_2`` object - (which carries the ID in its ``.id`` attribute). + Handles both a plain string value and a ``ConversationParam_2`` wire payload. - :param parsed: The parsed ``CreateResponse`` model instance. + :param parsed: The parsed ``CreateResponse`` wire payload. :type parsed: CreateResponse :returns: The conversation ID string, or ``None`` if not present. :rtype: str | None """ - raw = getattr(parsed, "conversation", None) + raw = parsed.get("conversation") if isinstance(raw, str): return raw or None if isinstance(raw, dict): cid = raw.get("id") return str(cid) if cid else None - if raw is not None and hasattr(raw, "id"): - return str(raw.id) or None return None @@ -313,7 +303,7 @@ def _resolve_session_id( where *partition_hint* is extracted from ``conversation_id`` or ``previous_response_id``. 4. Random 63-char lowercase hex (one-shot, no conversational context) - :param parsed: Parsed ``CreateResponse`` model instance. + :param parsed: Parsed ``CreateResponse`` wire payload. :type parsed: CreateResponse :param payload: Raw JSON payload dict. :type payload: dict[str, Any] @@ -327,7 +317,7 @@ def _resolve_session_id( :rtype: str """ # Priority 1: payload field - session_id = getattr(parsed, "agent_session_id", None) + session_id = parsed.get("agent_session_id") if not isinstance(session_id, str) or not session_id.strip(): # Also check the raw payload for when the field isn't in the model yet if isinstance(payload, dict): @@ -342,7 +332,7 @@ def _resolve_session_id( # Priority 3: deterministic derivation from conversation context conversation_id = _resolve_conversation_id(parsed) previous_response_id: str | None = None - raw_prev = getattr(parsed, "previous_response_id", None) + raw_prev = parsed.get("previous_response_id") if isinstance(raw_prev, str) and raw_prev.strip(): previous_response_id = raw_prev.strip() @@ -400,19 +390,15 @@ def _extract_agent_identity( ) -> tuple[str, str]: """Extract (agent_name, agent_version) from an agent reference. - :param agent_reference: Agent reference mapping or model instance. + :param agent_reference: Agent reference mapping. :type agent_reference: AgentReference | dict[str, Any] | None :returns: Tuple of (name, version) with fallback defaults. :rtype: tuple[str, str] """ if agent_reference is None: return _DEFAULT_AGENT_REFERENCE_NAME, "" - if isinstance(agent_reference, dict): - name = agent_reference.get("name") or _DEFAULT_AGENT_REFERENCE_NAME - version = agent_reference.get("version") or "" - return str(name), str(version) - name = getattr(agent_reference, "name", None) or _DEFAULT_AGENT_REFERENCE_NAME - version = getattr(agent_reference, "version", None) or "" + name = get_field(agent_reference, "name") or _DEFAULT_AGENT_REFERENCE_NAME + version = get_field(agent_reference, "version") or "" return str(name), str(version) diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_routing.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_routing.py index 4efe92b7c596..40a0344bd6d7 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_routing.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_routing.py @@ -20,11 +20,11 @@ AgentServerHost, build_server_version, ) +from azure.ai.extensions.openai.responses import CreateResponse, ResponseStreamEvent from .._options import ResponsesServerOptions from .._response_context import ResponseContext from .._version import VERSION as _RESPONSES_VERSION -from ..models._generated import CreateResponse, ResponseStreamEvent from ..store._base import ResponseProviderProtocol, ResponseStreamProviderProtocol from ..store._memory import InMemoryResponseProvider from ._endpoint_handler import _ResponseEndpointHandler @@ -42,14 +42,14 @@ """Type alias for the user-registered create-response handler function. The handler receives: -- ``request``: The parsed :class:`CreateResponse` model. +- ``request``: The parsed :class:`CreateResponse` wire payload. - ``context``: The :class:`ResponseContext` for the current request. - ``cancellation_signal``: An :class:`asyncio.Event` set when cancellation is requested. It must return one of: - A ``TextResponse`` for text-only responses (it implements ``AsyncIterable``). -- An ``AsyncIterable`` (async generator) of :class:`ResponseStreamEvent` instances. -- A synchronous ``Generator`` of :class:`ResponseStreamEvent` instances. +- An ``AsyncIterable`` (async generator) of :class:`ResponseStreamEvent` wire payloads. +- A synchronous ``Generator`` of :class:`ResponseStreamEvent` wire payloads. """ logger = logging.getLogger("azure.ai.agentserver") diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_runtime_state.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_runtime_state.py index 66faac3eb560..06a5e323b0e7 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_runtime_state.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_runtime_state.py @@ -8,7 +8,7 @@ from copy import deepcopy from typing import Any -from ..models._generated import OutputItem +from azure.ai.extensions.openai.responses import OutputItem from ..models.runtime import ResponseExecution from ..streaming._helpers import strip_nulls @@ -181,8 +181,8 @@ async def list_records(self) -> list[ResponseExecution]: def to_snapshot(execution: ResponseExecution) -> dict[str, Any]: """Build a normalized response snapshot dictionary from an execution. - Uses ``execution.response.as_dict()`` directly when a response snapshot is - available, avoiding an unnecessary ``Response(dict).as_dict()`` round-trip. + Uses the execution's response dict directly when a response snapshot is + available. Falls back to a minimal status-only dict when no response has been set yet. :param execution: The execution whose response snapshot to build. @@ -191,7 +191,7 @@ def to_snapshot(execution: ResponseExecution) -> dict[str, Any]: :rtype: dict[str, Any] """ if execution.response is not None: - result: dict[str, Any] = execution.response.as_dict() + result: dict[str, Any] = deepcopy(execution.response) result.setdefault("id", execution.response_id) result.setdefault("response_id", execution.response_id) result.setdefault("object", "response") diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_validation.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_validation.py index 2574777258bc..62c7e89b9dea 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_validation.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/hosting/_validation.py @@ -16,17 +16,17 @@ ) from azure.ai.agentserver.responses._id_generator import IdGenerator from azure.ai.agentserver.responses._options import ResponsesServerOptions -from azure.ai.agentserver.responses.models._generated import ApiErrorResponse, CreateResponse, Error from azure.ai.agentserver.responses.models._generated._validators import validate_CreateResponse +from azure.ai.extensions.openai.responses import ApiErrorResponse, CreateResponse from azure.ai.agentserver.responses.models.errors import RequestValidationError def parse_create_response(payload: Mapping[str, Any]) -> CreateResponse: - """Parse incoming JSON payload into the generated ``CreateResponse`` model. + """Validate incoming JSON payload and return a dict-native ``CreateResponse`` payload. :param payload: Raw request payload mapping. :type payload: Mapping[str, Any] - :returns: Parsed generated create response model. + :returns: Parsed create response wire payload. :rtype: CreateResponse :raises RequestValidationError: If payload is not an object or cannot be parsed. """ @@ -49,21 +49,14 @@ def parse_create_response(payload: Mapping[str, Any]) -> CreateResponse: details=details, ) - try: - return CreateResponse(payload) - except Exception as exc: # pragma: no cover - generated model raises implementation-specific errors. - raise RequestValidationError( - "request body failed schema validation", - code="invalid_request", - debug_info={"exception_type": type(exc).__name__, "detail": str(exc)}, - ) from exc + return CreateResponse(payload) def normalize_create_response( request: CreateResponse, options: ResponsesServerOptions | None, ) -> CreateResponse: - """Apply server-side defaults to a parsed create request model. + """Apply server-side defaults to a parsed create request payload. :param request: The parsed create response model to normalize. :type request: CreateResponse @@ -72,13 +65,15 @@ def normalize_create_response( :return: The same model instance with defaults applied. :rtype: CreateResponse """ - if (request.model is None or (isinstance(request.model, str) and not request.model.strip())) and options: - request.model = options.default_model + model = request.get("model") + if (model is None or (isinstance(model, str) and not model.strip())) and options: + request["model"] = options.default_model + model = request.get("model") - if isinstance(request.model, str): - request.model = request.model.strip() or "" - elif request.model is None: - request.model = "" + if isinstance(model, str): + request["model"] = model.strip() or "" + elif model is None: + request["model"] = "" return request @@ -90,16 +85,16 @@ def validate_create_response(request: CreateResponse) -> None: :type request: CreateResponse :raises RequestValidationError: If semantic preconditions are violated. """ - store_enabled = True if request.store is None else bool(request.store) + store_enabled = True if request.get("store") is None else bool(request.get("store")) - if request.background and not store_enabled: + if request.get("background") and not store_enabled: raise RequestValidationError( "background=true requires store=true", code="unsupported_parameter", param="background", ) - if request.stream_options is not None and request.stream is not True: + if request.get("stream_options") is not None and request.get("stream") is not True: raise RequestValidationError( "stream_options requires stream=true", code="invalid_mode", @@ -109,7 +104,7 @@ def validate_create_response(request: CreateResponse) -> None: # B22: model is optional — resolved to default in normalize_create_response() # Metadata constraints: ≤16 keys, key ≤64 chars, value ≤512 chars - metadata = getattr(request, "metadata", None) + metadata = request.get("metadata") if metadata is not None and hasattr(metadata, "items"): if len(metadata) > 16: raise RequestValidationError( @@ -132,7 +127,7 @@ def validate_create_response(request: CreateResponse) -> None: ) # Validate previous_response_id format (must be a valid caresp ID) - prev_id = getattr(request, "previous_response_id", None) + prev_id = request.get("previous_response_id") if isinstance(prev_id, str) and prev_id: is_valid, _ = IdGenerator.is_valid(prev_id, allowed_prefixes=["caresp"]) if not is_valid: @@ -172,7 +167,7 @@ def build_api_error_response( error_type: str = "invalid_request_error", debug_info: dict[str, Any] | None = None, ) -> ApiErrorResponse: - """Build a generated ``ApiErrorResponse`` envelope for client-visible failures. + """Build an API error envelope for client-visible failures. :param message: Human-readable error message. :type message: str @@ -187,15 +182,15 @@ def build_api_error_response( :return: A generated ``ApiErrorResponse`` envelope. :rtype: ApiErrorResponse """ - return ApiErrorResponse( - error=Error( - code=code, - message=message, - param=param, - type=error_type, - debug_info=debug_info, - ) - ) + error: dict[str, Any] = { + "code": code, + "message": message, + "param": param, + "type": error_type, + } + if debug_info is not None: + error["debug_info"] = debug_info + return ApiErrorResponse(error=error) def build_not_found_error_response( @@ -353,8 +348,6 @@ def _json_payload(value: Any) -> Any: :return: A JSON-serializable representation of the value. :rtype: Any """ - if hasattr(value, "as_dict"): - return value.as_dict() # type: ignore[no-any-return] return value diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/__init__.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/__init__.py index 460033db09b0..2e48da461545 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/__init__.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/__init__.py @@ -3,7 +3,7 @@ """Canonical non-generated model types for the response server.""" from ._generated import * # type: ignore # noqa: F401,F403 # pylint: disable=unused-wildcard-import -from ._generated.sdk.models.models import __all__ as _generated_all +from ._generated.models import __all__ as _generated_all from ._helpers import ( get_content_expanded, get_conversation_expanded, diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/__init__.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/__init__.py index b783bfa73795..acdd1cfbf714 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/__init__.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/__init__.py @@ -1,11 +1,5 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- +"""Compatibility package for extension-owned OpenAI Responses models.""" -"""Compatibility re-exports for generated models preserved under sdk/models.""" - -from .sdk.models.models import * # type: ignore # noqa: F401,F403 +from azure.ai.extensions.openai.responses._generated.sdk.models import * # type: ignore # noqa: F401,F403 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_enums.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_enums.py deleted file mode 100644 index 481d6d628755..000000000000 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_enums.py +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT license. -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- - -"""Compatibility shim for generated enum symbols.""" - -from .sdk.models.models._enums import * # type: ignore # noqa: F401,F403 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_models.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_models.py deleted file mode 100644 index 01e649adb824..000000000000 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_models.py +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT license. -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- - -"""Compatibility shim for generated model symbols.""" - -from .sdk.models.models._models import * # type: ignore # noqa: F401,F403 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_patch.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_patch.py index 66ee2dea3a63..9fe84caef087 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_patch.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_patch.py @@ -1,11 +1,5 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- +"""Compatibility re-export for extension-owned OpenAI Responses models.""" -"""Compatibility shim for generated patch helpers.""" - -from .sdk.models.models._patch import * # type: ignore # noqa: F401,F403 +from azure.ai.extensions.openai.responses._generated.sdk.models._patch import * # type: ignore # noqa: F401,F403 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_types.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_types.py new file mode 100644 index 000000000000..7910b8a1d80b --- /dev/null +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_types.py @@ -0,0 +1,5 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. +"""Compatibility re-export for extension-owned OpenAI Responses models.""" + +from azure.ai.extensions.openai.responses._generated.sdk.models._types import * # type: ignore # noqa: F401,F403 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_unions.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_unions.py new file mode 100644 index 000000000000..a15a813a24b6 --- /dev/null +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_unions.py @@ -0,0 +1,5 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. +"""Compatibility re-export for extension-owned OpenAI Responses models.""" + +from azure.ai.extensions.openai.responses._generated.sdk.models._unions import * # type: ignore # noqa: F401,F403 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_utils/__init__.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_utils/__init__.py new file mode 100644 index 000000000000..6e7800cdfd24 --- /dev/null +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_utils/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. +"""Compatibility re-export for extension-owned OpenAI Responses models.""" + +from azure.ai.extensions.openai.responses._generated.sdk.models._utils import * # type: ignore # noqa: F401,F403 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_utils/model_base.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_utils/model_base.py new file mode 100644 index 000000000000..116f55b1ca20 --- /dev/null +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_utils/model_base.py @@ -0,0 +1,5 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. +"""Compatibility re-export for extension-owned OpenAI Responses models.""" + +from azure.ai.extensions.openai.responses._generated.sdk.models._utils.model_base import * # type: ignore # noqa: F401,F403 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_utils/serialization.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_utils/serialization.py new file mode 100644 index 000000000000..a25de8f1abea --- /dev/null +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_utils/serialization.py @@ -0,0 +1,5 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. +"""Compatibility re-export for extension-owned OpenAI Responses models.""" + +from azure.ai.extensions.openai.responses._generated.sdk.models._utils.serialization import * # type: ignore # noqa: F401,F403 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_validators.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_validators.py index 6a4861b0714e..cb2b3ff60f29 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_validators.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/_validators.py @@ -10,13 +10,25 @@ from __future__ import annotations -from typing import Any +from typing import Any, get_args + +try: + from azure.ai.extensions.openai import responses as _response_types +except Exception: + _response_types = None try: from . import _enums as _generated_enums except Exception: _generated_enums = None +_LITERAL_ENUM_ALIASES = { + 'ServiceTier': 'ServiceTierEnum', +} +_LITERAL_ENUM_VALUES = { + 'Verbosity': ('low', 'medium', 'high'), +} + def _append_error(errors: list[dict[str, str]], path: str, message: str) -> None: errors.append({'path': path, 'message': message}) @@ -56,6 +68,14 @@ def _append_type_mismatch(errors: list[dict[str, str]], path: str, expected: str _append_error(errors, path, f"Expected {expected}, got {_type_label(value)}") def _enum_values(enum_name: str) -> tuple[tuple[str, ...] | None, str | None]: + if enum_name in _LITERAL_ENUM_VALUES: + return _LITERAL_ENUM_VALUES[enum_name], None + if _response_types is not None: + alias_name = _LITERAL_ENUM_ALIASES.get(enum_name, enum_name) + literal_alias = getattr(_response_types, alias_name, None) + literal_values = get_args(literal_alias) + if literal_values: + return tuple(str(value) for value in literal_values), None if _generated_enums is None: return None, f'enum type _enums.{enum_name} is unavailable' enum_cls = getattr(_generated_enums, enum_name, None) @@ -96,6 +116,8 @@ def _validate_CreateResponse(value: Any, path: str, errors: list[dict[str, str]] _validate_CreateResponse_metadata(value['metadata'], f"{path}.metadata", errors) if 'model' in value: _validate_CreateResponse_model(value['model'], f"{path}.model", errors) + if 'moderation' in value: + _validate_CreateResponse_moderation(value['moderation'], f"{path}.moderation", errors) if 'parallel_tool_calls' in value: _validate_CreateResponse_parallel_tool_calls(value['parallel_tool_calls'], f"{path}.parallel_tool_calls", errors) if 'previous_response_id' in value: @@ -206,6 +228,13 @@ def _validate_CreateResponse_model(value: Any, path: str, errors: list[dict[str, _append_type_mismatch(errors, path, 'string', value) return +def _validate_CreateResponse_moderation(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if value is None: + return + if not _is_type(value, 'object'): + _append_type_mismatch(errors, path, 'object', value) + return + def _validate_CreateResponse_parallel_tool_calls(value: Any, path: str, errors: list[dict[str, str]]) -> None: if value is None: return @@ -224,7 +253,7 @@ def _validate_CreateResponse_prompt_cache_key(value: Any, path: str, errors: lis def _validate_CreateResponse_prompt_cache_retention(value: Any, path: str, errors: list[dict[str, str]]) -> None: if value is None: return - _allowed_values = ('in-memory', '24h') + _allowed_values = ('in_memory', '24h') if value not in _allowed_values: _append_error(errors, path, f"Invalid value '{value}'. Allowed: {', '.join(str(v) for v in _allowed_values)}") if not _is_type(value, 'string'): @@ -398,6 +427,10 @@ def _validate_OpenAI_ToolChoiceParam(value: Any, path: str, errors: list[dict[st _validate_OpenAI_SpecificApplyPatchParam(value, path, errors) if _disc_value == 'code_interpreter': _validate_OpenAI_ToolChoiceCodeInterpreter(value, path, errors) + if _disc_value == 'computer': + _validate_OpenAI_ToolChoiceComputer(value, path, errors) + if _disc_value == 'computer_use': + _validate_OpenAI_ToolChoiceComputerUse(value, path, errors) if _disc_value == 'computer_use_preview': _validate_OpenAI_ToolChoiceComputerUsePreview(value, path, errors) if _disc_value == 'custom': @@ -519,6 +552,24 @@ def _validate_OpenAI_ToolChoiceCodeInterpreter(value: Any, path: str, errors: li if 'type' in value: _validate_OpenAI_ToolChoiceCodeInterpreter_type(value['type'], f"{path}.type", errors) +def _validate_OpenAI_ToolChoiceComputer(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'object'): + _append_type_mismatch(errors, path, 'object', value) + return + if 'type' not in value: + _append_error(errors, f"{path}.type", "Required property 'type' is missing") + if 'type' in value: + _validate_OpenAI_ToolChoiceComputer_type(value['type'], f"{path}.type", errors) + +def _validate_OpenAI_ToolChoiceComputerUse(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'object'): + _append_type_mismatch(errors, path, 'object', value) + return + if 'type' not in value: + _append_error(errors, f"{path}.type", "Required property 'type' is missing") + if 'type' in value: + _validate_OpenAI_ToolChoiceComputerUse_type(value['type'], f"{path}.type", errors) + def _validate_OpenAI_ToolChoiceComputerUsePreview(value: Any, path: str, errors: list[dict[str, str]]) -> None: if not _is_type(value, 'object'): _append_type_mismatch(errors, path, 'object', value) @@ -727,6 +778,22 @@ def _validate_OpenAI_ToolChoiceCodeInterpreter_type(value: Any, path: str, error _append_type_mismatch(errors, path, 'string', value) return +def _validate_OpenAI_ToolChoiceComputer_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _allowed_values = ('computer',) + if value not in _allowed_values: + _append_error(errors, path, f"Invalid value '{value}'. Allowed: {', '.join(str(v) for v in _allowed_values)}") + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + +def _validate_OpenAI_ToolChoiceComputerUse_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _allowed_values = ('computer_use',) + if value not in _allowed_values: + _append_error(errors, path, f"Invalid value '{value}'. Allowed: {', '.join(str(v) for v in _allowed_values)}") + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + def _validate_OpenAI_ToolChoiceComputerUsePreview_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: _allowed_values = ('computer_use_preview',) if value not in _allowed_values: @@ -844,6 +911,8 @@ def _validate_OpenAI_Tool(value: Any, path: str, errors: list[dict[str, str]]) - _validate_CaptureStructuredOutputsTool(value, path, errors) if _disc_value == 'code_interpreter': _validate_OpenAI_CodeInterpreterTool(value, path, errors) + if _disc_value == 'computer': + _validate_OpenAI_ComputerTool(value, path, errors) if _disc_value == 'computer_use_preview': _validate_OpenAI_ComputerUsePreviewTool(value, path, errors) if _disc_value == 'custom': @@ -864,12 +933,16 @@ def _validate_OpenAI_Tool(value: Any, path: str, errors: list[dict[str, str]]) - _validate_MemorySearchTool(value, path, errors) if _disc_value == 'memory_search_preview': _validate_MemorySearchPreviewTool(value, path, errors) + if _disc_value == 'namespace': + _validate_OpenAI_NamespaceToolParam(value, path, errors) if _disc_value == 'openapi': _validate_OpenApiTool(value, path, errors) if _disc_value == 'sharepoint_grounding_preview': _validate_SharepointPreviewTool(value, path, errors) if _disc_value == 'shell': _validate_OpenAI_FunctionShellToolParam(value, path, errors) + if _disc_value == 'tool_search': + _validate_OpenAI_ToolSearchToolParam(value, path, errors) if _disc_value == 'web_search': _validate_OpenAI_WebSearchTool(value, path, errors) if _disc_value == 'web_search_preview': @@ -889,6 +962,8 @@ def _validate_OpenAI_Item(value: Any, path: str, errors: list[dict[str, str]]) - if not isinstance(_disc_value, str): _append_error(errors, f"{path}.type", "Required discriminator 'type' is missing or invalid") return + if _disc_value == 'additional_tools': + _validate_OpenAI_AdditionalToolsItemParam(value, path, errors) if _disc_value == 'apply_patch_call': _validate_OpenAI_ApplyPatchToolCallItemParam(value, path, errors) if _disc_value == 'apply_patch_call_output': @@ -939,6 +1014,10 @@ def _validate_OpenAI_Item(value: Any, path: str, errors: list[dict[str, str]]) - _validate_OpenAI_FunctionShellCallItemParam(value, path, errors) if _disc_value == 'shell_call_output': _validate_OpenAI_FunctionShellCallOutputItemParam(value, path, errors) + if _disc_value == 'tool_search_call': + _validate_OpenAI_ToolSearchCallItemParam(value, path, errors) + if _disc_value == 'tool_search_output': + _validate_OpenAI_ToolSearchOutputItemParam(value, path, errors) if _disc_value == 'web_search_call': _validate_OpenAI_ItemWebSearchToolCall(value, path, errors) @@ -1145,6 +1224,15 @@ def _validate_OpenAI_CodeInterpreterTool(value: Any, path: str, errors: list[dic if 'type' in value: _validate_OpenAI_CodeInterpreterTool_type(value['type'], f"{path}.type", errors) +def _validate_OpenAI_ComputerTool(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'object'): + _append_type_mismatch(errors, path, 'object', value) + return + if 'type' not in value: + _append_error(errors, f"{path}.type", "Required property 'type' is missing") + if 'type' in value: + _validate_OpenAI_ComputerTool_type(value['type'], f"{path}.type", errors) + def _validate_OpenAI_ComputerUsePreviewTool(value: Any, path: str, errors: list[dict[str, str]]) -> None: if not _is_type(value, 'object'): _append_type_mismatch(errors, path, 'object', value) @@ -1174,6 +1262,8 @@ def _validate_OpenAI_CustomToolParam(value: Any, path: str, errors: list[dict[st _append_error(errors, f"{path}.type", "Required property 'type' is missing") if 'name' not in value: _append_error(errors, f"{path}.name", "Required property 'name' is missing") + if 'defer_loading' in value: + _validate_OpenAI_CustomToolParam_defer_loading(value['defer_loading'], f"{path}.defer_loading", errors) if 'description' in value: _validate_OpenAI_CustomToolParam_description(value['description'], f"{path}.description", errors) if 'format' in value: @@ -1231,6 +1321,8 @@ def _validate_OpenAI_FunctionTool(value: Any, path: str, errors: list[dict[str, _append_error(errors, f"{path}.type", "Required property 'type' is missing") if 'name' not in value: _append_error(errors, f"{path}.name", "Required property 'name' is missing") + if 'defer_loading' in value: + _validate_OpenAI_FunctionTool_defer_loading(value['defer_loading'], f"{path}.defer_loading", errors) if 'description' in value: _validate_CreateResponse_instructions(value['description'], f"{path}.description", errors) if 'name' in value: @@ -1304,6 +1396,8 @@ def _validate_OpenAI_MCPTool(value: Any, path: str, errors: list[dict[str, str]] _validate_OpenAI_MCPTool_authorization(value['authorization'], f"{path}.authorization", errors) if 'connector_id' in value: _validate_OpenAI_MCPTool_connector_id(value['connector_id'], f"{path}.connector_id", errors) + if 'defer_loading' in value: + _validate_OpenAI_MCPTool_defer_loading(value['defer_loading'], f"{path}.defer_loading", errors) if 'headers' in value: _validate_OpenAI_MCPTool_headers(value['headers'], f"{path}.headers", errors) if 'project_connection_id' in value: @@ -1316,6 +1410,8 @@ def _validate_OpenAI_MCPTool(value: Any, path: str, errors: list[dict[str, str]] _validate_OpenAI_MCPTool_server_label(value['server_label'], f"{path}.server_label", errors) if 'server_url' in value: _validate_OpenAI_MCPTool_server_url(value['server_url'], f"{path}.server_url", errors) + if 'tunnel_id' in value: + _validate_OpenAI_MCPTool_tunnel_id(value['tunnel_id'], f"{path}.tunnel_id", errors) if 'type' in value: _validate_OpenAI_MCPTool_type(value['type'], f"{path}.type", errors) @@ -1369,6 +1465,27 @@ def _validate_MemorySearchPreviewTool(value: Any, path: str, errors: list[dict[s if 'update_delay' in value: _validate_MemorySearchTool_update_delay(value['update_delay'], f"{path}.update_delay", errors) +def _validate_OpenAI_NamespaceToolParam(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'object'): + _append_type_mismatch(errors, path, 'object', value) + return + if 'type' not in value: + _append_error(errors, f"{path}.type", "Required property 'type' is missing") + if 'name' not in value: + _append_error(errors, f"{path}.name", "Required property 'name' is missing") + if 'description' not in value: + _append_error(errors, f"{path}.description", "Required property 'description' is missing") + if 'tools' not in value: + _append_error(errors, f"{path}.tools", "Required property 'tools' is missing") + if 'description' in value: + _validate_OpenAI_NamespaceToolParam_description(value['description'], f"{path}.description", errors) + if 'name' in value: + _validate_OpenAI_NamespaceToolParam_name(value['name'], f"{path}.name", errors) + if 'tools' in value: + _validate_OpenAI_NamespaceToolParam_tools(value['tools'], f"{path}.tools", errors) + if 'type' in value: + _validate_OpenAI_NamespaceToolParam_type(value['type'], f"{path}.type", errors) + def _validate_OpenApiTool(value: Any, path: str, errors: list[dict[str, str]]) -> None: if not _is_type(value, 'object'): _append_type_mismatch(errors, path, 'object', value) @@ -1414,6 +1531,21 @@ def _validate_OpenAI_FunctionShellToolParam(value: Any, path: str, errors: list[ if 'type' in value: _validate_OpenAI_FunctionShellToolParam_type(value['type'], f"{path}.type", errors) +def _validate_OpenAI_ToolSearchToolParam(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'object'): + _append_type_mismatch(errors, path, 'object', value) + return + if 'type' not in value: + _append_error(errors, f"{path}.type", "Required property 'type' is missing") + if 'description' in value: + _validate_CreateResponse_instructions(value['description'], f"{path}.description", errors) + if 'execution' in value: + _validate_OpenAI_ToolSearchToolParam_execution(value['execution'], f"{path}.execution", errors) + if 'parameters' in value: + _validate_OpenAI_ToolSearchToolParam_parameters(value['parameters'], f"{path}.parameters", errors) + if 'type' in value: + _validate_OpenAI_ToolSearchToolParam_type(value['type'], f"{path}.type", errors) + def _validate_OpenAI_WebSearchTool(value: Any, path: str, errors: list[dict[str, str]]) -> None: if not _is_type(value, 'object'): _append_type_mismatch(errors, path, 'object', value) @@ -1441,6 +1573,8 @@ def _validate_OpenAI_WebSearchPreviewTool(value: Any, path: str, errors: list[di return if 'type' not in value: _append_error(errors, f"{path}.type", "Required property 'type' is missing") + if 'search_content_types' in value: + _validate_OpenAI_WebSearchPreviewTool_search_content_types(value['search_content_types'], f"{path}.search_content_types", errors) if 'search_context_size' in value: _validate_OpenAI_WebSearchPreviewTool_search_context_size(value['search_context_size'], f"{path}.search_context_size", errors) if 'type' in value: @@ -1464,6 +1598,25 @@ def _validate_WorkIQPreviewTool(value: Any, path: str, errors: list[dict[str, st def _validate_OpenAI_Item_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: _validate_OpenAI_ItemType(value, path, errors) +def _validate_OpenAI_AdditionalToolsItemParam(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'object'): + _append_type_mismatch(errors, path, 'object', value) + return + if 'type' not in value: + _append_error(errors, f"{path}.type", "Required property 'type' is missing") + if 'role' not in value: + _append_error(errors, f"{path}.role", "Required property 'role' is missing") + if 'tools' not in value: + _append_error(errors, f"{path}.tools", "Required property 'tools' is missing") + if 'id' in value: + _validate_CreateResponse_instructions(value['id'], f"{path}.id", errors) + if 'role' in value: + _validate_OpenAI_AdditionalToolsItemParam_role(value['role'], f"{path}.role", errors) + if 'tools' in value: + _validate_OpenAI_AdditionalToolsItemParam_tools(value['tools'], f"{path}.tools", errors) + if 'type' in value: + _validate_OpenAI_AdditionalToolsItemParam_type(value['type'], f"{path}.type", errors) + def _validate_OpenAI_ApplyPatchToolCallItemParam(value: Any, path: str, errors: list[dict[str, str]]) -> None: if not _is_type(value, 'object'): _append_type_mismatch(errors, path, 'object', value) @@ -1562,14 +1715,14 @@ def _validate_OpenAI_ItemComputerToolCall(value: Any, path: str, errors: list[di _append_error(errors, f"{path}.id", "Required property 'id' is missing") if 'call_id' not in value: _append_error(errors, f"{path}.call_id", "Required property 'call_id' is missing") - if 'action' not in value: - _append_error(errors, f"{path}.action", "Required property 'action' is missing") if 'pending_safety_checks' not in value: _append_error(errors, f"{path}.pending_safety_checks", "Required property 'pending_safety_checks' is missing") if 'status' not in value: _append_error(errors, f"{path}.status", "Required property 'status' is missing") if 'action' in value: _validate_OpenAI_ItemComputerToolCall_action(value['action'], f"{path}.action", errors) + if 'actions' in value: + _validate_OpenAI_ItemComputerToolCall_actions(value['actions'], f"{path}.actions", errors) if 'call_id' in value: _validate_OpenAI_ItemComputerToolCall_call_id(value['call_id'], f"{path}.call_id", errors) if 'id' in value: @@ -1624,6 +1777,8 @@ def _validate_OpenAI_ItemCustomToolCall(value: Any, path: str, errors: list[dict _validate_OpenAI_ItemCustomToolCall_input(value['input'], f"{path}.input", errors) if 'name' in value: _validate_OpenAI_ItemCustomToolCall_name(value['name'], f"{path}.name", errors) + if 'namespace' in value: + _validate_OpenAI_ItemCustomToolCall_namespace(value['namespace'], f"{path}.namespace", errors) if 'type' in value: _validate_OpenAI_ItemCustomToolCall_type(value['type'], f"{path}.type", errors) @@ -1689,6 +1844,8 @@ def _validate_OpenAI_ItemFunctionToolCall(value: Any, path: str, errors: list[di _validate_OpenAI_ItemFunctionToolCall_id(value['id'], f"{path}.id", errors) if 'name' in value: _validate_OpenAI_ItemFunctionToolCall_name(value['name'], f"{path}.name", errors) + if 'namespace' in value: + _validate_OpenAI_ItemFunctionToolCall_namespace(value['namespace'], f"{path}.namespace", errors) if 'status' in value: _validate_OpenAI_ItemComputerToolCall_status(value['status'], f"{path}.status", errors) if 'type' in value: @@ -1885,7 +2042,7 @@ def _validate_OpenAI_ItemMcpListTools(value: Any, path: str, errors: list[dict[s if 'tools' not in value: _append_error(errors, f"{path}.tools", "Required property 'tools' is missing") if 'error' in value: - _validate_CreateResponse_instructions(value['error'], f"{path}.error", errors) + _validate_OpenAI_ItemMcpListTools_error(value['error'], f"{path}.error", errors) if 'id' in value: _validate_OpenAI_ItemMcpListTools_id(value['id'], f"{path}.id", errors) if 'server_label' in value: @@ -1916,6 +2073,8 @@ def _validate_OpenAI_ItemMessage(value: Any, path: str, errors: list[dict[str, s _append_error(errors, f"{path}.content", "Required property 'content' is missing") if 'content' in value: _validate_OpenAI_ItemMessage_content(value['content'], f"{path}.content", errors) + if 'phase' in value: + _validate_OpenAI_ItemMessage_phase(value['phase'], f"{path}.phase", errors) if 'role' in value: _validate_OpenAI_ItemMessage_role(value['role'], f"{path}.role", errors) if 'type' in value: @@ -1939,6 +2098,8 @@ def _validate_OpenAI_ItemOutputMessage(value: Any, path: str, errors: list[dict[ _validate_OpenAI_ItemOutputMessage_content(value['content'], f"{path}.content", errors) if 'id' in value: _validate_OpenAI_ItemOutputMessage_id(value['id'], f"{path}.id", errors) + if 'phase' in value: + _validate_OpenAI_ItemMessage_phase(value['phase'], f"{path}.phase", errors) if 'role' in value: _validate_OpenAI_ItemOutputMessage_role(value['role'], f"{path}.role", errors) if 'status' in value: @@ -2015,6 +2176,48 @@ def _validate_OpenAI_FunctionShellCallOutputItemParam(value: Any, path: str, err if 'type' in value: _validate_OpenAI_FunctionShellCallOutputItemParam_type(value['type'], f"{path}.type", errors) +def _validate_OpenAI_ToolSearchCallItemParam(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'object'): + _append_type_mismatch(errors, path, 'object', value) + return + if 'type' not in value: + _append_error(errors, f"{path}.type", "Required property 'type' is missing") + if 'arguments' not in value: + _append_error(errors, f"{path}.arguments", "Required property 'arguments' is missing") + if 'arguments' in value: + _validate_OpenAI_ToolSearchCallItemParam_arguments(value['arguments'], f"{path}.arguments", errors) + if 'call_id' in value: + _validate_CreateResponse_instructions(value['call_id'], f"{path}.call_id", errors) + if 'execution' in value: + _validate_OpenAI_ToolSearchCallItemParam_execution(value['execution'], f"{path}.execution", errors) + if 'id' in value: + _validate_CreateResponse_instructions(value['id'], f"{path}.id", errors) + if 'status' in value: + _validate_OpenAI_ComputerCallOutputItemParam_status(value['status'], f"{path}.status", errors) + if 'type' in value: + _validate_OpenAI_ToolSearchCallItemParam_type(value['type'], f"{path}.type", errors) + +def _validate_OpenAI_ToolSearchOutputItemParam(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'object'): + _append_type_mismatch(errors, path, 'object', value) + return + if 'type' not in value: + _append_error(errors, f"{path}.type", "Required property 'type' is missing") + if 'tools' not in value: + _append_error(errors, f"{path}.tools", "Required property 'tools' is missing") + if 'call_id' in value: + _validate_CreateResponse_instructions(value['call_id'], f"{path}.call_id", errors) + if 'execution' in value: + _validate_OpenAI_ToolSearchCallItemParam_execution(value['execution'], f"{path}.execution", errors) + if 'id' in value: + _validate_CreateResponse_instructions(value['id'], f"{path}.id", errors) + if 'status' in value: + _validate_OpenAI_ComputerCallOutputItemParam_status(value['status'], f"{path}.status", errors) + if 'tools' in value: + _validate_OpenAI_ToolSearchOutputItemParam_tools(value['tools'], f"{path}.tools", errors) + if 'type' in value: + _validate_OpenAI_ToolSearchOutputItemParam_type(value['type'], f"{path}.type", errors) + def _validate_OpenAI_ItemWebSearchToolCall(value: Any, path: str, errors: list[dict[str, str]]) -> None: if not _is_type(value, 'object'): _append_type_mismatch(errors, path, 'object', value) @@ -2236,6 +2439,14 @@ def _validate_OpenAI_CodeInterpreterTool_type(value: Any, path: str, errors: lis _append_type_mismatch(errors, path, 'string', value) return +def _validate_OpenAI_ComputerTool_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _allowed_values = ('computer',) + if value not in _allowed_values: + _append_error(errors, path, f"Invalid value '{value}'. Allowed: {', '.join(str(v) for v in _allowed_values)}") + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + def _validate_OpenAI_ComputerUsePreviewTool_display_height(value: Any, path: str, errors: list[dict[str, str]]) -> None: if not _is_type(value, 'integer'): _append_type_mismatch(errors, path, 'integer', value) @@ -2257,6 +2468,11 @@ def _validate_OpenAI_ComputerUsePreviewTool_type(value: Any, path: str, errors: _append_type_mismatch(errors, path, 'string', value) return +def _validate_OpenAI_CustomToolParam_defer_loading(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'boolean'): + _append_type_mismatch(errors, path, 'boolean', value) + return + def _validate_OpenAI_CustomToolParam_description(value: Any, path: str, errors: list[dict[str, str]]) -> None: if not _is_type(value, 'string'): _append_type_mismatch(errors, path, 'string', value) @@ -2316,6 +2532,11 @@ def _validate_OpenAI_FileSearchTool_vector_store_ids(value: Any, path: str, erro for _idx, _item in enumerate(value): _validate_OpenAI_InputParam_string(_item, f"{path}[{_idx}]", errors) +def _validate_OpenAI_FunctionTool_defer_loading(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'boolean'): + _append_type_mismatch(errors, path, 'boolean', value) + return + def _validate_OpenAI_FunctionTool_parameters(value: Any, path: str, errors: list[dict[str, str]]) -> None: if value is None: return @@ -2403,11 +2624,19 @@ def _validate_OpenAI_ImageGenTool_quality(value: Any, path: str, errors: list[di return def _validate_OpenAI_ImageGenTool_size(value: Any, path: str, errors: list[dict[str, str]]) -> None: - _allowed_values = ('1024x1024', '1024x1536', '1536x1024', 'auto') - if value not in _allowed_values: - _append_error(errors, path, f"Invalid value '{value}'. Allowed: {', '.join(str(v) for v in _allowed_values)}") - if not _is_type(value, 'string'): - _append_type_mismatch(errors, path, 'string', value) + _matched_union = False + if not _matched_union and _is_type(value, 'string'): + _branch_errors_0: list[dict[str, str]] = [] + _validate_OpenAI_InputParam_string(value, path, _branch_errors_0) + if not _branch_errors_0: + _matched_union = True + if not _matched_union and _is_type(value, 'string'): + _branch_errors_1: list[dict[str, str]] = [] + _validate_OpenAI_ImageGenTool_size_2(value, path, _branch_errors_1) + if not _branch_errors_1: + _matched_union = True + if not _matched_union: + _append_error(errors, path, f"Expected ImageGenTool_size to be a string value, got {_type_label(value)}") return def _validate_OpenAI_ImageGenTool_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: @@ -2455,6 +2684,11 @@ def _validate_OpenAI_MCPTool_connector_id(value: Any, path: str, errors: list[di _append_type_mismatch(errors, path, 'string', value) return +def _validate_OpenAI_MCPTool_defer_loading(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'boolean'): + _append_type_mismatch(errors, path, 'boolean', value) + return + def _validate_OpenAI_MCPTool_headers(value: Any, path: str, errors: list[dict[str, str]]) -> None: if value is None: return @@ -2501,6 +2735,11 @@ def _validate_OpenAI_MCPTool_server_url(value: Any, path: str, errors: list[dict _append_type_mismatch(errors, path, 'string', value) return +def _validate_OpenAI_MCPTool_tunnel_id(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + def _validate_OpenAI_MCPTool_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: _allowed_values = ('mcp',) if value not in _allowed_values: @@ -2543,6 +2782,31 @@ def _validate_MemorySearchPreviewTool_type(value: Any, path: str, errors: list[d _append_type_mismatch(errors, path, 'string', value) return +def _validate_OpenAI_NamespaceToolParam_description(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + +def _validate_OpenAI_NamespaceToolParam_name(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + +def _validate_OpenAI_NamespaceToolParam_tools(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'array'): + _append_type_mismatch(errors, path, 'array', value) + return + for _idx, _item in enumerate(value): + _validate_OpenAI_NamespaceToolParam_tools_item(_item, f"{path}[{_idx}]", errors) + +def _validate_OpenAI_NamespaceToolParam_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _allowed_values = ('namespace',) + if value not in _allowed_values: + _append_error(errors, path, f"Invalid value '{value}'. Allowed: {', '.join(str(v) for v in _allowed_values)}") + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + def _validate_OpenApiTool_openapi(value: Any, path: str, errors: list[dict[str, str]]) -> None: return @@ -2580,6 +2844,24 @@ def _validate_OpenAI_FunctionShellToolParam_type(value: Any, path: str, errors: _append_type_mismatch(errors, path, 'string', value) return +def _validate_OpenAI_ToolSearchToolParam_execution(value: Any, path: str, errors: list[dict[str, str]]) -> None: + return + +def _validate_OpenAI_ToolSearchToolParam_parameters(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if value is None: + return + if not _is_type(value, 'object'): + _append_type_mismatch(errors, path, 'object', value) + return + +def _validate_OpenAI_ToolSearchToolParam_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _allowed_values = ('tool_search',) + if value not in _allowed_values: + _append_error(errors, path, f"Invalid value '{value}'. Allowed: {', '.join(str(v) for v in _allowed_values)}") + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + def _validate_OpenAI_WebSearchTool_custom_search_configuration(value: Any, path: str, errors: list[dict[str, str]]) -> None: return @@ -2613,6 +2895,13 @@ def _validate_OpenAI_WebSearchTool_user_location(value: Any, path: str, errors: _append_type_mismatch(errors, path, 'object', value) return +def _validate_OpenAI_WebSearchPreviewTool_search_content_types(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'array'): + _append_type_mismatch(errors, path, 'array', value) + return + for _idx, _item in enumerate(value): + _validate_OpenAI_WebSearchPreviewTool_search_content_types_item(_item, f"{path}[{_idx}]", errors) + def _validate_OpenAI_WebSearchPreviewTool_search_context_size(value: Any, path: str, errors: list[dict[str, str]]) -> None: return @@ -2658,6 +2947,29 @@ def _validate_OpenAI_ItemType(value: Any, path: str, errors: list[dict[str, str] _append_error(errors, path, f"Expected ItemType to be a string value, got {_type_label(value)}") return +def _validate_OpenAI_AdditionalToolsItemParam_role(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _allowed_values = ('developer',) + if value not in _allowed_values: + _append_error(errors, path, f"Invalid value '{value}'. Allowed: {', '.join(str(v) for v in _allowed_values)}") + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + +def _validate_OpenAI_AdditionalToolsItemParam_tools(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'array'): + _append_type_mismatch(errors, path, 'array', value) + return + for _idx, _item in enumerate(value): + _validate_OpenAI_ToolsArray_item(_item, f"{path}[{_idx}]", errors) + +def _validate_OpenAI_AdditionalToolsItemParam_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _allowed_values = ('additional_tools',) + if value not in _allowed_values: + _append_error(errors, path, f"Invalid value '{value}'. Allowed: {', '.join(str(v) for v in _allowed_values)}") + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + def _validate_OpenAI_ApplyPatchToolCallItemParam_call_id(value: Any, path: str, errors: list[dict[str, str]]) -> None: if not _is_type(value, 'string'): _append_type_mismatch(errors, path, 'string', value) @@ -2739,6 +3051,9 @@ def _validate_OpenAI_CompactionSummaryItemParam_type(value: Any, path: str, erro def _validate_OpenAI_ItemComputerToolCall_action(value: Any, path: str, errors: list[dict[str, str]]) -> None: _validate_OpenAI_ComputerAction(value, path, errors) +def _validate_OpenAI_ItemComputerToolCall_actions(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _validate_OpenAI_ComputerActionList(value, path, errors) + def _validate_OpenAI_ItemComputerToolCall_call_id(value: Any, path: str, errors: list[dict[str, str]]) -> None: if not _is_type(value, 'string'): _append_type_mismatch(errors, path, 'string', value) @@ -2821,6 +3136,11 @@ def _validate_OpenAI_ItemCustomToolCall_name(value: Any, path: str, errors: list _append_type_mismatch(errors, path, 'string', value) return +def _validate_OpenAI_ItemCustomToolCall_namespace(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + def _validate_OpenAI_ItemCustomToolCall_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: _allowed_values = ('custom_tool_call',) if value not in _allowed_values: @@ -2920,6 +3240,11 @@ def _validate_OpenAI_ItemFunctionToolCall_name(value: Any, path: str, errors: li _append_type_mismatch(errors, path, 'string', value) return +def _validate_OpenAI_ItemFunctionToolCall_namespace(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + def _validate_OpenAI_ItemFunctionToolCall_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: _allowed_values = ('function_call',) if value not in _allowed_values: @@ -3120,6 +3445,9 @@ def _validate_OpenAI_ItemMcpToolCall_type(value: Any, path: str, errors: list[di _append_type_mismatch(errors, path, 'string', value) return +def _validate_OpenAI_ItemMcpListTools_error(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _validate_OpenAI_RealtimeMCPError(value, path, errors) + def _validate_OpenAI_ItemMcpListTools_id(value: Any, path: str, errors: list[dict[str, str]]) -> None: if not _is_type(value, 'string'): _append_type_mismatch(errors, path, 'string', value) @@ -3178,6 +3506,10 @@ def _validate_OpenAI_ItemMessage_content(value: Any, path: str, errors: list[dic _append_error(errors, path, f"Expected one of: string, array; got {_type_label(value)}") return +def _validate_OpenAI_ItemMessage_phase(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if value is None: + return + def _validate_OpenAI_ItemMessage_role(value: Any, path: str, errors: list[dict[str, str]]) -> None: return @@ -3296,6 +3628,35 @@ def _validate_OpenAI_FunctionShellCallOutputItemParam_type(value: Any, path: str _append_type_mismatch(errors, path, 'string', value) return +def _validate_OpenAI_ToolSearchCallItemParam_arguments(value: Any, path: str, errors: list[dict[str, str]]) -> None: + return + +def _validate_OpenAI_ToolSearchCallItemParam_execution(value: Any, path: str, errors: list[dict[str, str]]) -> None: + return + +def _validate_OpenAI_ToolSearchCallItemParam_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _allowed_values = ('tool_search_call',) + if value not in _allowed_values: + _append_error(errors, path, f"Invalid value '{value}'. Allowed: {', '.join(str(v) for v in _allowed_values)}") + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + +def _validate_OpenAI_ToolSearchOutputItemParam_tools(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'array'): + _append_type_mismatch(errors, path, 'array', value) + return + for _idx, _item in enumerate(value): + _validate_OpenAI_ToolsArray_item(_item, f"{path}[{_idx}]", errors) + +def _validate_OpenAI_ToolSearchOutputItemParam_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _allowed_values = ('tool_search_output',) + if value not in _allowed_values: + _append_error(errors, path, f"Invalid value '{value}'. Allowed: {', '.join(str(v) for v in _allowed_values)}") + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + def _validate_OpenAI_ItemWebSearchToolCall_action(value: Any, path: str, errors: list[dict[str, str]]) -> None: _matched_union = False if not _matched_union and _is_type(value, 'object'): @@ -3395,6 +3756,14 @@ def _validate_OpenAI_ImageGenTool_model_2(value: Any, path: str, errors: list[di _append_type_mismatch(errors, path, 'string', value) return +def _validate_OpenAI_ImageGenTool_size_2(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _allowed_values = ('1024x1024', '1024x1536', '1536x1024', 'auto') + if value not in _allowed_values: + _append_error(errors, path, f"Invalid value '{value}'. Allowed: {', '.join(str(v) for v in _allowed_values)}") + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + def _validate_OpenAI_MCPTool_allowed_tools_array(value: Any, path: str, errors: list[dict[str, str]]) -> None: if value is None: return @@ -3428,6 +3797,25 @@ def _validate_OpenAI_MCPTool_require_approval_2(value: Any, path: str, errors: l _append_type_mismatch(errors, path, 'string', value) return +def _validate_OpenAI_NamespaceToolParam_tools_item(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _matched_union = False + if not _matched_union and _is_type(value, 'object'): + _branch_errors_0: list[dict[str, str]] = [] + _validate_OpenAI_FunctionToolParam(value, path, _branch_errors_0) + if not _branch_errors_0: + _matched_union = True + if not _matched_union and _is_type(value, 'object'): + _branch_errors_1: list[dict[str, str]] = [] + _validate_OpenAI_CustomToolParam(value, path, _branch_errors_1) + if not _branch_errors_1: + _matched_union = True + if not _matched_union: + _append_error(errors, path, f"Expected one of: OpenAI.FunctionToolParam, OpenAI.CustomToolParam; got {_type_label(value)}") + return + +def _validate_OpenAI_WebSearchPreviewTool_search_content_types_item(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _validate_OpenAI_SearchContentType(value, path, errors) + def _validate_OpenAI_ItemType_2(value: Any, path: str, errors: list[dict[str, str]]) -> None: _allowed_values, _enum_error = _enum_values('ItemType') if _enum_error is not None: @@ -3488,6 +3876,13 @@ def _validate_OpenAI_ComputerAction(value: Any, path: str, errors: list[dict[str if _disc_value == 'wait': _validate_OpenAI_WaitParam(value, path, errors) +def _validate_OpenAI_ComputerActionList(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'array'): + _append_type_mismatch(errors, path, 'array', value) + return + for _idx, _item in enumerate(value): + _validate_OpenAI_ItemComputerToolCall_action(_item, f"{path}[{_idx}]", errors) + def _validate_OpenAI_ItemComputerToolCall_pending_safety_checks_item(value: Any, path: str, errors: list[dict[str, str]]) -> None: _validate_OpenAI_ComputerCallSafetyCheckParam(value, path, errors) @@ -3544,6 +3939,25 @@ def _validate_OpenAI_LocalShellExecAction(value: Any, path: str, errors: list[di if 'working_directory' in value: _validate_CreateResponse_instructions(value['working_directory'], f"{path}.working_directory", errors) +def _validate_OpenAI_RealtimeMCPError(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'object'): + _append_type_mismatch(errors, path, 'object', value) + return + if 'type' not in value: + _append_error(errors, f"{path}.type", "Required property 'type' is missing") + if 'type' in value: + _validate_OpenAI_RealtimeMCPError_type(value['type'], f"{path}.type", errors) + _disc_value = value.get('type') + if not isinstance(_disc_value, str): + _append_error(errors, f"{path}.type", "Required discriminator 'type' is missing or invalid") + return + if _disc_value == 'http_error': + _validate_OpenAI_RealtimeMCPHTTPError(value, path, errors) + if _disc_value == 'protocol_error': + _validate_OpenAI_RealtimeMCPProtocolError(value, path, errors) + if _disc_value == 'tool_execution_error': + _validate_OpenAI_RealtimeMCPToolExecutionError(value, path, errors) + def _validate_OpenAI_ItemMcpListTools_tools_item(value: Any, path: str, errors: list[dict[str, str]]) -> None: _validate_OpenAI_MCPListToolsTool(value, path, errors) @@ -3575,8 +3989,6 @@ def _validate_OpenAI_WebSearchActionSearch(value: Any, path: str, errors: list[d return if 'type' not in value: _append_error(errors, f"{path}.type", "Required property 'type' is missing") - if 'query' not in value: - _append_error(errors, f"{path}.query", "Required property 'query' is missing") if 'queries' in value: _validate_OpenAI_WebSearchActionSearch_queries(value['queries'], f"{path}.queries", errors) if 'query' in value: @@ -3636,6 +4048,40 @@ def _validate_OpenAI_AutoCodeInterpreterToolParam_type(value: Any, path: str, er _append_type_mismatch(errors, path, 'string', value) return +def _validate_OpenAI_FunctionToolParam(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'object'): + _append_type_mismatch(errors, path, 'object', value) + return + if 'name' not in value: + _append_error(errors, f"{path}.name", "Required property 'name' is missing") + if 'type' not in value: + _append_error(errors, f"{path}.type", "Required property 'type' is missing") + if 'defer_loading' in value: + _validate_OpenAI_FunctionToolParam_defer_loading(value['defer_loading'], f"{path}.defer_loading", errors) + if 'description' in value: + _validate_CreateResponse_instructions(value['description'], f"{path}.description", errors) + if 'name' in value: + _validate_OpenAI_FunctionToolParam_name(value['name'], f"{path}.name", errors) + if 'parameters' in value: + _validate_OpenAI_ToolSearchToolParam_parameters(value['parameters'], f"{path}.parameters", errors) + if 'strict' in value: + _validate_CreateResponse_background(value['strict'], f"{path}.strict", errors) + if 'type' in value: + _validate_OpenAI_FunctionToolParam_type(value['type'], f"{path}.type", errors) + +def _validate_OpenAI_SearchContentType(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _allowed_values, _enum_error = _enum_values('SearchContentType') + if _enum_error is not None: + _append_error(errors, path, _enum_error) + return + if _allowed_values is None: + return + if value not in _allowed_values: + _append_error(errors, path, f"Invalid value '{value}'. Allowed: {', '.join(str(v) for v in _allowed_values)}") + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + def _validate_OpenAI_CodeInterpreterOutputLogs(value: Any, path: str, errors: list[dict[str, str]]) -> None: if not _is_type(value, 'object'): _append_type_mismatch(errors, path, 'object', value) @@ -3679,6 +4125,8 @@ def _validate_OpenAI_ClickParam(value: Any, path: str, errors: list[dict[str, st _append_error(errors, f"{path}.y", "Required property 'y' is missing") if 'button' in value: _validate_OpenAI_ClickParam_button(value['button'], f"{path}.button", errors) + if 'keys' in value: + _validate_OpenAI_MCPTool_allowed_tools_array(value['keys'], f"{path}.keys", errors) if 'type' in value: _validate_OpenAI_ClickParam_type(value['type'], f"{path}.type", errors) if 'x' in value: @@ -3696,6 +4144,10 @@ def _validate_OpenAI_DoubleClickAction(value: Any, path: str, errors: list[dict[ _append_error(errors, f"{path}.x", "Required property 'x' is missing") if 'y' not in value: _append_error(errors, f"{path}.y", "Required property 'y' is missing") + if 'keys' not in value: + _append_error(errors, f"{path}.keys", "Required property 'keys' is missing") + if 'keys' in value: + _validate_OpenAI_MCPTool_allowed_tools_array(value['keys'], f"{path}.keys", errors) if 'type' in value: _validate_OpenAI_DoubleClickAction_type(value['type'], f"{path}.type", errors) if 'x' in value: @@ -3711,6 +4163,8 @@ def _validate_OpenAI_DragParam(value: Any, path: str, errors: list[dict[str, str _append_error(errors, f"{path}.type", "Required property 'type' is missing") if 'path' not in value: _append_error(errors, f"{path}.path", "Required property 'path' is missing") + if 'keys' in value: + _validate_OpenAI_MCPTool_allowed_tools_array(value['keys'], f"{path}.keys", errors) if 'path' in value: _validate_OpenAI_DragParam_path(value['path'], f"{path}.path", errors) if 'type' in value: @@ -3739,6 +4193,8 @@ def _validate_OpenAI_MoveParam(value: Any, path: str, errors: list[dict[str, str _append_error(errors, f"{path}.x", "Required property 'x' is missing") if 'y' not in value: _append_error(errors, f"{path}.y", "Required property 'y' is missing") + if 'keys' in value: + _validate_OpenAI_MCPTool_allowed_tools_array(value['keys'], f"{path}.keys", errors) if 'type' in value: _validate_OpenAI_MoveParam_type(value['type'], f"{path}.type", errors) if 'x' in value: @@ -3769,6 +4225,8 @@ def _validate_OpenAI_ScrollParam(value: Any, path: str, errors: list[dict[str, s _append_error(errors, f"{path}.scroll_x", "Required property 'scroll_x' is missing") if 'scroll_y' not in value: _append_error(errors, f"{path}.scroll_y", "Required property 'scroll_y' is missing") + if 'keys' in value: + _validate_OpenAI_MCPTool_allowed_tools_array(value['keys'], f"{path}.keys", errors) if 'scroll_x' in value: _validate_OpenAI_ScrollParam_scroll_x(value['scroll_x'], f"{path}.scroll_x", errors) if 'scroll_y' in value: @@ -3895,6 +4353,56 @@ def _validate_OpenAI_LocalShellExecAction_type(value: Any, path: str, errors: li _append_type_mismatch(errors, path, 'string', value) return +def _validate_OpenAI_RealtimeMCPError_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _validate_OpenAI_RealtimeMcpErrorType(value, path, errors) + +def _validate_OpenAI_RealtimeMCPHTTPError(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'object'): + _append_type_mismatch(errors, path, 'object', value) + return + if 'type' not in value: + _append_error(errors, f"{path}.type", "Required property 'type' is missing") + if 'code' not in value: + _append_error(errors, f"{path}.code", "Required property 'code' is missing") + if 'message' not in value: + _append_error(errors, f"{path}.message", "Required property 'message' is missing") + if 'code' in value: + _validate_OpenAI_RealtimeMCPHTTPError_code(value['code'], f"{path}.code", errors) + if 'message' in value: + _validate_OpenAI_InputParam_string(value['message'], f"{path}.message", errors) + if 'type' in value: + _validate_OpenAI_RealtimeMCPHTTPError_type(value['type'], f"{path}.type", errors) + +def _validate_OpenAI_RealtimeMCPProtocolError(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'object'): + _append_type_mismatch(errors, path, 'object', value) + return + if 'type' not in value: + _append_error(errors, f"{path}.type", "Required property 'type' is missing") + if 'code' not in value: + _append_error(errors, f"{path}.code", "Required property 'code' is missing") + if 'message' not in value: + _append_error(errors, f"{path}.message", "Required property 'message' is missing") + if 'code' in value: + _validate_OpenAI_RealtimeMCPHTTPError_code(value['code'], f"{path}.code", errors) + if 'message' in value: + _validate_OpenAI_InputParam_string(value['message'], f"{path}.message", errors) + if 'type' in value: + _validate_OpenAI_RealtimeMCPProtocolError_type(value['type'], f"{path}.type", errors) + +def _validate_OpenAI_RealtimeMCPToolExecutionError(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'object'): + _append_type_mismatch(errors, path, 'object', value) + return + if 'type' not in value: + _append_error(errors, f"{path}.type", "Required property 'type' is missing") + if 'message' not in value: + _append_error(errors, f"{path}.message", "Required property 'message' is missing") + if 'message' in value: + _validate_OpenAI_InputParam_string(value['message'], f"{path}.message", errors) + if 'type' in value: + _validate_OpenAI_RealtimeMCPToolExecutionError_type(value['type'], f"{path}.type", errors) + def _validate_OpenAI_MCPListToolsTool(value: Any, path: str, errors: list[dict[str, str]]) -> None: if not _is_type(value, 'object'): _append_type_mismatch(errors, path, 'object', value) @@ -4061,6 +4569,24 @@ def _validate_OpenAI_ContainerNetworkPolicyParam(value: Any, path: str, errors: if _disc_value == 'disabled': _validate_OpenAI_ContainerNetworkPolicyDisabledParam(value, path, errors) +def _validate_OpenAI_FunctionToolParam_defer_loading(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'boolean'): + _append_type_mismatch(errors, path, 'boolean', value) + return + +def _validate_OpenAI_FunctionToolParam_name(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + +def _validate_OpenAI_FunctionToolParam_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _allowed_values = ('function',) + if value not in _allowed_values: + _append_error(errors, path, f"Invalid value '{value}'. Allowed: {', '.join(str(v) for v in _allowed_values)}") + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + def _validate_OpenAI_CodeInterpreterOutputLogs_logs(value: Any, path: str, errors: list[dict[str, str]]) -> None: if not _is_type(value, 'string'): _append_type_mismatch(errors, path, 'string', value) @@ -4317,6 +4843,8 @@ def _validate_OpenAI_InputFileContentParam(value: Any, path: str, errors: list[d return if 'type' not in value: _append_error(errors, f"{path}.type", "Required property 'type' is missing") + if 'detail' in value: + _validate_OpenAI_InputFileContentParam_detail(value['detail'], f"{path}.detail", errors) if 'file_data' in value: _validate_CreateResponse_instructions(value['file_data'], f"{path}.file_data", errors) if 'file_id' in value: @@ -4328,6 +4856,51 @@ def _validate_OpenAI_InputFileContentParam(value: Any, path: str, errors: list[d if 'type' in value: _validate_OpenAI_InputFileContentParam_type(value['type'], f"{path}.type", errors) +def _validate_OpenAI_RealtimeMcpErrorType(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _matched_union = False + if not _matched_union and _is_type(value, 'string'): + _branch_errors_0: list[dict[str, str]] = [] + _validate_OpenAI_InputParam_string(value, path, _branch_errors_0) + if not _branch_errors_0: + _matched_union = True + if not _matched_union and _is_type(value, 'string'): + _branch_errors_1: list[dict[str, str]] = [] + _validate_OpenAI_RealtimeMcpErrorType_2(value, path, _branch_errors_1) + if not _branch_errors_1: + _matched_union = True + if not _matched_union: + _append_error(errors, path, f"Expected RealtimeMcpErrorType to be a string value, got {_type_label(value)}") + return + +def _validate_OpenAI_RealtimeMCPHTTPError_code(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'integer'): + _append_type_mismatch(errors, path, 'integer', value) + return + +def _validate_OpenAI_RealtimeMCPHTTPError_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _allowed_values = ('http_error',) + if value not in _allowed_values: + _append_error(errors, path, f"Invalid value '{value}'. Allowed: {', '.join(str(v) for v in _allowed_values)}") + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + +def _validate_OpenAI_RealtimeMCPProtocolError_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _allowed_values = ('protocol_error',) + if value not in _allowed_values: + _append_error(errors, path, f"Invalid value '{value}'. Allowed: {', '.join(str(v) for v in _allowed_values)}") + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + +def _validate_OpenAI_RealtimeMCPToolExecutionError_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _allowed_values = ('tool_execution_error',) + if value not in _allowed_values: + _append_error(errors, path, f"Invalid value '{value}'. Allowed: {', '.join(str(v) for v in _allowed_values)}") + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + def _validate_OpenAI_MCPListToolsTool_annotations(value: Any, path: str, errors: list[dict[str, str]]) -> None: if value is None: return @@ -4372,6 +4945,8 @@ def _validate_OpenAI_MessageContent(value: Any, path: str, errors: list[dict[str _validate_OpenAI_MessageContentReasoningTextContent(value, path, errors) if _disc_value == 'refusal': _validate_OpenAI_MessageContentRefusalContent(value, path, errors) + if _disc_value == 'summary_text': + _validate_OpenAI_SummaryTextContent(value, path, errors) if _disc_value == 'text': _validate_OpenAI_TextContent(value, path, errors) @@ -4467,8 +5042,6 @@ def _validate_OpenAI_ContainerNetworkPolicyAllowlistParam(value: Any, path: str, _append_error(errors, f"{path}.allowed_domains", "Required property 'allowed_domains' is missing") if 'allowed_domains' in value: _validate_OpenAI_ContainerNetworkPolicyAllowlistParam_allowed_domains(value['allowed_domains'], f"{path}.allowed_domains", errors) - if 'domain_secrets' in value: - _validate_OpenAI_ContainerNetworkPolicyAllowlistParam_domain_secrets(value['domain_secrets'], f"{path}.domain_secrets", errors) if 'type' in value: _validate_OpenAI_ContainerNetworkPolicyAllowlistParam_type(value['type'], f"{path}.type", errors) @@ -4506,6 +5079,8 @@ def _validate_OpenAI_FunctionAndCustomToolCallOutputInputFileContent(value: Any, return if 'type' not in value: _append_error(errors, f"{path}.type", "Required property 'type' is missing") + if 'detail' in value: + _validate_OpenAI_InputFileContentParam_detail(value['detail'], f"{path}.detail", errors) if 'file_data' in value: _validate_OpenAI_FunctionAndCustomToolCallOutputInputFileContent_file_data(value['file_data'], f"{path}.file_data", errors) if 'file_id' in value: @@ -4579,6 +5154,9 @@ def _validate_OpenAI_InputImageContentParamAutoParam_type(value: Any, path: str, _append_type_mismatch(errors, path, 'string', value) return +def _validate_OpenAI_InputFileContentParam_detail(value: Any, path: str, errors: list[dict[str, str]]) -> None: + return + def _validate_OpenAI_InputFileContentParam_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: _allowed_values = ('input_file',) if value not in _allowed_values: @@ -4587,6 +5165,19 @@ def _validate_OpenAI_InputFileContentParam_type(value: Any, path: str, errors: l _append_type_mismatch(errors, path, 'string', value) return +def _validate_OpenAI_RealtimeMcpErrorType_2(value: Any, path: str, errors: list[dict[str, str]]) -> None: + _allowed_values, _enum_error = _enum_values('RealtimeMcpErrorType') + if _enum_error is not None: + _append_error(errors, path, _enum_error) + return + if _allowed_values is None: + return + if value not in _allowed_values: + _append_error(errors, path, f"Invalid value '{value}'. Allowed: {', '.join(str(v) for v in _allowed_values)}") + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + def _validate_OpenAI_MessageContent_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: _validate_OpenAI_MessageContentType(value, path, errors) @@ -4600,6 +5191,10 @@ def _validate_OpenAI_ComputerScreenshotContent(value: Any, path: str, errors: li _append_error(errors, f"{path}.image_url", "Required property 'image_url' is missing") if 'file_id' not in value: _append_error(errors, f"{path}.file_id", "Required property 'file_id' is missing") + if 'detail' not in value: + _append_error(errors, f"{path}.detail", "Required property 'detail' is missing") + if 'detail' in value: + _validate_OpenAI_ComputerScreenshotContent_detail(value['detail'], f"{path}.detail", errors) if 'file_id' in value: _validate_CreateResponse_instructions(value['file_id'], f"{path}.file_id", errors) if 'image_url' in value: @@ -4613,6 +5208,8 @@ def _validate_OpenAI_MessageContentInputFileContent(value: Any, path: str, error return if 'type' not in value: _append_error(errors, f"{path}.type", "Required property 'type' is missing") + if 'detail' in value: + _validate_OpenAI_InputFileContentParam_detail(value['detail'], f"{path}.detail", errors) if 'file_data' in value: _validate_OpenAI_FunctionAndCustomToolCallOutputInputFileContent_file_data(value['file_data'], f"{path}.file_data", errors) if 'file_id' in value: @@ -4779,7 +5376,7 @@ def _validate_OpenAI_WebSearchActionSearchSources(value: Any, path: str, errors: if 'type' in value: _validate_OpenAI_WebSearchActionSearchSources_type(value['type'], f"{path}.type", errors) if 'url' in value: - _validate_OpenAI_InputParam_string(value['url'], f"{path}.url", errors) + _validate_OpenAI_WebSearchActionSearchSources_url(value['url'], f"{path}.url", errors) def _validate_OpenAI_ContainerNetworkPolicyParamType(value: Any, path: str, errors: list[dict[str, str]]) -> None: _matched_union = False @@ -4804,13 +5401,6 @@ def _validate_OpenAI_ContainerNetworkPolicyAllowlistParam_allowed_domains(value: for _idx, _item in enumerate(value): _validate_OpenAI_InputParam_string(_item, f"{path}[{_idx}]", errors) -def _validate_OpenAI_ContainerNetworkPolicyAllowlistParam_domain_secrets(value: Any, path: str, errors: list[dict[str, str]]) -> None: - if not _is_type(value, 'array'): - _append_type_mismatch(errors, path, 'array', value) - return - for _idx, _item in enumerate(value): - _validate_OpenAI_ContainerNetworkPolicyAllowlistParam_domain_secrets_item(_item, f"{path}[{_idx}]", errors) - def _validate_OpenAI_ContainerNetworkPolicyAllowlistParam_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: _allowed_values = ('allowlist',) if value not in _allowed_values: @@ -4895,6 +5485,9 @@ def _validate_OpenAI_MessageContentType(value: Any, path: str, errors: list[dict _append_error(errors, path, f"Expected MessageContentType to be a string value, got {_type_label(value)}") return +def _validate_OpenAI_ComputerScreenshotContent_detail(value: Any, path: str, errors: list[dict[str, str]]) -> None: + return + def _validate_OpenAI_ComputerScreenshotContent_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: _allowed_values = ('computer_screenshot',) if value not in _allowed_values: @@ -4942,6 +5535,11 @@ def _validate_OpenAI_WebSearchActionSearchSources_type(value: Any, path: str, er _append_type_mismatch(errors, path, 'string', value) return +def _validate_OpenAI_WebSearchActionSearchSources_url(value: Any, path: str, errors: list[dict[str, str]]) -> None: + if not _is_type(value, 'string'): + _append_type_mismatch(errors, path, 'string', value) + return + def _validate_OpenAI_ContainerNetworkPolicyParamType_2(value: Any, path: str, errors: list[dict[str, str]]) -> None: _allowed_values, _enum_error = _enum_values('ContainerNetworkPolicyParamType') if _enum_error is not None: @@ -4955,9 +5553,6 @@ def _validate_OpenAI_ContainerNetworkPolicyParamType_2(value: Any, path: str, er _append_type_mismatch(errors, path, 'string', value) return -def _validate_OpenAI_ContainerNetworkPolicyAllowlistParam_domain_secrets_item(value: Any, path: str, errors: list[dict[str, str]]) -> None: - _validate_OpenAI_ContainerNetworkPolicyDomainSecretParam(value, path, errors) - def _validate_OpenAI_CoordParam_x(value: Any, path: str, errors: list[dict[str, str]]) -> None: if not _is_type(value, 'integer'): _append_type_mismatch(errors, path, 'integer', value) @@ -5036,23 +5631,6 @@ def _validate_OpenAI_LogProb(value: Any, path: str, errors: list[dict[str, str]] if 'top_logprobs' in value: _validate_OpenAI_LogProb_top_logprobs(value['top_logprobs'], f"{path}.top_logprobs", errors) -def _validate_OpenAI_ContainerNetworkPolicyDomainSecretParam(value: Any, path: str, errors: list[dict[str, str]]) -> None: - if not _is_type(value, 'object'): - _append_type_mismatch(errors, path, 'object', value) - return - if 'domain' not in value: - _append_error(errors, f"{path}.domain", "Required property 'domain' is missing") - if 'name' not in value: - _append_error(errors, f"{path}.name", "Required property 'name' is missing") - if 'value' not in value: - _append_error(errors, f"{path}.value", "Required property 'value' is missing") - if 'domain' in value: - _validate_OpenAI_ContainerNetworkPolicyDomainSecretParam_domain(value['domain'], f"{path}.domain", errors) - if 'name' in value: - _validate_OpenAI_ContainerNetworkPolicyDomainSecretParam_name(value['name'], f"{path}.name", errors) - if 'value' in value: - _validate_OpenAI_ContainerNetworkPolicyDomainSecretParam_value(value['value'], f"{path}.value", errors) - def _validate_OpenAI_Annotation_type(value: Any, path: str, errors: list[dict[str, str]]) -> None: _validate_OpenAI_AnnotationType(value, path, errors) @@ -5153,7 +5731,7 @@ def _validate_OpenAI_LogProb_bytes(value: Any, path: str, errors: list[dict[str, _append_type_mismatch(errors, path, 'array', value) return for _idx, _item in enumerate(value): - _validate_OpenAI_LogProb_bytes_item(_item, f"{path}[{_idx}]", errors) + _validate_OpenAI_RealtimeMCPHTTPError_code(_item, f"{path}[{_idx}]", errors) def _validate_OpenAI_LogProb_logprob(value: Any, path: str, errors: list[dict[str, str]]) -> None: if not _is_type(value, 'number'): @@ -5167,21 +5745,6 @@ def _validate_OpenAI_LogProb_top_logprobs(value: Any, path: str, errors: list[di for _idx, _item in enumerate(value): _validate_OpenAI_LogProb_top_logprobs_item(_item, f"{path}[{_idx}]", errors) -def _validate_OpenAI_ContainerNetworkPolicyDomainSecretParam_domain(value: Any, path: str, errors: list[dict[str, str]]) -> None: - if not _is_type(value, 'string'): - _append_type_mismatch(errors, path, 'string', value) - return - -def _validate_OpenAI_ContainerNetworkPolicyDomainSecretParam_name(value: Any, path: str, errors: list[dict[str, str]]) -> None: - if not _is_type(value, 'string'): - _append_type_mismatch(errors, path, 'string', value) - return - -def _validate_OpenAI_ContainerNetworkPolicyDomainSecretParam_value(value: Any, path: str, errors: list[dict[str, str]]) -> None: - if not _is_type(value, 'string'): - _append_type_mismatch(errors, path, 'string', value) - return - def _validate_OpenAI_AnnotationType(value: Any, path: str, errors: list[dict[str, str]]) -> None: _matched_union = False if not _matched_union and _is_type(value, 'string'): @@ -5285,11 +5848,6 @@ def _validate_OpenAI_UrlCitationBody_url(value: Any, path: str, errors: list[dic _append_type_mismatch(errors, path, 'string', value) return -def _validate_OpenAI_LogProb_bytes_item(value: Any, path: str, errors: list[dict[str, str]]) -> None: - if not _is_type(value, 'integer'): - _append_type_mismatch(errors, path, 'integer', value) - return - def _validate_OpenAI_LogProb_top_logprobs_item(value: Any, path: str, errors: list[dict[str, str]]) -> None: _validate_OpenAI_TopLogProb(value, path, errors) diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/models/__init__.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/models/__init__.py new file mode 100644 index 000000000000..7f8ed6e8f6e9 --- /dev/null +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/models/__init__.py @@ -0,0 +1,10 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. +"""Compatibility re-export for extension-owned OpenAI Responses model classes.""" + +from azure.ai.extensions.openai.responses._generated.sdk.models.models import * # type: ignore # noqa: F401,F403 + +try: + from azure.ai.extensions.openai.responses._generated.sdk.models.models import __all__ # type: ignore # noqa: F401 +except ImportError: + __all__: list[str] = [] diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/models/_enums.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/models/_enums.py new file mode 100644 index 000000000000..96ff3f3acda0 --- /dev/null +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/models/_enums.py @@ -0,0 +1,5 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. +"""Compatibility re-export for extension-owned OpenAI Responses models.""" + +from azure.ai.extensions.openai.responses._generated.sdk.models.models._enums import * # type: ignore # noqa: F401,F403 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/models/_models.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/models/_models.py new file mode 100644 index 000000000000..12c95af3cb41 --- /dev/null +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/models/_models.py @@ -0,0 +1,5 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. +"""Compatibility re-export for extension-owned OpenAI Responses models.""" + +from azure.ai.extensions.openai.responses._generated.sdk.models.models._models import * # type: ignore # noqa: F401,F403 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/models/_patch.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/models/_patch.py new file mode 100644 index 000000000000..3c631becc310 --- /dev/null +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/models/_patch.py @@ -0,0 +1,5 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. +"""Compatibility re-export for extension-owned OpenAI Responses models.""" + +from azure.ai.extensions.openai.responses._generated.sdk.models.models._patch import * # type: ignore # noqa: F401,F403 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/py.typed b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/py.typed new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/__init__.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/__init__.py deleted file mode 100644 index 9abd30ab9c84..000000000000 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/__init__.py +++ /dev/null @@ -1,11 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT license. -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- - -"""Model-only generated package surface.""" - -from .models import * # type: ignore # noqa: F401,F403 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/_patch.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/_patch.py deleted file mode 100644 index 87676c65a8f0..000000000000 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/_patch.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" - - -__all__: list[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/_types.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/_types.py deleted file mode 100644 index c99439ce635a..000000000000 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/_types.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, TYPE_CHECKING, Union - -if TYPE_CHECKING: - from . import models as _models -Filters = Union["_models.ComparisonFilter", "_models.CompoundFilter"] -ToolCallOutputContent = Union[dict[str, Any], str, list[Any]] -InputParam = Union[str, list["_models.Item"]] -ConversationParam = Union[str, "_models.ConversationParam_2"] -CreateResponseStreamingResponse = Union[ - "_models.ResponseAudioDeltaEvent", - "_models.ResponseAudioTranscriptDeltaEvent", - "_models.ResponseCodeInterpreterCallCodeDeltaEvent", - "_models.ResponseCodeInterpreterCallInProgressEvent", - "_models.ResponseCodeInterpreterCallInterpretingEvent", - "_models.ResponseContentPartAddedEvent", - "_models.ResponseCreatedEvent", - "_models.ResponseErrorEvent", - "_models.ResponseFileSearchCallInProgressEvent", - "_models.ResponseFileSearchCallSearchingEvent", - "_models.ResponseFunctionCallArgumentsDeltaEvent", - "_models.ResponseInProgressEvent", - "_models.ResponseFailedEvent", - "_models.ResponseIncompleteEvent", - "_models.ResponseOutputItemAddedEvent", - "_models.ResponseReasoningSummaryPartAddedEvent", - "_models.ResponseReasoningSummaryTextDeltaEvent", - "_models.ResponseReasoningTextDeltaEvent", - "_models.ResponseRefusalDeltaEvent", - "_models.ResponseTextDeltaEvent", - "_models.ResponseWebSearchCallInProgressEvent", - "_models.ResponseWebSearchCallSearchingEvent", - "_models.ResponseImageGenCallGeneratingEvent", - "_models.ResponseImageGenCallInProgressEvent", - "_models.ResponseImageGenCallPartialImageEvent", - "_models.ResponseMCPCallArgumentsDeltaEvent", - "_models.ResponseMCPCallFailedEvent", - "_models.ResponseMCPCallInProgressEvent", - "_models.ResponseMCPListToolsFailedEvent", - "_models.ResponseMCPListToolsInProgressEvent", - "_models.ResponseOutputTextAnnotationAddedEvent", - "_models.ResponseQueuedEvent", - "_models.ResponseCustomToolCallInputDeltaEvent", - "_models.ResponseAudioDoneEvent", - "_models.ResponseAudioTranscriptDoneEvent", - "_models.ResponseCodeInterpreterCallCodeDoneEvent", - "_models.ResponseCodeInterpreterCallCompletedEvent", - "_models.ResponseCompletedEvent", - "_models.ResponseContentPartDoneEvent", - "_models.ResponseFileSearchCallCompletedEvent", - "_models.ResponseFunctionCallArgumentsDoneEvent", - "_models.ResponseOutputItemDoneEvent", - "_models.ResponseReasoningSummaryPartDoneEvent", - "_models.ResponseReasoningSummaryTextDoneEvent", - "_models.ResponseReasoningTextDoneEvent", - "_models.ResponseRefusalDoneEvent", - "_models.ResponseTextDoneEvent", - "_models.ResponseWebSearchCallCompletedEvent", - "_models.ResponseImageGenCallCompletedEvent", - "_models.ResponseMCPCallArgumentsDoneEvent", - "_models.ResponseMCPCallCompletedEvent", - "_models.ResponseMCPListToolsCompletedEvent", - "_models.ResponseCustomToolCallInputDoneEvent", -] diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/_utils/__init__.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/_utils/__init__.py deleted file mode 100644 index 8026245c2abc..000000000000 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/_utils/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/_utils/model_base.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/_utils/model_base.py deleted file mode 100644 index 1139045a6acc..000000000000 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/_utils/model_base.py +++ /dev/null @@ -1,1461 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=protected-access, broad-except - -import copy -import calendar -import decimal -import functools -import sys -import logging -import base64 -import re -import typing -import enum -import email.utils -from datetime import datetime, date, time, timedelta, timezone -from json import JSONEncoder -import xml.etree.ElementTree as ET -from collections.abc import MutableMapping -from typing_extensions import Self -import isodate -from azure.core.exceptions import DeserializationError -from azure.core import CaseInsensitiveEnumMeta -from azure.core.pipeline import PipelineResponse -from azure.core.serialization import _Null -from azure.core.rest import HttpResponse - -_LOGGER = logging.getLogger(__name__) - -__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] - -TZ_UTC = timezone.utc -_T = typing.TypeVar("_T") -_NONE_TYPE = type(None) - - -def _timedelta_as_isostr(td: timedelta) -> str: - """Converts a datetime.timedelta object into an ISO 8601 formatted string, e.g. 'P4DT12H30M05S' - - Function adapted from the Tin Can Python project: https://github.com/RusticiSoftware/TinCanPython - - :param timedelta td: The timedelta to convert - :rtype: str - :return: ISO8601 version of this timedelta - """ - - # Split seconds to larger units - seconds = td.total_seconds() - minutes, seconds = divmod(seconds, 60) - hours, minutes = divmod(minutes, 60) - days, hours = divmod(hours, 24) - - days, hours, minutes = list(map(int, (days, hours, minutes))) - seconds = round(seconds, 6) - - # Build date - date_str = "" - if days: - date_str = "%sD" % days - - if hours or minutes or seconds: - # Build time - time_str = "T" - - # Hours - bigger_exists = date_str or hours - if bigger_exists: - time_str += "{:02}H".format(hours) - - # Minutes - bigger_exists = bigger_exists or minutes - if bigger_exists: - time_str += "{:02}M".format(minutes) - - # Seconds - try: - if seconds.is_integer(): - seconds_string = "{:02}".format(int(seconds)) - else: - # 9 chars long w/ leading 0, 6 digits after decimal - seconds_string = "%09.6f" % seconds - # Remove trailing zeros - seconds_string = seconds_string.rstrip("0") - except AttributeError: # int.is_integer() raises - seconds_string = "{:02}".format(seconds) - - time_str += "{}S".format(seconds_string) - else: - time_str = "" - - return "P" + date_str + time_str - - -def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: - encoded = base64.b64encode(o).decode() - if format == "base64url": - return encoded.strip("=").replace("+", "-").replace("/", "_") - return encoded - - -def _serialize_datetime(o, format: typing.Optional[str] = None): - if hasattr(o, "year") and hasattr(o, "hour"): - if format == "rfc7231": - return email.utils.format_datetime(o, usegmt=True) - if format == "unix-timestamp": - return int(calendar.timegm(o.utctimetuple())) - - # astimezone() fails for naive times in Python 2.7, so make make sure o is aware (tzinfo is set) - if not o.tzinfo: - iso_formatted = o.replace(tzinfo=TZ_UTC).isoformat() - else: - iso_formatted = o.astimezone(TZ_UTC).isoformat() - # Replace the trailing "+00:00" UTC offset with "Z" (RFC 3339: https://www.ietf.org/rfc/rfc3339.txt) - return iso_formatted.replace("+00:00", "Z") - # Next try datetime.date or datetime.time - return o.isoformat() - - -def _is_readonly(p): - try: - return p._visibility == ["read"] - except AttributeError: - return False - - -class SdkJSONEncoder(JSONEncoder): - """A JSON encoder that's capable of serializing datetime objects and bytes.""" - - def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): - super().__init__(*args, **kwargs) - self.exclude_readonly = exclude_readonly - self.format = format - - def default(self, o): # pylint: disable=too-many-return-statements - if _is_model(o): - if self.exclude_readonly: - readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] - return {k: v for k, v in o.items() if k not in readonly_props} - return dict(o.items()) - try: - return super(SdkJSONEncoder, self).default(o) - except TypeError: - if isinstance(o, _Null): - return None - if isinstance(o, decimal.Decimal): - return float(o) - if isinstance(o, (bytes, bytearray)): - return _serialize_bytes(o, self.format) - try: - # First try datetime.datetime - return _serialize_datetime(o, self.format) - except AttributeError: - pass - # Last, try datetime.timedelta - try: - return _timedelta_as_isostr(o) - except AttributeError: - # This will be raised when it hits value.total_seconds in the method above - pass - return super(SdkJSONEncoder, self).default(o) - - -_VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") -_VALID_RFC7231 = re.compile( - r"(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s\d{2}\s" - r"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT" -) - -_ARRAY_ENCODE_MAPPING = { - "pipeDelimited": "|", - "spaceDelimited": " ", - "commaDelimited": ",", - "newlineDelimited": "\n", -} - - -def _deserialize_array_encoded(delimit: str, attr): - if isinstance(attr, str): - if attr == "": - return [] - return attr.split(delimit) - return attr - - -def _deserialize_datetime(attr: typing.Union[str, datetime]) -> datetime: - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: ~datetime.datetime - :returns: The datetime object from that input - """ - if isinstance(attr, datetime): - # i'm already deserialized - return attr - attr = attr.upper() - match = _VALID_DATE.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - return date_obj # type: ignore[no-any-return] - - -def _deserialize_datetime_rfc7231(attr: typing.Union[str, datetime]) -> datetime: - """Deserialize RFC7231 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: ~datetime.datetime - :returns: The datetime object from that input - """ - if isinstance(attr, datetime): - # i'm already deserialized - return attr - match = _VALID_RFC7231.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - return email.utils.parsedate_to_datetime(attr) - - -def _deserialize_datetime_unix_timestamp(attr: typing.Union[float, datetime]) -> datetime: - """Deserialize unix timestamp into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: ~datetime.datetime - :returns: The datetime object from that input - """ - if isinstance(attr, datetime): - # i'm already deserialized - return attr - return datetime.fromtimestamp(attr, TZ_UTC) - - -def _deserialize_date(attr: typing.Union[str, date]) -> date: - """Deserialize ISO-8601 formatted string into Date object. - :param str attr: response string to be deserialized. - :rtype: date - :returns: The date object from that input - """ - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - if isinstance(attr, date): - return attr - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) # type: ignore - - -def _deserialize_time(attr: typing.Union[str, time]) -> time: - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :returns: The time object from that input - """ - if isinstance(attr, time): - return attr - return isodate.parse_time(attr) # type: ignore[no-any-return] - - -def _deserialize_bytes(attr): - if isinstance(attr, (bytes, bytearray)): - return attr - return bytes(base64.b64decode(attr)) - - -def _deserialize_bytes_base64(attr): - if isinstance(attr, (bytes, bytearray)): - return attr - padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore - attr = attr + padding # type: ignore - encoded = attr.replace("-", "+").replace("_", "/") - return bytes(base64.b64decode(encoded)) - - -def _deserialize_duration(attr): - if isinstance(attr, timedelta): - return attr - return isodate.parse_duration(attr) - - -def _deserialize_decimal(attr): - if isinstance(attr, decimal.Decimal): - return attr - return decimal.Decimal(str(attr)) - - -def _deserialize_int_as_str(attr): - if isinstance(attr, int): - return attr - return int(attr) - - -_DESERIALIZE_MAPPING = { - datetime: _deserialize_datetime, - date: _deserialize_date, - time: _deserialize_time, - bytes: _deserialize_bytes, - bytearray: _deserialize_bytes, - timedelta: _deserialize_duration, - typing.Any: lambda x: x, - decimal.Decimal: _deserialize_decimal, -} - -_DESERIALIZE_MAPPING_WITHFORMAT = { - "rfc3339": _deserialize_datetime, - "rfc7231": _deserialize_datetime_rfc7231, - "unix-timestamp": _deserialize_datetime_unix_timestamp, - "base64": _deserialize_bytes, - "base64url": _deserialize_bytes_base64, -} - - -def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): - if annotation is int and rf and rf._format == "str": - return _deserialize_int_as_str - if annotation is str and rf and rf._format in _ARRAY_ENCODE_MAPPING: - return functools.partial(_deserialize_array_encoded, _ARRAY_ENCODE_MAPPING[rf._format]) - if rf and rf._format: - return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) - return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore - - -def _get_type_alias_type(module_name: str, alias_name: str): - types = { - k: v - for k, v in sys.modules[module_name].__dict__.items() - if isinstance(v, typing._GenericAlias) # type: ignore - } - if alias_name not in types: - return alias_name - return types[alias_name] - - -def _get_model(module_name: str, model_name: str): - models = {k: v for k, v in sys.modules[module_name].__dict__.items() if isinstance(v, type)} - module_end = module_name.rsplit(".", 1)[0] - models.update({k: v for k, v in sys.modules[module_end].__dict__.items() if isinstance(v, type)}) - if isinstance(model_name, str): - model_name = model_name.split(".")[-1] - if model_name not in models: - return model_name - return models[model_name] - - -_UNSET = object() - - -class _MyMutableMapping(MutableMapping[str, typing.Any]): - def __init__(self, data: dict[str, typing.Any]) -> None: - self._data = data - - def __contains__(self, key: typing.Any) -> bool: - return key in self._data - - def __getitem__(self, key: str) -> typing.Any: - # If this key has been deserialized (for mutable types), we need to handle serialization - if hasattr(self, "_attr_to_rest_field"): - cache_attr = f"_deserialized_{key}" - if hasattr(self, cache_attr): - rf = _get_rest_field(getattr(self, "_attr_to_rest_field"), key) - if rf: - value = self._data.get(key) - if isinstance(value, (dict, list, set)): - # For mutable types, serialize and return - # But also update _data with serialized form and clear flag - # so mutations via this returned value affect _data - serialized = _serialize(value, rf._format) - # If serialized form is same type (no transformation needed), - # return _data directly so mutations work - if isinstance(serialized, type(value)) and serialized == value: - return self._data.get(key) - # Otherwise return serialized copy and clear flag - try: - object.__delattr__(self, cache_attr) - except AttributeError: - pass - # Store serialized form back - self._data[key] = serialized - return serialized - return self._data.__getitem__(key) - - def __setitem__(self, key: str, value: typing.Any) -> None: - # Clear any cached deserialized value when setting through dictionary access - cache_attr = f"_deserialized_{key}" - try: - object.__delattr__(self, cache_attr) - except AttributeError: - pass - self._data.__setitem__(key, value) - - def __delitem__(self, key: str) -> None: - self._data.__delitem__(key) - - def __iter__(self) -> typing.Iterator[typing.Any]: - return self._data.__iter__() - - def __len__(self) -> int: - return self._data.__len__() - - def __ne__(self, other: typing.Any) -> bool: - return not self.__eq__(other) - - def keys(self) -> typing.KeysView[str]: - """ - :returns: a set-like object providing a view on D's keys - :rtype: ~typing.KeysView - """ - return self._data.keys() - - def values(self) -> typing.ValuesView[typing.Any]: - """ - :returns: an object providing a view on D's values - :rtype: ~typing.ValuesView - """ - return self._data.values() - - def items(self) -> typing.ItemsView[str, typing.Any]: - """ - :returns: set-like object providing a view on D's items - :rtype: ~typing.ItemsView - """ - return self._data.items() - - def get(self, key: str, default: typing.Any = None) -> typing.Any: - """ - Get the value for key if key is in the dictionary, else default. - :param str key: The key to look up. - :param any default: The value to return if key is not in the dictionary. Defaults to None - :returns: D[k] if k in D, else d. - :rtype: any - """ - try: - return self[key] - except KeyError: - return default - - @typing.overload - def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ - - @typing.overload - def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs - - @typing.overload - def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs - - def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: - """ - Removes specified key and return the corresponding value. - :param str key: The key to pop. - :param any default: The value to return if key is not in the dictionary - :returns: The value corresponding to the key. - :rtype: any - :raises KeyError: If key is not found and default is not given. - """ - if default is _UNSET: - return self._data.pop(key) - return self._data.pop(key, default) - - def popitem(self) -> tuple[str, typing.Any]: - """ - Removes and returns some (key, value) pair - :returns: The (key, value) pair. - :rtype: tuple - :raises KeyError: if D is empty. - """ - return self._data.popitem() - - def clear(self) -> None: - """ - Remove all items from D. - """ - self._data.clear() - - def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ - """ - Updates D from mapping/iterable E and F. - :param any args: Either a mapping object or an iterable of key-value pairs. - """ - self._data.update(*args, **kwargs) - - @typing.overload - def setdefault(self, key: str, default: None = None) -> None: ... - - @typing.overload - def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs - - def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: - """ - Same as calling D.get(k, d), and setting D[k]=d if k not found - :param str key: The key to look up. - :param any default: The value to set if key is not in the dictionary - :returns: D[k] if k in D, else d. - :rtype: any - """ - if default is _UNSET: - return self._data.setdefault(key) - return self._data.setdefault(key, default) - - def __eq__(self, other: typing.Any) -> bool: - if isinstance(other, _MyMutableMapping): - return self._data == other._data - try: - other_model = self.__class__(other) - except Exception: - return False - return self._data == other_model._data - - def __repr__(self) -> str: - return str(self._data) - - -def _is_model(obj: typing.Any) -> bool: - return getattr(obj, "_is_model", False) - - -def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-many-return-statements - if isinstance(o, list): - if format in _ARRAY_ENCODE_MAPPING and all(isinstance(x, str) for x in o): - return _ARRAY_ENCODE_MAPPING[format].join(o) - return [_serialize(x, format) for x in o] - if isinstance(o, dict): - return {k: _serialize(v, format) for k, v in o.items()} - if isinstance(o, set): - return {_serialize(x, format) for x in o} - if isinstance(o, tuple): - return tuple(_serialize(x, format) for x in o) - if isinstance(o, (bytes, bytearray)): - return _serialize_bytes(o, format) - if isinstance(o, decimal.Decimal): - return float(o) - if isinstance(o, enum.Enum): - return o.value - if isinstance(o, int): - if format == "str": - return str(o) - return o - try: - # First try datetime.datetime - return _serialize_datetime(o, format) - except AttributeError: - pass - # Last, try datetime.timedelta - try: - return _timedelta_as_isostr(o) - except AttributeError: - # This will be raised when it hits value.total_seconds in the method above - pass - return o - - -def _get_rest_field(attr_to_rest_field: dict[str, "_RestField"], rest_name: str) -> typing.Optional["_RestField"]: - try: - return next(rf for rf in attr_to_rest_field.values() if rf._rest_name == rest_name) - except StopIteration: - return None - - -def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typing.Any: - if not rf: - return _serialize(value, None) - if rf._is_multipart_file_input: - return value - if rf._is_model: - return _deserialize(rf._type, value) - if isinstance(value, ET.Element): - value = _deserialize(rf._type, value) - return _serialize(value, rf._format) - - -class Model(_MyMutableMapping): - _is_model = True - # label whether current class's _attr_to_rest_field has been calculated - # could not see _attr_to_rest_field directly because subclass inherits it from parent class - _calculated: set[str] = set() - - def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: - class_name = self.__class__.__name__ - if len(args) > 1: - raise TypeError(f"{class_name}.__init__() takes 2 positional arguments but {len(args) + 1} were given") - dict_to_pass = { - rest_field._rest_name: rest_field._default - for rest_field in self._attr_to_rest_field.values() - if rest_field._default is not _UNSET - } - if args: - if isinstance(args[0], ET.Element): - dict_to_pass.update(self._init_from_xml(args[0])) - else: - dict_to_pass.update( - {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} - ) - else: - non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] - if non_attr_kwargs: - # actual type errors only throw the first wrong keyword arg they see, so following that. - raise TypeError(f"{class_name}.__init__() got an unexpected keyword argument '{non_attr_kwargs[0]}'") - dict_to_pass.update( - { - self._attr_to_rest_field[k]._rest_name: _create_value(self._attr_to_rest_field[k], v) - for k, v in kwargs.items() - if v is not None - } - ) - super().__init__(dict_to_pass) - - def _init_from_xml(self, element: ET.Element) -> dict[str, typing.Any]: - """Deserialize an XML element into a dict mapping rest field names to values. - - :param ET.Element element: The XML element to deserialize from. - :returns: A dictionary of rest_name to deserialized value pairs. - :rtype: dict - """ - result: dict[str, typing.Any] = {} - model_meta = getattr(self, "_xml", {}) - existed_attr_keys: list[str] = [] - - for rf in self._attr_to_rest_field.values(): - prop_meta = getattr(rf, "_xml", {}) - xml_name = prop_meta.get("name", rf._rest_name) - xml_ns = _resolve_xml_ns(prop_meta, model_meta) - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - - # attribute - if prop_meta.get("attribute", False) and element.get(xml_name) is not None: - existed_attr_keys.append(xml_name) - result[rf._rest_name] = _deserialize(rf._type, element.get(xml_name)) - continue - - # unwrapped element is array - if prop_meta.get("unwrapped", False): - # unwrapped array could either use prop items meta/prop meta - _items_name = prop_meta.get("itemsName") - if _items_name: - xml_name = _items_name - _items_ns = prop_meta.get("itemsNs") - if _items_ns is not None: - xml_ns = _items_ns - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - items = element.findall(xml_name) # pyright: ignore - if len(items) > 0: - existed_attr_keys.append(xml_name) - result[rf._rest_name] = _deserialize(rf._type, items) - elif not rf._is_optional: - existed_attr_keys.append(xml_name) - result[rf._rest_name] = [] - continue - - # text element is primitive type - if prop_meta.get("text", False): - if element.text is not None: - result[rf._rest_name] = _deserialize(rf._type, element.text) - continue - - # wrapped element could be normal property or array, it should only have one element - item = element.find(xml_name) - if item is not None: - existed_attr_keys.append(xml_name) - result[rf._rest_name] = _deserialize(rf._type, item) - - # rest thing is additional properties - for e in element: - if e.tag not in existed_attr_keys: - result[e.tag] = _convert_element(e) - - return result - - def copy(self) -> "Model": - return Model(self.__dict__) - - def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: - if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: - # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', - # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' - mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order - attr_to_rest_field: dict[str, _RestField] = { # map attribute name to rest_field property - k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") - } - annotations = { - k: v - for mro_class in mros - if hasattr(mro_class, "__annotations__") - for k, v in mro_class.__annotations__.items() - } - for attr, rf in attr_to_rest_field.items(): - rf._module = cls.__module__ - if not rf._type: - rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) - if not rf._rest_name_input: - rf._rest_name_input = attr - cls._attr_to_rest_field: dict[str, _RestField] = dict(attr_to_rest_field.items()) - cls._backcompat_attr_to_rest_field: dict[str, _RestField] = { - Model._get_backcompat_attribute_name(cls._attr_to_rest_field, attr): rf - for attr, rf in cls._attr_to_rest_field.items() - } - cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") - - return super().__new__(cls) - - def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: - for base in cls.__bases__: - if hasattr(base, "__mapping__"): - base.__mapping__[discriminator or cls.__name__] = cls # type: ignore - - @classmethod - def _get_backcompat_attribute_name(cls, attr_to_rest_field: dict[str, "_RestField"], attr_name: str) -> str: - rest_field_obj = attr_to_rest_field.get(attr_name) # pylint: disable=protected-access - if rest_field_obj is None: - return attr_name - original_tsp_name = getattr(rest_field_obj, "_original_tsp_name", None) # pylint: disable=protected-access - if original_tsp_name: - return original_tsp_name - return attr_name - - @classmethod - def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: - for v in cls.__dict__.values(): - if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: - return v - return None - - @classmethod - def _deserialize(cls, data, exist_discriminators): - if not hasattr(cls, "__mapping__"): - return cls(data) - discriminator = cls._get_discriminator(exist_discriminators) - if discriminator is None: - return cls(data) - exist_discriminators.append(discriminator._rest_name) - if isinstance(data, ET.Element): - model_meta = getattr(cls, "_xml", {}) - prop_meta = getattr(discriminator, "_xml", {}) - xml_name = prop_meta.get("name", discriminator._rest_name) - xml_ns = _resolve_xml_ns(prop_meta, model_meta) - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - - if data.get(xml_name) is not None: - discriminator_value = data.get(xml_name) - else: - discriminator_value = data.find(xml_name).text # pyright: ignore - else: - discriminator_value = data.get(discriminator._rest_name) - mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member - return mapped_cls._deserialize(data, exist_discriminators) - - def as_dict(self, *, exclude_readonly: bool = False) -> dict[str, typing.Any]: - """Return a dict that can be turned into json using json.dump. - - :keyword bool exclude_readonly: Whether to remove the readonly properties. - :returns: A dict JSON compatible object - :rtype: dict - """ - - result = {} - readonly_props = [] - if exclude_readonly: - readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] - for k, v in self.items(): - if exclude_readonly and k in readonly_props: # pyright: ignore - continue - is_multipart_file_input = False - try: - is_multipart_file_input = next( - rf for rf in self._attr_to_rest_field.values() if rf._rest_name == k - )._is_multipart_file_input - except StopIteration: - pass - result[k] = v if is_multipart_file_input else Model._as_dict_value(v, exclude_readonly=exclude_readonly) - return result - - @staticmethod - def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: - if v is None or isinstance(v, _Null): - return None - if isinstance(v, (list, tuple, set)): - return type(v)(Model._as_dict_value(x, exclude_readonly=exclude_readonly) for x in v) - if isinstance(v, dict): - return {dk: Model._as_dict_value(dv, exclude_readonly=exclude_readonly) for dk, dv in v.items()} - return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v - - -def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): - if _is_model(obj): - return obj - return _deserialize(model_deserializer, obj) - - -def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): - if obj is None: - return obj - return _deserialize_with_callable(if_obj_deserializer, obj) - - -def _deserialize_with_union(deserializers, obj): - for deserializer in deserializers: - try: - return _deserialize(deserializer, obj) - except DeserializationError: - pass - raise DeserializationError() - - -def _deserialize_dict( - value_deserializer: typing.Optional[typing.Callable], - module: typing.Optional[str], - obj: dict[typing.Any, typing.Any], -): - if obj is None: - return obj - if isinstance(obj, ET.Element): - obj = {child.tag: child for child in obj} - return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} - - -def _deserialize_multiple_sequence( - entry_deserializers: list[typing.Optional[typing.Callable]], - module: typing.Optional[str], - obj, -): - if obj is None: - return obj - return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) - - -def _is_array_encoded_deserializer(deserializer: functools.partial) -> bool: - return ( - isinstance(deserializer, functools.partial) - and isinstance(deserializer.args[0], functools.partial) - and deserializer.args[0].func == _deserialize_array_encoded # pylint: disable=comparison-with-callable - ) - - -def _deserialize_sequence( - deserializer: typing.Optional[typing.Callable], - module: typing.Optional[str], - obj, -): - if obj is None: - return obj - if isinstance(obj, ET.Element): - obj = list(obj) - - # encoded string may be deserialized to sequence - if isinstance(obj, str) and isinstance(deserializer, functools.partial): - # for list[str] - if _is_array_encoded_deserializer(deserializer): - return deserializer(obj) - - # for list[Union[...]] - if isinstance(deserializer.args[0], list): - for sub_deserializer in deserializer.args[0]: - if _is_array_encoded_deserializer(sub_deserializer): - return sub_deserializer(obj) - - if isinstance(obj, str): - raise DeserializationError() - return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) - - -def _sorted_annotations(types: list[typing.Any]) -> list[typing.Any]: - return sorted( - types, - key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), - ) - - -def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-statements, too-many-branches - annotation: typing.Any, - module: typing.Optional[str], - rf: typing.Optional["_RestField"] = None, -) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: - if not annotation: - return None - - # is it a type alias? - if isinstance(annotation, str): - if module is not None: - annotation = _get_type_alias_type(module, annotation) - - # is it a forward ref / in quotes? - if isinstance(annotation, (str, typing.ForwardRef)): - try: - model_name = annotation.__forward_arg__ # type: ignore - except AttributeError: - model_name = annotation - if module is not None: - annotation = _get_model(module, model_name) # type: ignore - - try: - if module and _is_model(annotation): - if rf: - rf._is_model = True - - return functools.partial(_deserialize_model, annotation) # pyright: ignore - except Exception: - pass - - # is it a literal? - try: - if annotation.__origin__ is typing.Literal: # pyright: ignore - return None - except AttributeError: - pass - - # is it optional? - try: - if any(a is _NONE_TYPE for a in annotation.__args__): # pyright: ignore - if rf: - rf._is_optional = True - if len(annotation.__args__) <= 2: # pyright: ignore - if_obj_deserializer = _get_deserialize_callable_from_annotation( - next(a for a in annotation.__args__ if a is not _NONE_TYPE), module, rf # pyright: ignore - ) - - return functools.partial(_deserialize_with_optional, if_obj_deserializer) - # the type is Optional[Union[...]], we need to remove the None type from the Union - annotation_copy = copy.copy(annotation) - annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a is not _NONE_TYPE] # pyright: ignore - return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) - except AttributeError: - pass - - # is it union? - if getattr(annotation, "__origin__", None) is typing.Union: - # initial ordering is we make `string` the last deserialization option, because it is often them most generic - deserializers = [ - _get_deserialize_callable_from_annotation(arg, module, rf) - for arg in _sorted_annotations(annotation.__args__) # pyright: ignore - ] - - return functools.partial(_deserialize_with_union, deserializers) - - try: - annotation_name = ( - annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore - ) - if annotation_name.lower() == "dict": - value_deserializer = _get_deserialize_callable_from_annotation( - annotation.__args__[1], module, rf # pyright: ignore - ) - - return functools.partial( - _deserialize_dict, - value_deserializer, - module, - ) - except (AttributeError, IndexError): - pass - try: - annotation_name = ( - annotation.__name__ if hasattr(annotation, "__name__") else annotation._name # pyright: ignore - ) - if annotation_name.lower() in ["list", "set", "tuple", "sequence"]: - if len(annotation.__args__) > 1: # pyright: ignore - entry_deserializers = [ - _get_deserialize_callable_from_annotation(dt, module, rf) - for dt in annotation.__args__ # pyright: ignore - ] - return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) - deserializer = _get_deserialize_callable_from_annotation( - annotation.__args__[0], module, rf # pyright: ignore - ) - - return functools.partial(_deserialize_sequence, deserializer, module) - except (TypeError, IndexError, AttributeError, SyntaxError): - pass - - def _deserialize_default( - deserializer, - obj, - ): - if obj is None: - return obj - try: - return _deserialize_with_callable(deserializer, obj) - except Exception: - pass - return obj - - if get_deserializer(annotation, rf): - return functools.partial(_deserialize_default, get_deserializer(annotation, rf)) - - return functools.partial(_deserialize_default, annotation) - - -def _deserialize_with_callable( - deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], - value: typing.Any, -): # pylint: disable=too-many-return-statements - try: - if value is None or isinstance(value, _Null): - return None - if isinstance(value, ET.Element): - if deserializer is str: - return value.text or "" - if deserializer is int: - return int(value.text) if value.text else None - if deserializer is float: - return float(value.text) if value.text else None - if deserializer is bool: - return value.text == "true" if value.text else None - if deserializer and deserializer in _DESERIALIZE_MAPPING.values(): - return deserializer(value.text) if value.text else None - if deserializer and deserializer in _DESERIALIZE_MAPPING_WITHFORMAT.values(): - return deserializer(value.text) if value.text else None - if deserializer is None: - return value - if deserializer in [int, float, bool]: - return deserializer(value) - if isinstance(deserializer, CaseInsensitiveEnumMeta): - try: - return deserializer(value.text if isinstance(value, ET.Element) else value) - except ValueError: - # for unknown value, return raw value - return value.text if isinstance(value, ET.Element) else value - if isinstance(deserializer, type) and issubclass(deserializer, Model): - return deserializer._deserialize(value, []) - return typing.cast(typing.Callable[[typing.Any], typing.Any], deserializer)(value) - except Exception as e: - raise DeserializationError() from e - - -def _deserialize( - deserializer: typing.Any, - value: typing.Any, - module: typing.Optional[str] = None, - rf: typing.Optional["_RestField"] = None, - format: typing.Optional[str] = None, -) -> typing.Any: - if isinstance(value, PipelineResponse): - value = value.http_response.json() - if rf is None and format: - rf = _RestField(format=format) - if not isinstance(deserializer, functools.partial): - deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) - return _deserialize_with_callable(deserializer, value) - - -def _failsafe_deserialize( - deserializer: typing.Any, - response: HttpResponse, - module: typing.Optional[str] = None, - rf: typing.Optional["_RestField"] = None, - format: typing.Optional[str] = None, -) -> typing.Any: - try: - return _deserialize(deserializer, response.json(), module, rf, format) - except Exception: # pylint: disable=broad-except - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - -def _failsafe_deserialize_xml( - deserializer: typing.Any, - response: HttpResponse, -) -> typing.Any: - try: - return _deserialize_xml(deserializer, response.text()) - except Exception: # pylint: disable=broad-except - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - -# pylint: disable=too-many-instance-attributes -class _RestField: - def __init__( - self, - *, - name: typing.Optional[str] = None, - type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin - is_discriminator: bool = False, - visibility: typing.Optional[list[str]] = None, - default: typing.Any = _UNSET, - format: typing.Optional[str] = None, - is_multipart_file_input: bool = False, - xml: typing.Optional[dict[str, typing.Any]] = None, - original_tsp_name: typing.Optional[str] = None, - ): - self._type = type - self._rest_name_input = name - self._module: typing.Optional[str] = None - self._is_discriminator = is_discriminator - self._visibility = visibility - self._is_model = False - self._is_optional = False - self._default = default - self._format = format - self._is_multipart_file_input = is_multipart_file_input - self._xml = xml if xml is not None else {} - self._original_tsp_name = original_tsp_name - - @property - def _class_type(self) -> typing.Any: - result = getattr(self._type, "args", [None])[0] - # type may be wrapped by nested functools.partial so we need to check for that - if isinstance(result, functools.partial): - return getattr(result, "args", [None])[0] - return result - - @property - def _rest_name(self) -> str: - if self._rest_name_input is None: - raise ValueError("Rest name was never set") - return self._rest_name_input - - def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin - # by this point, type and rest_name will have a value bc we default - # them in __new__ of the Model class - # Use _data.get() directly to avoid triggering __getitem__ which clears the cache - item = obj._data.get(self._rest_name) - if item is None: - return item - if self._is_model: - return item - - # For mutable types, we want mutations to directly affect _data - # Check if we've already deserialized this value - cache_attr = f"_deserialized_{self._rest_name}" - if hasattr(obj, cache_attr): - # Return the value from _data directly (it's been deserialized in place) - return obj._data.get(self._rest_name) - - deserialized = _deserialize(self._type, _serialize(item, self._format), rf=self) - - # For mutable types, store the deserialized value back in _data - # so mutations directly affect _data - if isinstance(deserialized, (dict, list, set)): - obj._data[self._rest_name] = deserialized - object.__setattr__(obj, cache_attr, True) # Mark as deserialized - return deserialized - - return deserialized - - def __set__(self, obj: Model, value) -> None: - # Clear the cached deserialized object when setting a new value - cache_attr = f"_deserialized_{self._rest_name}" - if hasattr(obj, cache_attr): - object.__delattr__(obj, cache_attr) - - if value is None: - # we want to wipe out entries if users set attr to None - try: - obj.__delitem__(self._rest_name) - except KeyError: - pass - return - if self._is_model: - if not _is_model(value): - value = _deserialize(self._type, value) - obj.__setitem__(self._rest_name, value) - return - obj.__setitem__(self._rest_name, _serialize(value, self._format)) - - def _get_deserialize_callable_from_annotation( - self, annotation: typing.Any - ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: - return _get_deserialize_callable_from_annotation(annotation, self._module, self) - - -def rest_field( - *, - name: typing.Optional[str] = None, - type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin - visibility: typing.Optional[list[str]] = None, - default: typing.Any = _UNSET, - format: typing.Optional[str] = None, - is_multipart_file_input: bool = False, - xml: typing.Optional[dict[str, typing.Any]] = None, - original_tsp_name: typing.Optional[str] = None, -) -> typing.Any: - return _RestField( - name=name, - type=type, - visibility=visibility, - default=default, - format=format, - is_multipart_file_input=is_multipart_file_input, - xml=xml, - original_tsp_name=original_tsp_name, - ) - - -def rest_discriminator( - *, - name: typing.Optional[str] = None, - type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin - visibility: typing.Optional[list[str]] = None, - xml: typing.Optional[dict[str, typing.Any]] = None, -) -> typing.Any: - return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) - - -def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: - """Serialize a model to XML. - - :param Model model: The model to serialize. - :param bool exclude_readonly: Whether to exclude readonly properties. - :returns: The XML representation of the model. - :rtype: str - """ - return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore - - -def _get_xml_ns(meta: dict[str, typing.Any]) -> typing.Optional[str]: - """Return the XML namespace from a metadata dict, checking both 'ns' (old-style) and 'namespace' (DPG) keys. - - :param dict meta: The metadata dictionary to extract namespace from. - :returns: The namespace string if 'ns' or 'namespace' key is present, None otherwise. - :rtype: str or None - """ - ns = meta.get("ns") - if ns is None: - ns = meta.get("namespace") - return ns - - -def _resolve_xml_ns( - prop_meta: dict[str, typing.Any], model_meta: typing.Optional[dict[str, typing.Any]] = None -) -> typing.Optional[str]: - """Resolve XML namespace for a property, falling back to model namespace when appropriate. - - Checks the property metadata first; if no namespace is found and the model does not declare - an explicit prefix, falls back to the model-level namespace. - - :param dict prop_meta: The property metadata dictionary. - :param dict model_meta: The model metadata dictionary, used as fallback. - :returns: The resolved namespace string, or None. - :rtype: str or None - """ - ns = _get_xml_ns(prop_meta) - if ns is None and model_meta is not None and not model_meta.get("prefix"): - ns = _get_xml_ns(model_meta) - return ns - - -def _set_xml_attribute(element: ET.Element, name: str, value: typing.Any, prop_meta: dict[str, typing.Any]) -> None: - """Set an XML attribute on an element, handling namespace prefix registration. - - :param ET.Element element: The element to set the attribute on. - :param str name: The default attribute name (wire name). - :param any value: The attribute value. - :param dict prop_meta: The property metadata dictionary. - """ - xml_name = prop_meta.get("name", name) - _attr_ns = _get_xml_ns(prop_meta) - if _attr_ns: - _attr_prefix = prop_meta.get("prefix") - if _attr_prefix: - _safe_register_namespace(_attr_prefix, _attr_ns) - xml_name = "{" + _attr_ns + "}" + xml_name - element.set(xml_name, _get_primitive_type_value(value)) - - -def _get_element( - o: typing.Any, - exclude_readonly: bool = False, - parent_meta: typing.Optional[dict[str, typing.Any]] = None, - wrapped_element: typing.Optional[ET.Element] = None, -) -> typing.Union[ET.Element, list[ET.Element]]: - if _is_model(o): - model_meta = getattr(o, "_xml", {}) - - # if prop is a model, then use the prop element directly, else generate a wrapper of model - if wrapped_element is None: - # When serializing as an array item (parent_meta is set), check if the parent has an - # explicit itemsName. This ensures correct element names for unwrapped arrays (where - # the element tag is the property/items name, not the model type name). - _items_name = parent_meta.get("itemsName") if parent_meta is not None else None - element_name = _items_name if _items_name else (model_meta.get("name") or o.__class__.__name__) - _model_ns = _get_xml_ns(model_meta) - wrapped_element = _create_xml_element( - element_name, - model_meta.get("prefix"), - _model_ns, - ) - - readonly_props = [] - if exclude_readonly: - readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] - - for k, v in o.items(): - # do not serialize readonly properties - if exclude_readonly and k in readonly_props: - continue - - prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) - if prop_rest_field: - prop_meta = getattr(prop_rest_field, "_xml").copy() - # use the wire name as xml name if no specific name is set - if prop_meta.get("name") is None: - prop_meta["name"] = k - else: - # additional properties will not have rest field, use the wire name as xml name - prop_meta = {"name": k} - - # Propagate model namespace to properties only for old-style "ns"-keyed models. - # DPG-generated models use the "namespace" key and explicitly declare namespace on - # each property that needs it, so propagation is intentionally skipped for them. - if prop_meta.get("ns") is None and model_meta.get("ns"): - prop_meta["ns"] = model_meta.get("ns") - prop_meta["prefix"] = model_meta.get("prefix") - - if prop_meta.get("unwrapped", False): - # unwrapped could only set on array - wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) - elif prop_meta.get("text", False): - # text could only set on primitive type - wrapped_element.text = _get_primitive_type_value(v) - elif prop_meta.get("attribute", False): - _set_xml_attribute(wrapped_element, k, v, prop_meta) - else: - # other wrapped prop element - wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) - return wrapped_element - if isinstance(o, list): - return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore - if isinstance(o, dict): - result = [] - _dict_ns = _get_xml_ns(parent_meta) if parent_meta else None - for k, v in o.items(): - result.append( - _get_wrapped_element( - v, - exclude_readonly, - { - "name": k, - "ns": _dict_ns, - "prefix": parent_meta.get("prefix") if parent_meta else None, - }, - ) - ) - return result - - # primitive case need to create element based on parent_meta - if parent_meta: - _items_ns = parent_meta.get("itemsNs") - if _items_ns is None: - _items_ns = _get_xml_ns(parent_meta) - return _get_wrapped_element( - o, - exclude_readonly, - { - "name": parent_meta.get("itemsName", parent_meta.get("name")), - "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), - "ns": _items_ns, - }, - ) - - raise ValueError("Could not serialize value into xml: " + o) - - -def _get_wrapped_element( - v: typing.Any, - exclude_readonly: bool, - meta: typing.Optional[dict[str, typing.Any]], -) -> ET.Element: - _meta_ns = _get_xml_ns(meta) if meta else None - wrapped_element = _create_xml_element( - meta.get("name") if meta else None, meta.get("prefix") if meta else None, _meta_ns - ) - if isinstance(v, (dict, list)): - wrapped_element.extend(_get_element(v, exclude_readonly, meta)) - elif _is_model(v): - _get_element(v, exclude_readonly, meta, wrapped_element) - else: - wrapped_element.text = _get_primitive_type_value(v) - return wrapped_element # type: ignore[no-any-return] - - -def _get_primitive_type_value(v) -> str: - if v is True: - return "true" - if v is False: - return "false" - if isinstance(v, _Null): - return "" - return str(v) - - -def _safe_register_namespace(prefix: str, ns: str) -> None: - """Register an XML namespace prefix, handling reserved prefix patterns. - - Some prefixes (e.g. 'ns2') match Python's reserved 'ns\\d+' pattern used for - auto-generated prefixes, causing register_namespace to raise ValueError. - Falls back to directly registering in the internal namespace map. - - :param str prefix: The namespace prefix to register. - :param str ns: The namespace URI. - """ - try: - ET.register_namespace(prefix, ns) - except ValueError: - _ns_map = getattr(ET, "_namespace_map", None) - if _ns_map is not None: - _ns_map[ns] = prefix - - -def _create_xml_element( - tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None -) -> ET.Element: - if prefix and ns: - _safe_register_namespace(prefix, ns) - if ns: - return ET.Element("{" + ns + "}" + tag) - return ET.Element(tag) - - -def _deserialize_xml( - deserializer: typing.Any, - value: str, -) -> typing.Any: - element = ET.fromstring(value) # nosec - return _deserialize(deserializer, element) - - -def _convert_element(e: ET.Element): - # dict case - if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: - dict_result: dict[str, typing.Any] = {} - for child in e: - if dict_result.get(child.tag) is not None: - if isinstance(dict_result[child.tag], list): - dict_result[child.tag].append(_convert_element(child)) - else: - dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] - else: - dict_result[child.tag] = _convert_element(child) - dict_result.update(e.attrib) - return dict_result - # array case - if len(e) > 0: - array_result: list[typing.Any] = [] - for child in e: - array_result.append(_convert_element(child)) - return array_result - # primitive case - return e.text diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/_utils/serialization.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/_utils/serialization.py deleted file mode 100644 index 81ec1de5922b..000000000000 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/_utils/serialization.py +++ /dev/null @@ -1,2041 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -# pyright: reportUnnecessaryTypeIgnoreComment=false - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs -from typing import ( - Any, - cast, - Optional, - Union, - AnyStr, - IO, - Mapping, - Callable, - MutableMapping, -) - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote -import xml.etree.ElementTree as ET - -import isodate # type: ignore -from typing_extensions import Self - -from azure.core.exceptions import DeserializationError, SerializationError -from azure.core.serialization import NULL as CoreNull - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -JSON = MutableMapping[str, Any] - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - :return: The deserialized data. - :rtype: object - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) from err - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) # nosec - except ET.ParseError as err: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise DeserializationError("XML is invalid") from err - elif content_type.startswith("text/"): - return data_as_str - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - - :param bytes body_bytes: The body of the response. - :param dict headers: The headers of the response. - :returns: The deserialized data. - :rtype: object - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - -TZ_UTC = datetime.timezone.utc - -_FLATTEN = re.compile(r"(? None: - self.additional_properties: Optional[dict[str, Any]] = {} - for k in kwargs: # pylint: disable=consider-using-dict-items - if k not in self._attribute_map: - _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) - elif k in self._validation and self._validation[k].get("readonly", False): - _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) - else: - setattr(self, k, kwargs[k]) - - def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are equal - :rtype: bool - """ - if isinstance(other, self.__class__): - return self.__dict__ == other.__dict__ - return False - - def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes. - - :param object other: The object to compare - :returns: True if objects are not equal - :rtype: bool - """ - return not self.__eq__(other) - - def __str__(self) -> str: - return str(self.__dict__) - - @classmethod - def enable_additional_properties_sending(cls) -> None: - cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} - - @classmethod - def is_xml_model(cls) -> bool: - try: - cls._xml_map # type: ignore - except AttributeError: - return False - return True - - @classmethod - def _create_xml_node(cls): - """Create XML node. - - :returns: The XML node - :rtype: xml.etree.ElementTree.Element - """ - try: - xml_map = cls._xml_map # type: ignore - except AttributeError: - xml_map = {} - - return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - - def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to server from this model. - - This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, keep_readonly=keep_readonly, **kwargs - ) - - def as_dict( - self, - keep_readonly: bool = True, - key_transformer: Callable[[str, dict[str, Any], Any], Any] = attribute_transformer, - **kwargs: Any - ) -> JSON: - """Return a dict that can be serialized using json.dump. - - Advanced usage might optionally use a callback as parameter: - - .. code::python - - def my_key_transformer(key, attr_desc, value): - return key - - Key is the attribute name used in Python. Attr_desc - is a dict of metadata. Currently contains 'type' with the - msrest type and 'key' with the RestAPI encoded key. - Value is the current value in this object. - - The string returned will be used to serialize the key. - If the return type is a list, this is considered hierarchical - result dict. - - See the three examples in this file: - - - attribute_transformer - - full_restapi_key_transformer - - last_restapi_key_transformer - - If you want XML serialization, you can pass the kwargs is_xml=True. - - :param bool keep_readonly: If you want to serialize the readonly attributes - :param function key_transformer: A key transformer function. - :returns: A dict JSON compatible object - :rtype: dict - """ - serializer = Serializer(self._infer_class_models()) - return serializer._serialize( # type: ignore # pylint: disable=protected-access - self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs - ) - - @classmethod - def _infer_class_models(cls): - try: - str_models = cls.__module__.rsplit(".", 1)[0] - models = sys.modules[str_models] - client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} - if cls.__name__ not in client_models: - raise ValueError("Not Autorest generated code") - except Exception: # pylint: disable=broad-exception-caught - # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. - client_models = {cls.__name__: cls} - return client_models - - @classmethod - def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: - """Parse a str using the RestAPI syntax and return a model. - - :param str data: A str using RestAPI structure. JSON by default. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def from_dict( - cls, - data: Any, - key_extractors: Optional[Callable[[str, dict[str, Any], Any], Any]] = None, - content_type: Optional[str] = None, - ) -> Self: - """Parse a dict using given key extractor return a model. - - By default consider key - extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor - and last_rest_key_case_insensitive_extractor) - - :param dict data: A dict using RestAPI structure - :param function key_extractors: A key extractor function. - :param str content_type: JSON by default, set application/xml if XML. - :returns: An instance of this model - :raises DeserializationError: if something went wrong - :rtype: Self - """ - deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( # type: ignore - [ # type: ignore - attribute_key_case_insensitive_extractor, - rest_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - if key_extractors is None - else key_extractors - ) - return deserializer(cls.__name__, data, content_type=content_type) # type: ignore - - @classmethod - def _flatten_subtype(cls, key, objects): - if "_subtype_map" not in cls.__dict__: - return {} - result = dict(cls._subtype_map[key]) - for valuetype in cls._subtype_map[key].values(): - result |= objects[valuetype]._flatten_subtype(key, objects) # pylint: disable=protected-access - return result - - @classmethod - def _classify(cls, response, objects): - """Check the class _subtype_map for any child classes. - We want to ignore any inherited _subtype_maps. - - :param dict response: The initial data - :param dict objects: The class objects - :returns: The class to be used - :rtype: class - """ - for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): - subtype_value = None - - if not isinstance(response, ET.Element): - rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) - else: - subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) - if subtype_value: - # Try to match base class. Can be class name only - # (bug to fix in Autorest to support x-ms-discriminator-name) - if cls.__name__ == subtype_value: - return cls - flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) - try: - return objects[flatten_mapping_type[subtype_value]] # type: ignore - except KeyError: - _LOGGER.warning( - "Subtype value %s has no mapping, use base class %s.", - subtype_value, - cls.__name__, - ) - break - else: - _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) - break - return cls - - @classmethod - def _get_rest_key_parts(cls, attr_key): - """Get the RestAPI key of this attr, split it and decode part - :param str attr_key: Attribute key must be in attribute_map. - :returns: A list of RestAPI part - :rtype: list - """ - rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) - return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] - - -def _decode_attribute_map_key(key): - """This decode a key in an _attribute_map to the actual key we want to look at - inside the received data. - - :param str key: A key string from the generated code - :returns: The decoded key - :rtype: str - """ - return key.replace("\\.", ".") - - -class Serializer: # pylint: disable=too-many-public-methods - """Request object model serializer.""" - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} - days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} - months = { - 1: "Jan", - 2: "Feb", - 3: "Mar", - 4: "Apr", - 5: "May", - 6: "Jun", - 7: "Jul", - 8: "Aug", - 9: "Sep", - 10: "Oct", - 11: "Nov", - 12: "Dec", - } - validation = { - "min_length": lambda x, y: len(x) < y, - "max_length": lambda x, y: len(x) > y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals - self, target_obj, data_type=None, **kwargs - ): - """Serialize data into a string according to type. - - :param object target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises SerializationError: if serialization fails. - :returns: The serialized data. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() # pylint: disable=protected-access - try: - attributes = target_obj._attribute_map # pylint: disable=protected-access - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access - attr_name, {} - ).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized |= target_obj.additional_properties - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) # type: ignore - continue - if xml_desc.get("text", False): - serialized.text = new_attr # type: ignore - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) # type: ignore - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, - # we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) # type: ignore - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = str(new_attr) - serialized.append(local_node) # type: ignore - else: # JSON - for k in reversed(keys): # type: ignore - new_attr = {k: new_attr} - - _new_attr = new_attr - _serialized = serialized - for k in keys: # type: ignore - if k not in _serialized: - _serialized.update(_new_attr) # type: ignore - _new_attr = _new_attr[k] # type: ignore - _serialized = _serialized[k] - except ValueError as err: - if isinstance(err, SerializationError): - raise - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise SerializationError(msg) from err - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises SerializationError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized request body - """ - - # Just in case this is a dict - internal_data_type_str = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type_str, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ # type: ignore - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access - except DeserializationError as err: - raise SerializationError("Unable to build a model: " + str(err)) from err - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param str name: The name of the URL path parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :returns: The serialized URL path - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - output = output.replace("{", quote("{")).replace("}", quote("}")) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param str name: The name of the query parameter. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, list - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized query parameter - """ - try: - # Treat the list aside, since we don't want to encode the div separator - if data_type.startswith("["): - internal_data_type = data_type[1:-1] - do_quote = not kwargs.get("skip_quote", False) - return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param str name: The name of the header. - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises TypeError: if serialization fails. - :raises ValueError: if data is None - :returns: The serialized header - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError as exc: - raise TypeError("{} must be type {}.".format(name, data_type)) from exc - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param object data: The data to be serialized. - :param str data_type: The type to be serialized from. - :raises AttributeError: if required data is None. - :raises ValueError: if data is None - :raises SerializationError: if serialization fails. - :returns: The serialized data. - :rtype: str, int, float, bool, dict, list - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data is CoreNull: - return None - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - if data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, cast(type, data.__class__)) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise SerializationError(msg.format(data, data_type)) from err - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param obj data: Object to be serialized. - :param str data_type: Type of object in the iterable. - :rtype: str, int, float, bool - :return: serialized object - :raises TypeError: raise if data_type is not one of str, int, float, bool. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - if data_type == "int": - return int(data) - if data_type == "float": - return float(data) - if data_type == "bool": - return bool(data) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param str data: Object to be serialized. - :rtype: str - :return: serialized object - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): # type: ignore - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list data: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - Defaults to False. - :rtype: list, str - :return: serialized iterable - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized.append(None) - - if kwargs.get("do_quote", False): - serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :rtype: dict - :return: serialized dictionary - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError as err: - if isinstance(err, SerializationError): - raise - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - :return: serialized object - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - if obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) # type: ignore - return result - except ValueError as exc: - for enum_value in enum_obj: # type: ignore - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) from exc - - @staticmethod - def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument - """Serialize bytearray into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument - """Serialize str into base-64 string. - - :param str attr: Object to be serialized. - :rtype: str - :return: serialized base64 - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Decimal object to float. - - :param decimal attr: Object to be serialized. - :rtype: float - :return: serialized decimal - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): # pylint: disable=unused-argument - """Serialize long (Py2) or int (Py3). - - :param int attr: Object to be serialized. - :rtype: int/long - :return: serialized long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - :return: serialized date - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - :return: serialized time - """ - if isinstance(attr, str): - attr = isodate.parse_time(attr) - t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) - if attr.microsecond: - t += ".{:02}".format(attr.microsecond) - return t - - @staticmethod - def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - :return: serialized duration - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises TypeError: if format invalid. - :return: serialized rfc - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError as exc: - raise TypeError("RFC1123 object must be valid Datetime object.") from exc - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises SerializationError: if format invalid. - :return: serialized iso - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - if utc.tm_year > 9999 or utc.tm_year < 1: - raise OverflowError("Hit max or min date") - - microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") - if microseconds: - microseconds = "." + microseconds - date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( - utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec - ) - return date + microseconds + "Z" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise SerializationError(msg) from err - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise TypeError(msg) from err - - @staticmethod - def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises SerializationError: if format invalid - :return: serialied unix - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError as exc: - raise TypeError("Unix time object must be valid Datetime object.") from exc - - -def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - key = attr_desc["key"] - working_data = data - - while "." in key: - # Need the cast, as for some reasons "split" is typed as list[str | Any] - dict_keys = cast(list[str], _FLATTEN.split(key)) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements - attr, attr_desc, data -): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - :param str attr: The attribute to extract - :param dict attr_desc: The attribute description - :param dict data: The data to extract from - :rtype: object - :returns: The extracted attribute - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{{{}}}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer: - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - - def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies: dict[str, type] = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, str): - return self.deserialize_data(data, response) - if isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None or data is CoreNull: - return data - try: - attributes = response._attribute_map # type: ignore # pylint: disable=protected-access - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name # type: ignore - raise DeserializationError(msg) from err - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :return: The classified target object and its class name. - :rtype: tuple - """ - if target is None: - return None, None - - if isinstance(target, str): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ # type: ignore - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deserialize. - :param str content_type: Swagger "produces" if available. - :return: Deserialized object. - :rtype: object - """ - try: - return self(target_obj, data, content_type=content_type) - except: # pylint: disable=bare-except - _LOGGER.debug( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param obj raw_data: Data to be processed. - :param str content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - :rtype: object - :return: Unpacked content. - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param Response response: The response model class. - :param dict attrs: The deserialized response attributes. - :param dict additional_properties: Additional properties to be set. - :rtype: Response - :return: The instantiated response model. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("readonly") - ] - const = [ - k - for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore - if v.get("constant") - ] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties # type: ignore - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) from err - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) from exp - - def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises DeserializationError: if deserialization fails. - :return: Deserialized object. - :rtype: object - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment - "object", - "[]", - r"{}", - ] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise DeserializationError(msg) from err - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :return: Deserialized iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :return: Deserialized dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :return: Deserialized object. - :rtype: dict - :raises TypeError: if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, str): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :return: Deserialized basic type. - :rtype: str, int, float or bool - :raises TypeError: if string format is not valid or data_type is not one of str, int, float, bool. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - if isinstance(attr, str): - if attr.lower() in ["true", "1"]: - return True - if attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - if data_type == "int": - return int(attr) - if data_type == "float": - return float(attr) - raise TypeError("Unknown basic data type: {}".format(data_type)) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :return: Deserialized string. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): # type: ignore - return data - except NameError: - return str(data) - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :return: Deserialized enum object. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - try: - return list(enum_obj.__members__.values())[data] - except IndexError as exc: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) from exc - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :return: Deserialized bytearray - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) # type: ignore - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :return: Deserialized base64 string - :rtype: bytearray - :raises TypeError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore - attr = attr + padding # type: ignore - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :return: Deserialized decimal - :raises DeserializationError: if string format invalid. - :rtype: decimal - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(str(attr)) # type: ignore - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise DeserializationError(msg) from err - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :return: Deserialized int - :rtype: long or int - :raises ValueError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) # type: ignore - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :return: Deserialized duration - :rtype: TimeDelta - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise DeserializationError(msg) from err - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :return: Deserialized date - :rtype: Date - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=0, defaultday=0) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :return: Deserialized time - :rtype: datetime.time - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized RFC datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - parsed_date = email.utils.parsedate_tz(attr) # type: ignore - date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :return: Deserialized ISO datetime - :rtype: Datetime - :raises DeserializationError: if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() # type: ignore - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise DeserializationError(msg) from err - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :return: Deserialized datetime - :rtype: Datetime - :raises DeserializationError: if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) # type: ignore - try: - attr = int(attr) - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise DeserializationError(msg) from err - return date_obj diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/models/__init__.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/models/__init__.py deleted file mode 100644 index 49bdcf3683e2..000000000000 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/models/__init__.py +++ /dev/null @@ -1,858 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=wrong-import-position - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from ._patch import * # pylint: disable=unused-wildcard-import - - -from ._models import ( # type: ignore - A2APreviewTool, - A2AToolCall, - A2AToolCallOutput, - AISearchIndexResource, - AgentReference, - Annotation, - ApiErrorResponse, - ApplyPatchCreateFileOperation, - ApplyPatchCreateFileOperationParam, - ApplyPatchDeleteFileOperation, - ApplyPatchDeleteFileOperationParam, - ApplyPatchFileOperation, - ApplyPatchOperationParam, - ApplyPatchToolCallItemParam, - ApplyPatchToolCallOutputItemParam, - ApplyPatchToolParam, - ApplyPatchUpdateFileOperation, - ApplyPatchUpdateFileOperationParam, - ApproximateLocation, - AutoCodeInterpreterToolParam, - AzureAISearchTool, - AzureAISearchToolCall, - AzureAISearchToolCallOutput, - AzureAISearchToolResource, - AzureFunctionBinding, - AzureFunctionDefinition, - AzureFunctionDefinitionFunction, - AzureFunctionStorageQueue, - AzureFunctionTool, - AzureFunctionToolCall, - AzureFunctionToolCallOutput, - BingCustomSearchConfiguration, - BingCustomSearchPreviewTool, - BingCustomSearchToolCall, - BingCustomSearchToolCallOutput, - BingCustomSearchToolParameters, - BingGroundingSearchConfiguration, - BingGroundingSearchToolParameters, - BingGroundingTool, - BingGroundingToolCall, - BingGroundingToolCallOutput, - BrowserAutomationPreviewTool, - BrowserAutomationToolCall, - BrowserAutomationToolCallOutput, - BrowserAutomationToolConnectionParameters, - BrowserAutomationToolParameters, - CaptureStructuredOutputsTool, - ChatSummaryMemoryItem, - ClickParam, - CodeInterpreterOutputImage, - CodeInterpreterOutputLogs, - CodeInterpreterTool, - CompactResource, - CompactionSummaryItemParam, - ComparisonFilter, - CompoundFilter, - ComputerAction, - ComputerCallOutputItemParam, - ComputerCallSafetyCheckParam, - ComputerScreenshotContent, - ComputerScreenshotImage, - ComputerUsePreviewTool, - ContainerAutoParam, - ContainerFileCitationBody, - ContainerNetworkPolicyAllowlistParam, - ContainerNetworkPolicyDisabledParam, - ContainerNetworkPolicyDomainSecretParam, - ContainerNetworkPolicyParam, - ContainerReferenceResource, - ContainerSkill, - ContextManagementParam, - ConversationParam_2, - ConversationReference, - CoordParam, - CreateResponse, - CustomGrammarFormatParam, - CustomTextFormatParam, - CustomToolParam, - CustomToolParamFormat, - DeleteResponseResult, - DoubleClickAction, - DragParam, - Error, - FabricDataAgentToolCall, - FabricDataAgentToolCallOutput, - FabricDataAgentToolParameters, - FileCitationBody, - FilePath, - FileSearchTool, - FileSearchToolCallResults, - FunctionAndCustomToolCallOutput, - FunctionAndCustomToolCallOutputInputFileContent, - FunctionAndCustomToolCallOutputInputImageContent, - FunctionAndCustomToolCallOutputInputTextContent, - FunctionCallOutputItemParam, - FunctionShellAction, - FunctionShellActionParam, - FunctionShellCallEnvironment, - FunctionShellCallItemParam, - FunctionShellCallItemParamEnvironment, - FunctionShellCallItemParamEnvironmentContainerReferenceParam, - FunctionShellCallItemParamEnvironmentLocalEnvironmentParam, - FunctionShellCallOutputContent, - FunctionShellCallOutputContentParam, - FunctionShellCallOutputExitOutcome, - FunctionShellCallOutputExitOutcomeParam, - FunctionShellCallOutputItemParam, - FunctionShellCallOutputOutcome, - FunctionShellCallOutputOutcomeParam, - FunctionShellCallOutputTimeoutOutcome, - FunctionShellCallOutputTimeoutOutcomeParam, - FunctionShellToolParam, - FunctionShellToolParamEnvironment, - FunctionShellToolParamEnvironmentContainerReferenceParam, - FunctionShellToolParamEnvironmentLocalEnvironmentParam, - FunctionTool, - FunctionToolCallOutput, - FunctionToolCallOutputResource, - HybridSearchOptions, - ImageGenTool, - ImageGenToolInputImageMask, - InlineSkillParam, - InlineSkillSourceParam, - InputFileContent, - InputFileContentParam, - InputImageContent, - InputImageContentParamAutoParam, - InputTextContent, - InputTextContentParam, - Item, - ItemCodeInterpreterToolCall, - ItemComputerToolCall, - ItemCustomToolCall, - ItemCustomToolCallOutput, - ItemField, - ItemFieldApplyPatchToolCall, - ItemFieldApplyPatchToolCallOutput, - ItemFieldCodeInterpreterToolCall, - ItemFieldCompactionBody, - ItemFieldComputerToolCall, - ItemFieldComputerToolCallOutputResource, - ItemFieldCustomToolCall, - ItemFieldCustomToolCallOutput, - ItemFieldFileSearchToolCall, - ItemFieldFunctionShellCall, - ItemFieldFunctionShellCallOutput, - ItemFieldFunctionToolCall, - ItemFieldImageGenToolCall, - ItemFieldLocalShellToolCall, - ItemFieldLocalShellToolCallOutput, - ItemFieldMcpApprovalRequest, - ItemFieldMcpApprovalResponseResource, - ItemFieldMcpListTools, - ItemFieldMcpToolCall, - ItemFieldMessage, - ItemFieldReasoningItem, - ItemFieldWebSearchToolCall, - ItemFileSearchToolCall, - ItemFunctionToolCall, - ItemImageGenToolCall, - ItemLocalShellToolCall, - ItemLocalShellToolCallOutput, - ItemMcpApprovalRequest, - ItemMcpListTools, - ItemMcpToolCall, - ItemMessage, - ItemOutputMessage, - ItemReasoningItem, - ItemReferenceParam, - ItemWebSearchToolCall, - KeyPressAction, - LocalEnvironmentResource, - LocalShellExecAction, - LocalShellToolParam, - LocalSkillParam, - LogProb, - MCPApprovalResponse, - MCPListToolsTool, - MCPListToolsToolAnnotations, - MCPListToolsToolInputSchema, - MCPTool, - MCPToolFilter, - MCPToolRequireApproval, - MemoryItem, - MemorySearchItem, - MemorySearchOptions, - MemorySearchPreviewTool, - MemorySearchToolCallItemParam, - MemorySearchToolCallItemResource, - MessageContent, - MessageContentInputFileContent, - MessageContentInputImageContent, - MessageContentInputTextContent, - MessageContentOutputTextContent, - MessageContentReasoningTextContent, - MessageContentRefusalContent, - Metadata, - MicrosoftFabricPreviewTool, - MoveParam, - OAuthConsentRequestOutputItem, - OpenApiAnonymousAuthDetails, - OpenApiAuthDetails, - OpenApiFunctionDefinition, - OpenApiFunctionDefinitionFunction, - OpenApiManagedAuthDetails, - OpenApiManagedSecurityScheme, - OpenApiProjectConnectionAuthDetails, - OpenApiProjectConnectionSecurityScheme, - OpenApiTool, - OpenApiToolCall, - OpenApiToolCallOutput, - OutputContent, - OutputContentOutputTextContent, - OutputContentReasoningTextContent, - OutputContentRefusalContent, - OutputItem, - OutputItemApplyPatchToolCall, - OutputItemApplyPatchToolCallOutput, - OutputItemCodeInterpreterToolCall, - OutputItemCompactionBody, - OutputItemComputerToolCall, - OutputItemComputerToolCallOutputResource, - OutputItemCustomToolCall, - OutputItemCustomToolCallOutput, - OutputItemFileSearchToolCall, - OutputItemFunctionShellCall, - OutputItemFunctionShellCallOutput, - OutputItemFunctionToolCall, - OutputItemImageGenToolCall, - OutputItemLocalShellToolCall, - OutputItemLocalShellToolCallOutput, - OutputItemMcpApprovalRequest, - OutputItemMcpApprovalResponseResource, - OutputItemMcpListTools, - OutputItemMcpToolCall, - OutputItemMessage, - OutputItemOutputMessage, - OutputItemReasoningItem, - OutputItemWebSearchToolCall, - OutputMessageContent, - OutputMessageContentOutputTextContent, - OutputMessageContentRefusalContent, - Prompt, - RankingOptions, - Reasoning, - ReasoningTextContent, - ResponseAudioDeltaEvent, - ResponseAudioDoneEvent, - ResponseAudioTranscriptDeltaEvent, - ResponseAudioTranscriptDoneEvent, - ResponseCodeInterpreterCallCodeDeltaEvent, - ResponseCodeInterpreterCallCodeDoneEvent, - ResponseCodeInterpreterCallCompletedEvent, - ResponseCodeInterpreterCallInProgressEvent, - ResponseCodeInterpreterCallInterpretingEvent, - ResponseCompletedEvent, - ResponseContentPartAddedEvent, - ResponseContentPartDoneEvent, - ResponseCreatedEvent, - ResponseCustomToolCallInputDeltaEvent, - ResponseCustomToolCallInputDoneEvent, - ResponseErrorEvent, - ResponseErrorInfo, - ResponseFailedEvent, - ResponseFileSearchCallCompletedEvent, - ResponseFileSearchCallInProgressEvent, - ResponseFileSearchCallSearchingEvent, - ResponseFormatJsonSchemaSchema, - ResponseFunctionCallArgumentsDeltaEvent, - ResponseFunctionCallArgumentsDoneEvent, - ResponseImageGenCallCompletedEvent, - ResponseImageGenCallGeneratingEvent, - ResponseImageGenCallInProgressEvent, - ResponseImageGenCallPartialImageEvent, - ResponseInProgressEvent, - ResponseIncompleteDetails, - ResponseIncompleteEvent, - ResponseLogProb, - ResponseLogProbTopLogprobs, - ResponseMCPCallArgumentsDeltaEvent, - ResponseMCPCallArgumentsDoneEvent, - ResponseMCPCallCompletedEvent, - ResponseMCPCallFailedEvent, - ResponseMCPCallInProgressEvent, - ResponseMCPListToolsCompletedEvent, - ResponseMCPListToolsFailedEvent, - ResponseMCPListToolsInProgressEvent, - ResponseObject, - ResponseOutputItemAddedEvent, - ResponseOutputItemDoneEvent, - ResponseOutputTextAnnotationAddedEvent, - ResponsePromptVariables, - ResponseQueuedEvent, - ResponseReasoningSummaryPartAddedEvent, - ResponseReasoningSummaryPartAddedEventPart, - ResponseReasoningSummaryPartDoneEvent, - ResponseReasoningSummaryPartDoneEventPart, - ResponseReasoningSummaryTextDeltaEvent, - ResponseReasoningSummaryTextDoneEvent, - ResponseReasoningTextDeltaEvent, - ResponseReasoningTextDoneEvent, - ResponseRefusalDeltaEvent, - ResponseRefusalDoneEvent, - ResponseStreamEvent, - ResponseStreamOptions, - ResponseTextDeltaEvent, - ResponseTextDoneEvent, - ResponseTextParam, - ResponseUsage, - ResponseUsageInputTokensDetails, - ResponseUsageOutputTokensDetails, - ResponseWebSearchCallCompletedEvent, - ResponseWebSearchCallInProgressEvent, - ResponseWebSearchCallSearchingEvent, - ScreenshotParam, - ScrollParam, - SharepointGroundingToolCall, - SharepointGroundingToolCallOutput, - SharepointGroundingToolParameters, - SharepointPreviewTool, - SkillReferenceParam, - SpecificApplyPatchParam, - SpecificFunctionShellParam, - StructuredOutputDefinition, - StructuredOutputsOutputItem, - SummaryTextContent, - TextContent, - TextResponseFormatConfiguration, - TextResponseFormatConfigurationResponseFormatJsonObject, - TextResponseFormatConfigurationResponseFormatText, - TextResponseFormatJsonSchema, - Tool, - ToolChoiceAllowed, - ToolChoiceCodeInterpreter, - ToolChoiceComputerUsePreview, - ToolChoiceCustom, - ToolChoiceFileSearch, - ToolChoiceFunction, - ToolChoiceImageGeneration, - ToolChoiceMCP, - ToolChoiceParam, - ToolChoiceWebSearchPreview, - ToolChoiceWebSearchPreview20250311, - ToolProjectConnection, - TopLogProb, - TypeParam, - UrlCitationBody, - UserProfileMemoryItem, - VectorStoreFileAttributes, - WaitParam, - WebSearchActionFind, - WebSearchActionOpenPage, - WebSearchActionSearch, - WebSearchActionSearchSources, - WebSearchApproximateLocation, - WebSearchConfiguration, - WebSearchPreviewTool, - WebSearchTool, - WebSearchToolFilters, - WorkIQPreviewTool, - WorkIQPreviewToolParameters, - WorkflowActionOutputItem, -) - -from ._enums import ( # type: ignore - AnnotationType, - ApplyPatchCallOutputStatus, - ApplyPatchCallOutputStatusParam, - ApplyPatchCallStatus, - ApplyPatchCallStatusParam, - ApplyPatchFileOperationType, - ApplyPatchOperationParamType, - AzureAISearchQueryType, - ClickButtonType, - ComputerActionType, - ComputerEnvironment, - ContainerMemoryLimit, - ContainerNetworkPolicyParamType, - ContainerSkillType, - CustomToolParamFormatType, - DetailEnum, - FunctionAndCustomToolCallOutputType, - FunctionCallItemStatus, - FunctionShellCallEnvironmentType, - FunctionShellCallItemParamEnvironmentType, - FunctionShellCallItemStatus, - FunctionShellCallOutputOutcomeParamType, - FunctionShellCallOutputOutcomeType, - FunctionShellToolParamEnvironmentType, - GrammarSyntax1, - ImageDetail, - ImageGenActionEnum, - IncludeEnum, - InputFidelity, - ItemFieldType, - ItemType, - LocalShellCallOutputStatusEnum, - LocalShellCallStatus, - MCPToolCallStatus, - MemoryItemKind, - MessageContentType, - MessageRole, - MessageStatus, - ModelIdsCompaction, - OpenApiAuthType, - OutputContentType, - OutputItemType, - OutputMessageContentType, - PageOrder, - RankerVersionType, - ResponseErrorCode, - ResponseStreamEventType, - SearchContextSize, - TextResponseFormatConfigurationType, - ToolCallStatus, - ToolChoiceOptions, - ToolChoiceParamType, - ToolType, -) -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "A2APreviewTool", - "A2AToolCall", - "A2AToolCallOutput", - "AISearchIndexResource", - "AgentReference", - "Annotation", - "ApiErrorResponse", - "ApplyPatchCreateFileOperation", - "ApplyPatchCreateFileOperationParam", - "ApplyPatchDeleteFileOperation", - "ApplyPatchDeleteFileOperationParam", - "ApplyPatchFileOperation", - "ApplyPatchOperationParam", - "ApplyPatchToolCallItemParam", - "ApplyPatchToolCallOutputItemParam", - "ApplyPatchToolParam", - "ApplyPatchUpdateFileOperation", - "ApplyPatchUpdateFileOperationParam", - "ApproximateLocation", - "AutoCodeInterpreterToolParam", - "AzureAISearchTool", - "AzureAISearchToolCall", - "AzureAISearchToolCallOutput", - "AzureAISearchToolResource", - "AzureFunctionBinding", - "AzureFunctionDefinition", - "AzureFunctionDefinitionFunction", - "AzureFunctionStorageQueue", - "AzureFunctionTool", - "AzureFunctionToolCall", - "AzureFunctionToolCallOutput", - "BingCustomSearchConfiguration", - "BingCustomSearchPreviewTool", - "BingCustomSearchToolCall", - "BingCustomSearchToolCallOutput", - "BingCustomSearchToolParameters", - "BingGroundingSearchConfiguration", - "BingGroundingSearchToolParameters", - "BingGroundingTool", - "BingGroundingToolCall", - "BingGroundingToolCallOutput", - "BrowserAutomationPreviewTool", - "BrowserAutomationToolCall", - "BrowserAutomationToolCallOutput", - "BrowserAutomationToolConnectionParameters", - "BrowserAutomationToolParameters", - "CaptureStructuredOutputsTool", - "ChatSummaryMemoryItem", - "ClickParam", - "CodeInterpreterOutputImage", - "CodeInterpreterOutputLogs", - "CodeInterpreterTool", - "CompactResource", - "CompactionSummaryItemParam", - "ComparisonFilter", - "CompoundFilter", - "ComputerAction", - "ComputerCallOutputItemParam", - "ComputerCallSafetyCheckParam", - "ComputerScreenshotContent", - "ComputerScreenshotImage", - "ComputerUsePreviewTool", - "ContainerAutoParam", - "ContainerFileCitationBody", - "ContainerNetworkPolicyAllowlistParam", - "ContainerNetworkPolicyDisabledParam", - "ContainerNetworkPolicyDomainSecretParam", - "ContainerNetworkPolicyParam", - "ContainerReferenceResource", - "ContainerSkill", - "ContextManagementParam", - "ConversationParam_2", - "ConversationReference", - "CoordParam", - "CreateResponse", - "CustomGrammarFormatParam", - "CustomTextFormatParam", - "CustomToolParam", - "CustomToolParamFormat", - "DeleteResponseResult", - "DoubleClickAction", - "DragParam", - "Error", - "FabricDataAgentToolCall", - "FabricDataAgentToolCallOutput", - "FabricDataAgentToolParameters", - "FileCitationBody", - "FilePath", - "FileSearchTool", - "FileSearchToolCallResults", - "FunctionAndCustomToolCallOutput", - "FunctionAndCustomToolCallOutputInputFileContent", - "FunctionAndCustomToolCallOutputInputImageContent", - "FunctionAndCustomToolCallOutputInputTextContent", - "FunctionCallOutputItemParam", - "FunctionShellAction", - "FunctionShellActionParam", - "FunctionShellCallEnvironment", - "FunctionShellCallItemParam", - "FunctionShellCallItemParamEnvironment", - "FunctionShellCallItemParamEnvironmentContainerReferenceParam", - "FunctionShellCallItemParamEnvironmentLocalEnvironmentParam", - "FunctionShellCallOutputContent", - "FunctionShellCallOutputContentParam", - "FunctionShellCallOutputExitOutcome", - "FunctionShellCallOutputExitOutcomeParam", - "FunctionShellCallOutputItemParam", - "FunctionShellCallOutputOutcome", - "FunctionShellCallOutputOutcomeParam", - "FunctionShellCallOutputTimeoutOutcome", - "FunctionShellCallOutputTimeoutOutcomeParam", - "FunctionShellToolParam", - "FunctionShellToolParamEnvironment", - "FunctionShellToolParamEnvironmentContainerReferenceParam", - "FunctionShellToolParamEnvironmentLocalEnvironmentParam", - "FunctionTool", - "FunctionToolCallOutput", - "FunctionToolCallOutputResource", - "HybridSearchOptions", - "ImageGenTool", - "ImageGenToolInputImageMask", - "InlineSkillParam", - "InlineSkillSourceParam", - "InputFileContent", - "InputFileContentParam", - "InputImageContent", - "InputImageContentParamAutoParam", - "InputTextContent", - "InputTextContentParam", - "Item", - "ItemCodeInterpreterToolCall", - "ItemComputerToolCall", - "ItemCustomToolCall", - "ItemCustomToolCallOutput", - "ItemField", - "ItemFieldApplyPatchToolCall", - "ItemFieldApplyPatchToolCallOutput", - "ItemFieldCodeInterpreterToolCall", - "ItemFieldCompactionBody", - "ItemFieldComputerToolCall", - "ItemFieldComputerToolCallOutputResource", - "ItemFieldCustomToolCall", - "ItemFieldCustomToolCallOutput", - "ItemFieldFileSearchToolCall", - "ItemFieldFunctionShellCall", - "ItemFieldFunctionShellCallOutput", - "ItemFieldFunctionToolCall", - "ItemFieldImageGenToolCall", - "ItemFieldLocalShellToolCall", - "ItemFieldLocalShellToolCallOutput", - "ItemFieldMcpApprovalRequest", - "ItemFieldMcpApprovalResponseResource", - "ItemFieldMcpListTools", - "ItemFieldMcpToolCall", - "ItemFieldMessage", - "ItemFieldReasoningItem", - "ItemFieldWebSearchToolCall", - "ItemFileSearchToolCall", - "ItemFunctionToolCall", - "ItemImageGenToolCall", - "ItemLocalShellToolCall", - "ItemLocalShellToolCallOutput", - "ItemMcpApprovalRequest", - "ItemMcpListTools", - "ItemMcpToolCall", - "ItemMessage", - "ItemOutputMessage", - "ItemReasoningItem", - "ItemReferenceParam", - "ItemWebSearchToolCall", - "KeyPressAction", - "LocalEnvironmentResource", - "LocalShellExecAction", - "LocalShellToolParam", - "LocalSkillParam", - "LogProb", - "MCPApprovalResponse", - "MCPListToolsTool", - "MCPListToolsToolAnnotations", - "MCPListToolsToolInputSchema", - "MCPTool", - "MCPToolFilter", - "MCPToolRequireApproval", - "MemoryItem", - "MemorySearchItem", - "MemorySearchOptions", - "MemorySearchPreviewTool", - "MemorySearchToolCallItemParam", - "MemorySearchToolCallItemResource", - "MessageContent", - "MessageContentInputFileContent", - "MessageContentInputImageContent", - "MessageContentInputTextContent", - "MessageContentOutputTextContent", - "MessageContentReasoningTextContent", - "MessageContentRefusalContent", - "Metadata", - "MicrosoftFabricPreviewTool", - "MoveParam", - "OAuthConsentRequestOutputItem", - "OpenApiAnonymousAuthDetails", - "OpenApiAuthDetails", - "OpenApiFunctionDefinition", - "OpenApiFunctionDefinitionFunction", - "OpenApiManagedAuthDetails", - "OpenApiManagedSecurityScheme", - "OpenApiProjectConnectionAuthDetails", - "OpenApiProjectConnectionSecurityScheme", - "OpenApiTool", - "OpenApiToolCall", - "OpenApiToolCallOutput", - "OutputContent", - "OutputContentOutputTextContent", - "OutputContentReasoningTextContent", - "OutputContentRefusalContent", - "OutputItem", - "OutputItemApplyPatchToolCall", - "OutputItemApplyPatchToolCallOutput", - "OutputItemCodeInterpreterToolCall", - "OutputItemCompactionBody", - "OutputItemComputerToolCall", - "OutputItemComputerToolCallOutputResource", - "OutputItemCustomToolCall", - "OutputItemCustomToolCallOutput", - "OutputItemFileSearchToolCall", - "OutputItemFunctionShellCall", - "OutputItemFunctionShellCallOutput", - "OutputItemFunctionToolCall", - "OutputItemImageGenToolCall", - "OutputItemLocalShellToolCall", - "OutputItemLocalShellToolCallOutput", - "OutputItemMcpApprovalRequest", - "OutputItemMcpApprovalResponseResource", - "OutputItemMcpListTools", - "OutputItemMcpToolCall", - "OutputItemMessage", - "OutputItemOutputMessage", - "OutputItemReasoningItem", - "OutputItemWebSearchToolCall", - "OutputMessageContent", - "OutputMessageContentOutputTextContent", - "OutputMessageContentRefusalContent", - "Prompt", - "RankingOptions", - "Reasoning", - "ReasoningTextContent", - "ResponseAudioDeltaEvent", - "ResponseAudioDoneEvent", - "ResponseAudioTranscriptDeltaEvent", - "ResponseAudioTranscriptDoneEvent", - "ResponseCodeInterpreterCallCodeDeltaEvent", - "ResponseCodeInterpreterCallCodeDoneEvent", - "ResponseCodeInterpreterCallCompletedEvent", - "ResponseCodeInterpreterCallInProgressEvent", - "ResponseCodeInterpreterCallInterpretingEvent", - "ResponseCompletedEvent", - "ResponseContentPartAddedEvent", - "ResponseContentPartDoneEvent", - "ResponseCreatedEvent", - "ResponseCustomToolCallInputDeltaEvent", - "ResponseCustomToolCallInputDoneEvent", - "ResponseErrorEvent", - "ResponseErrorInfo", - "ResponseFailedEvent", - "ResponseFileSearchCallCompletedEvent", - "ResponseFileSearchCallInProgressEvent", - "ResponseFileSearchCallSearchingEvent", - "ResponseFormatJsonSchemaSchema", - "ResponseFunctionCallArgumentsDeltaEvent", - "ResponseFunctionCallArgumentsDoneEvent", - "ResponseImageGenCallCompletedEvent", - "ResponseImageGenCallGeneratingEvent", - "ResponseImageGenCallInProgressEvent", - "ResponseImageGenCallPartialImageEvent", - "ResponseInProgressEvent", - "ResponseIncompleteDetails", - "ResponseIncompleteEvent", - "ResponseLogProb", - "ResponseLogProbTopLogprobs", - "ResponseMCPCallArgumentsDeltaEvent", - "ResponseMCPCallArgumentsDoneEvent", - "ResponseMCPCallCompletedEvent", - "ResponseMCPCallFailedEvent", - "ResponseMCPCallInProgressEvent", - "ResponseMCPListToolsCompletedEvent", - "ResponseMCPListToolsFailedEvent", - "ResponseMCPListToolsInProgressEvent", - "ResponseObject", - "ResponseOutputItemAddedEvent", - "ResponseOutputItemDoneEvent", - "ResponseOutputTextAnnotationAddedEvent", - "ResponsePromptVariables", - "ResponseQueuedEvent", - "ResponseReasoningSummaryPartAddedEvent", - "ResponseReasoningSummaryPartAddedEventPart", - "ResponseReasoningSummaryPartDoneEvent", - "ResponseReasoningSummaryPartDoneEventPart", - "ResponseReasoningSummaryTextDeltaEvent", - "ResponseReasoningSummaryTextDoneEvent", - "ResponseReasoningTextDeltaEvent", - "ResponseReasoningTextDoneEvent", - "ResponseRefusalDeltaEvent", - "ResponseRefusalDoneEvent", - "ResponseStreamEvent", - "ResponseStreamOptions", - "ResponseTextDeltaEvent", - "ResponseTextDoneEvent", - "ResponseTextParam", - "ResponseUsage", - "ResponseUsageInputTokensDetails", - "ResponseUsageOutputTokensDetails", - "ResponseWebSearchCallCompletedEvent", - "ResponseWebSearchCallInProgressEvent", - "ResponseWebSearchCallSearchingEvent", - "ScreenshotParam", - "ScrollParam", - "SharepointGroundingToolCall", - "SharepointGroundingToolCallOutput", - "SharepointGroundingToolParameters", - "SharepointPreviewTool", - "SkillReferenceParam", - "SpecificApplyPatchParam", - "SpecificFunctionShellParam", - "StructuredOutputDefinition", - "StructuredOutputsOutputItem", - "SummaryTextContent", - "TextContent", - "TextResponseFormatConfiguration", - "TextResponseFormatConfigurationResponseFormatJsonObject", - "TextResponseFormatConfigurationResponseFormatText", - "TextResponseFormatJsonSchema", - "Tool", - "ToolChoiceAllowed", - "ToolChoiceCodeInterpreter", - "ToolChoiceComputerUsePreview", - "ToolChoiceCustom", - "ToolChoiceFileSearch", - "ToolChoiceFunction", - "ToolChoiceImageGeneration", - "ToolChoiceMCP", - "ToolChoiceParam", - "ToolChoiceWebSearchPreview", - "ToolChoiceWebSearchPreview20250311", - "ToolProjectConnection", - "TopLogProb", - "TypeParam", - "UrlCitationBody", - "UserProfileMemoryItem", - "VectorStoreFileAttributes", - "WaitParam", - "WebSearchActionFind", - "WebSearchActionOpenPage", - "WebSearchActionSearch", - "WebSearchActionSearchSources", - "WebSearchApproximateLocation", - "WebSearchConfiguration", - "WebSearchPreviewTool", - "WebSearchTool", - "WebSearchToolFilters", - "WorkIQPreviewTool", - "WorkIQPreviewToolParameters", - "WorkflowActionOutputItem", - "AnnotationType", - "ApplyPatchCallOutputStatus", - "ApplyPatchCallOutputStatusParam", - "ApplyPatchCallStatus", - "ApplyPatchCallStatusParam", - "ApplyPatchFileOperationType", - "ApplyPatchOperationParamType", - "AzureAISearchQueryType", - "ClickButtonType", - "ComputerActionType", - "ComputerEnvironment", - "ContainerMemoryLimit", - "ContainerNetworkPolicyParamType", - "ContainerSkillType", - "CustomToolParamFormatType", - "DetailEnum", - "FunctionAndCustomToolCallOutputType", - "FunctionCallItemStatus", - "FunctionShellCallEnvironmentType", - "FunctionShellCallItemParamEnvironmentType", - "FunctionShellCallItemStatus", - "FunctionShellCallOutputOutcomeParamType", - "FunctionShellCallOutputOutcomeType", - "FunctionShellToolParamEnvironmentType", - "GrammarSyntax1", - "ImageDetail", - "ImageGenActionEnum", - "IncludeEnum", - "InputFidelity", - "ItemFieldType", - "ItemType", - "LocalShellCallOutputStatusEnum", - "LocalShellCallStatus", - "MCPToolCallStatus", - "MemoryItemKind", - "MessageContentType", - "MessageRole", - "MessageStatus", - "ModelIdsCompaction", - "OpenApiAuthType", - "OutputContentType", - "OutputItemType", - "OutputMessageContentType", - "PageOrder", - "RankerVersionType", - "ResponseErrorCode", - "ResponseStreamEventType", - "SearchContextSize", - "TextResponseFormatConfigurationType", - "ToolCallStatus", - "ToolChoiceOptions", - "ToolChoiceParamType", - "ToolType", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/models/_enums.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/models/_enums.py deleted file mode 100644 index 4ac334096a58..000000000000 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/models/_enums.py +++ /dev/null @@ -1,1226 +0,0 @@ -# pylint: disable=too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from enum import Enum -from azure.core import CaseInsensitiveEnumMeta - - -class AnnotationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of AnnotationType.""" - - FILE_CITATION = "file_citation" - """FILE_CITATION.""" - URL_CITATION = "url_citation" - """URL_CITATION.""" - CONTAINER_FILE_CITATION = "container_file_citation" - """CONTAINER_FILE_CITATION.""" - FILE_PATH = "file_path" - """FILE_PATH.""" - - -class ApplyPatchCallOutputStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of ApplyPatchCallOutputStatus.""" - - COMPLETED = "completed" - """COMPLETED.""" - FAILED = "failed" - """FAILED.""" - - -class ApplyPatchCallOutputStatusParam(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Apply patch call output status.""" - - COMPLETED = "completed" - """COMPLETED.""" - FAILED = "failed" - """FAILED.""" - - -class ApplyPatchCallStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of ApplyPatchCallStatus.""" - - IN_PROGRESS = "in_progress" - """IN_PROGRESS.""" - COMPLETED = "completed" - """COMPLETED.""" - - -class ApplyPatchCallStatusParam(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Apply patch call status.""" - - IN_PROGRESS = "in_progress" - """IN_PROGRESS.""" - COMPLETED = "completed" - """COMPLETED.""" - - -class ApplyPatchFileOperationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of ApplyPatchFileOperationType.""" - - CREATE_FILE = "create_file" - """CREATE_FILE.""" - DELETE_FILE = "delete_file" - """DELETE_FILE.""" - UPDATE_FILE = "update_file" - """UPDATE_FILE.""" - - -class ApplyPatchOperationParamType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of ApplyPatchOperationParamType.""" - - CREATE_FILE = "create_file" - """CREATE_FILE.""" - DELETE_FILE = "delete_file" - """DELETE_FILE.""" - UPDATE_FILE = "update_file" - """UPDATE_FILE.""" - - -class AzureAISearchQueryType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Available query types for Azure AI Search tool.""" - - SIMPLE = "simple" - """Query type ``simple``.""" - SEMANTIC = "semantic" - """Query type ``semantic``.""" - VECTOR = "vector" - """Query type ``vector``.""" - VECTOR_SIMPLE_HYBRID = "vector_simple_hybrid" - """Query type ``vector_simple_hybrid``.""" - VECTOR_SEMANTIC_HYBRID = "vector_semantic_hybrid" - """Query type ``vector_semantic_hybrid``.""" - - -class ClickButtonType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of ClickButtonType.""" - - LEFT = "left" - """LEFT.""" - RIGHT = "right" - """RIGHT.""" - WHEEL = "wheel" - """WHEEL.""" - BACK = "back" - """BACK.""" - FORWARD = "forward" - """FORWARD.""" - - -class ComputerActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of ComputerActionType.""" - - CLICK = "click" - """CLICK.""" - DOUBLE_CLICK = "double_click" - """DOUBLE_CLICK.""" - DRAG = "drag" - """DRAG.""" - KEYPRESS = "keypress" - """KEYPRESS.""" - MOVE = "move" - """MOVE.""" - SCREENSHOT = "screenshot" - """SCREENSHOT.""" - SCROLL = "scroll" - """SCROLL.""" - TYPE = "type" - """TYPE.""" - WAIT = "wait" - """WAIT.""" - - -class ComputerEnvironment(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of ComputerEnvironment.""" - - WINDOWS = "windows" - """WINDOWS.""" - MAC = "mac" - """MAC.""" - LINUX = "linux" - """LINUX.""" - UBUNTU = "ubuntu" - """UBUNTU.""" - BROWSER = "browser" - """BROWSER.""" - - -class ContainerMemoryLimit(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of ContainerMemoryLimit.""" - - ENUM_1_G = "1g" - """1_G.""" - ENUM_4_G = "4g" - """4_G.""" - ENUM_16_G = "16g" - """16_G.""" - ENUM_64_G = "64g" - """64_G.""" - - -class ContainerNetworkPolicyParamType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of ContainerNetworkPolicyParamType.""" - - DISABLED = "disabled" - """DISABLED.""" - ALLOWLIST = "allowlist" - """ALLOWLIST.""" - - -class ContainerSkillType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of ContainerSkillType.""" - - SKILL_REFERENCE = "skill_reference" - """SKILL_REFERENCE.""" - INLINE = "inline" - """INLINE.""" - - -class CustomToolParamFormatType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of CustomToolParamFormatType.""" - - TEXT = "text" - """TEXT.""" - GRAMMAR = "grammar" - """GRAMMAR.""" - - -class DetailEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of DetailEnum.""" - - LOW = "low" - """LOW.""" - HIGH = "high" - """HIGH.""" - AUTO = "auto" - """AUTO.""" - - -class FunctionAndCustomToolCallOutputType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of FunctionAndCustomToolCallOutputType.""" - - INPUT_TEXT = "input_text" - """INPUT_TEXT.""" - INPUT_IMAGE = "input_image" - """INPUT_IMAGE.""" - INPUT_FILE = "input_file" - """INPUT_FILE.""" - - -class FunctionCallItemStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of FunctionCallItemStatus.""" - - IN_PROGRESS = "in_progress" - """IN_PROGRESS.""" - COMPLETED = "completed" - """COMPLETED.""" - INCOMPLETE = "incomplete" - """INCOMPLETE.""" - - -class FunctionShellCallEnvironmentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of FunctionShellCallEnvironmentType.""" - - LOCAL = "local" - """LOCAL.""" - CONTAINER_REFERENCE = "container_reference" - """CONTAINER_REFERENCE.""" - - -class FunctionShellCallItemParamEnvironmentType( # pylint: disable=name-too-long - str, Enum, metaclass=CaseInsensitiveEnumMeta -): - """Type of FunctionShellCallItemParamEnvironmentType.""" - - LOCAL = "local" - """LOCAL.""" - CONTAINER_REFERENCE = "container_reference" - """CONTAINER_REFERENCE.""" - - -class FunctionShellCallItemStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Shell call status.""" - - IN_PROGRESS = "in_progress" - """IN_PROGRESS.""" - COMPLETED = "completed" - """COMPLETED.""" - INCOMPLETE = "incomplete" - """INCOMPLETE.""" - - -class FunctionShellCallOutputOutcomeParamType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of FunctionShellCallOutputOutcomeParamType.""" - - TIMEOUT = "timeout" - """TIMEOUT.""" - EXIT = "exit" - """EXIT.""" - - -class FunctionShellCallOutputOutcomeType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of FunctionShellCallOutputOutcomeType.""" - - TIMEOUT = "timeout" - """TIMEOUT.""" - EXIT = "exit" - """EXIT.""" - - -class FunctionShellToolParamEnvironmentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of FunctionShellToolParamEnvironmentType.""" - - CONTAINER_AUTO = "container_auto" - """CONTAINER_AUTO.""" - LOCAL = "local" - """LOCAL.""" - CONTAINER_REFERENCE = "container_reference" - """CONTAINER_REFERENCE.""" - - -class GrammarSyntax1(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of GrammarSyntax1.""" - - LARK = "lark" - """LARK.""" - REGEX = "regex" - """REGEX.""" - - -class ImageDetail(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of ImageDetail.""" - - LOW = "low" - """LOW.""" - HIGH = "high" - """HIGH.""" - AUTO = "auto" - """AUTO.""" - - -class ImageGenActionEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of ImageGenActionEnum.""" - - GENERATE = "generate" - """GENERATE.""" - EDIT = "edit" - """EDIT.""" - AUTO = "auto" - """AUTO.""" - - -class IncludeEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Specify additional output data to include in the model response. Currently supported values - are: - - * `web_search_call.action.sources`: Include the sources of the web search tool call. - * `code_interpreter_call.outputs`: Includes the outputs of python code execution in code - interpreter tool call items. - * `computer_call_output.output.image_url`: Include image urls from the computer call output. - * `file_search_call.results`: Include the search results of the file search tool call. - * `message.input_image.image_url`: Include image urls from the input message. - * `message.output_text.logprobs`: Include logprobs with assistant messages. - * `reasoning.encrypted_content`: Includes an encrypted version of reasoning tokens in reasoning - item outputs. This enables reasoning items to be used in multi-turn conversations when using - the Responses API statelessly (like when the `store` parameter is set to `false`, or when an - organization is enrolled in the zero data retention program). - """ - - FILE_SEARCH_CALL_RESULTS = "file_search_call.results" - """FILE_SEARCH_CALL_RESULTS.""" - WEB_SEARCH_CALL_RESULTS = "web_search_call.results" - """WEB_SEARCH_CALL_RESULTS.""" - WEB_SEARCH_CALL_ACTION_SOURCES = "web_search_call.action.sources" - """WEB_SEARCH_CALL_ACTION_SOURCES.""" - MESSAGE_INPUT_IMAGE_IMAGE_URL = "message.input_image.image_url" - """MESSAGE_INPUT_IMAGE_IMAGE_URL.""" - COMPUTER_CALL_OUTPUT_OUTPUT_IMAGE_URL = "computer_call_output.output.image_url" - """COMPUTER_CALL_OUTPUT_OUTPUT_IMAGE_URL.""" - CODE_INTERPRETER_CALL_OUTPUTS = "code_interpreter_call.outputs" - """CODE_INTERPRETER_CALL_OUTPUTS.""" - REASONING_ENCRYPTED_CONTENT = "reasoning.encrypted_content" - """REASONING_ENCRYPTED_CONTENT.""" - MESSAGE_OUTPUT_TEXT_LOGPROBS = "message.output_text.logprobs" - """MESSAGE_OUTPUT_TEXT_LOGPROBS.""" - MEMORY_SEARCH_CALL_RESULTS = "memory_search_call.results" - """MEMORY_SEARCH_CALL_RESULTS.""" - - -class InputFidelity(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Control how much effort the model will exert to match the style and features, especially facial - features, of input images. This parameter is only supported for ``gpt-image-1`` and - ``gpt-image-1.5`` and later models, unsupported for ``gpt-image-1-mini``. Supports ``high`` and - ``low``. Defaults to ``low``. - """ - - HIGH = "high" - """HIGH.""" - LOW = "low" - """LOW.""" - - -class ItemFieldType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of ItemFieldType.""" - - MESSAGE = "message" - """MESSAGE.""" - FUNCTION_CALL = "function_call" - """FUNCTION_CALL.""" - FUNCTION_CALL_OUTPUT = "function_call_output" - """FUNCTION_CALL_OUTPUT.""" - FILE_SEARCH_CALL = "file_search_call" - """FILE_SEARCH_CALL.""" - WEB_SEARCH_CALL = "web_search_call" - """WEB_SEARCH_CALL.""" - IMAGE_GENERATION_CALL = "image_generation_call" - """IMAGE_GENERATION_CALL.""" - COMPUTER_CALL = "computer_call" - """COMPUTER_CALL.""" - COMPUTER_CALL_OUTPUT = "computer_call_output" - """COMPUTER_CALL_OUTPUT.""" - REASONING = "reasoning" - """REASONING.""" - COMPACTION = "compaction" - """COMPACTION.""" - CODE_INTERPRETER_CALL = "code_interpreter_call" - """CODE_INTERPRETER_CALL.""" - LOCAL_SHELL_CALL = "local_shell_call" - """LOCAL_SHELL_CALL.""" - LOCAL_SHELL_CALL_OUTPUT = "local_shell_call_output" - """LOCAL_SHELL_CALL_OUTPUT.""" - SHELL_CALL = "shell_call" - """SHELL_CALL.""" - SHELL_CALL_OUTPUT = "shell_call_output" - """SHELL_CALL_OUTPUT.""" - APPLY_PATCH_CALL = "apply_patch_call" - """APPLY_PATCH_CALL.""" - APPLY_PATCH_CALL_OUTPUT = "apply_patch_call_output" - """APPLY_PATCH_CALL_OUTPUT.""" - MCP_LIST_TOOLS = "mcp_list_tools" - """MCP_LIST_TOOLS.""" - MCP_APPROVAL_REQUEST = "mcp_approval_request" - """MCP_APPROVAL_REQUEST.""" - MCP_APPROVAL_RESPONSE = "mcp_approval_response" - """MCP_APPROVAL_RESPONSE.""" - MCP_CALL = "mcp_call" - """MCP_CALL.""" - CUSTOM_TOOL_CALL = "custom_tool_call" - """CUSTOM_TOOL_CALL.""" - CUSTOM_TOOL_CALL_OUTPUT = "custom_tool_call_output" - """CUSTOM_TOOL_CALL_OUTPUT.""" - - -class ItemType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of ItemType.""" - - MESSAGE = "message" - """MESSAGE.""" - OUTPUT_MESSAGE = "output_message" - """OUTPUT_MESSAGE.""" - FILE_SEARCH_CALL = "file_search_call" - """FILE_SEARCH_CALL.""" - COMPUTER_CALL = "computer_call" - """COMPUTER_CALL.""" - COMPUTER_CALL_OUTPUT = "computer_call_output" - """COMPUTER_CALL_OUTPUT.""" - WEB_SEARCH_CALL = "web_search_call" - """WEB_SEARCH_CALL.""" - FUNCTION_CALL = "function_call" - """FUNCTION_CALL.""" - FUNCTION_CALL_OUTPUT = "function_call_output" - """FUNCTION_CALL_OUTPUT.""" - REASONING = "reasoning" - """REASONING.""" - COMPACTION = "compaction" - """COMPACTION.""" - IMAGE_GENERATION_CALL = "image_generation_call" - """IMAGE_GENERATION_CALL.""" - CODE_INTERPRETER_CALL = "code_interpreter_call" - """CODE_INTERPRETER_CALL.""" - LOCAL_SHELL_CALL = "local_shell_call" - """LOCAL_SHELL_CALL.""" - LOCAL_SHELL_CALL_OUTPUT = "local_shell_call_output" - """LOCAL_SHELL_CALL_OUTPUT.""" - SHELL_CALL = "shell_call" - """SHELL_CALL.""" - SHELL_CALL_OUTPUT = "shell_call_output" - """SHELL_CALL_OUTPUT.""" - APPLY_PATCH_CALL = "apply_patch_call" - """APPLY_PATCH_CALL.""" - APPLY_PATCH_CALL_OUTPUT = "apply_patch_call_output" - """APPLY_PATCH_CALL_OUTPUT.""" - MCP_LIST_TOOLS = "mcp_list_tools" - """MCP_LIST_TOOLS.""" - MCP_APPROVAL_REQUEST = "mcp_approval_request" - """MCP_APPROVAL_REQUEST.""" - MCP_APPROVAL_RESPONSE = "mcp_approval_response" - """MCP_APPROVAL_RESPONSE.""" - MCP_CALL = "mcp_call" - """MCP_CALL.""" - CUSTOM_TOOL_CALL_OUTPUT = "custom_tool_call_output" - """CUSTOM_TOOL_CALL_OUTPUT.""" - CUSTOM_TOOL_CALL = "custom_tool_call" - """CUSTOM_TOOL_CALL.""" - ITEM_REFERENCE = "item_reference" - """ITEM_REFERENCE.""" - STRUCTURED_OUTPUTS = "structured_outputs" - """STRUCTURED_OUTPUTS.""" - OAUTH_CONSENT_REQUEST = "oauth_consent_request" - """OAUTH_CONSENT_REQUEST.""" - MEMORY_SEARCH_CALL = "memory_search_call" - """MEMORY_SEARCH_CALL.""" - WORKFLOW_ACTION = "workflow_action" - """WORKFLOW_ACTION.""" - A2_A_PREVIEW_CALL = "a2a_preview_call" - """A2_A_PREVIEW_CALL.""" - A2_A_PREVIEW_CALL_OUTPUT = "a2a_preview_call_output" - """A2_A_PREVIEW_CALL_OUTPUT.""" - BING_GROUNDING_CALL = "bing_grounding_call" - """BING_GROUNDING_CALL.""" - BING_GROUNDING_CALL_OUTPUT = "bing_grounding_call_output" - """BING_GROUNDING_CALL_OUTPUT.""" - SHAREPOINT_GROUNDING_PREVIEW_CALL = "sharepoint_grounding_preview_call" - """SHAREPOINT_GROUNDING_PREVIEW_CALL.""" - SHAREPOINT_GROUNDING_PREVIEW_CALL_OUTPUT = "sharepoint_grounding_preview_call_output" - """SHAREPOINT_GROUNDING_PREVIEW_CALL_OUTPUT.""" - AZURE_AI_SEARCH_CALL = "azure_ai_search_call" - """AZURE_AI_SEARCH_CALL.""" - AZURE_AI_SEARCH_CALL_OUTPUT = "azure_ai_search_call_output" - """AZURE_AI_SEARCH_CALL_OUTPUT.""" - BING_CUSTOM_SEARCH_PREVIEW_CALL = "bing_custom_search_preview_call" - """BING_CUSTOM_SEARCH_PREVIEW_CALL.""" - BING_CUSTOM_SEARCH_PREVIEW_CALL_OUTPUT = "bing_custom_search_preview_call_output" - """BING_CUSTOM_SEARCH_PREVIEW_CALL_OUTPUT.""" - OPENAPI_CALL = "openapi_call" - """OPENAPI_CALL.""" - OPENAPI_CALL_OUTPUT = "openapi_call_output" - """OPENAPI_CALL_OUTPUT.""" - BROWSER_AUTOMATION_PREVIEW_CALL = "browser_automation_preview_call" - """BROWSER_AUTOMATION_PREVIEW_CALL.""" - BROWSER_AUTOMATION_PREVIEW_CALL_OUTPUT = "browser_automation_preview_call_output" - """BROWSER_AUTOMATION_PREVIEW_CALL_OUTPUT.""" - FABRIC_DATAAGENT_PREVIEW_CALL = "fabric_dataagent_preview_call" - """FABRIC_DATAAGENT_PREVIEW_CALL.""" - FABRIC_DATAAGENT_PREVIEW_CALL_OUTPUT = "fabric_dataagent_preview_call_output" - """FABRIC_DATAAGENT_PREVIEW_CALL_OUTPUT.""" - AZURE_FUNCTION_CALL = "azure_function_call" - """AZURE_FUNCTION_CALL.""" - AZURE_FUNCTION_CALL_OUTPUT = "azure_function_call_output" - """AZURE_FUNCTION_CALL_OUTPUT.""" - - -class LocalShellCallOutputStatusEnum(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of LocalShellCallOutputStatusEnum.""" - - IN_PROGRESS = "in_progress" - """IN_PROGRESS.""" - COMPLETED = "completed" - """COMPLETED.""" - INCOMPLETE = "incomplete" - """INCOMPLETE.""" - - -class LocalShellCallStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of LocalShellCallStatus.""" - - IN_PROGRESS = "in_progress" - """IN_PROGRESS.""" - COMPLETED = "completed" - """COMPLETED.""" - INCOMPLETE = "incomplete" - """INCOMPLETE.""" - - -class MCPToolCallStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of MCPToolCallStatus.""" - - IN_PROGRESS = "in_progress" - """IN_PROGRESS.""" - COMPLETED = "completed" - """COMPLETED.""" - INCOMPLETE = "incomplete" - """INCOMPLETE.""" - CALLING = "calling" - """CALLING.""" - FAILED = "failed" - """FAILED.""" - - -class MemoryItemKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Memory item kind.""" - - USER_PROFILE = "user_profile" - """User profile information extracted from conversations.""" - CHAT_SUMMARY = "chat_summary" - """Summary of chat conversations.""" - - -class MessageContentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of MessageContentType.""" - - INPUT_TEXT = "input_text" - """INPUT_TEXT.""" - OUTPUT_TEXT = "output_text" - """OUTPUT_TEXT.""" - TEXT = "text" - """TEXT.""" - SUMMARY_TEXT = "summary_text" - """SUMMARY_TEXT.""" - REASONING_TEXT = "reasoning_text" - """REASONING_TEXT.""" - REFUSAL = "refusal" - """REFUSAL.""" - INPUT_IMAGE = "input_image" - """INPUT_IMAGE.""" - COMPUTER_SCREENSHOT = "computer_screenshot" - """COMPUTER_SCREENSHOT.""" - INPUT_FILE = "input_file" - """INPUT_FILE.""" - - -class MessageRole(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of MessageRole.""" - - UNKNOWN = "unknown" - """UNKNOWN.""" - USER = "user" - """USER.""" - ASSISTANT = "assistant" - """ASSISTANT.""" - SYSTEM = "system" - """SYSTEM.""" - CRITIC = "critic" - """CRITIC.""" - DISCRIMINATOR = "discriminator" - """DISCRIMINATOR.""" - DEVELOPER = "developer" - """DEVELOPER.""" - TOOL = "tool" - """TOOL.""" - - -class MessageStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of MessageStatus.""" - - IN_PROGRESS = "in_progress" - """IN_PROGRESS.""" - COMPLETED = "completed" - """COMPLETED.""" - INCOMPLETE = "incomplete" - """INCOMPLETE.""" - - -class ModelIdsCompaction(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Model ID used to generate the response, like ``gpt-5`` or ``o3``. OpenAI offers a wide range of - models with different capabilities, performance characteristics, and price points. Refer to the - `model guide `_ to browse and compare available models. - """ - - GPT5_2 = "gpt-5.2" - """GPT5_2.""" - GPT5_2_2025_12_11 = "gpt-5.2-2025-12-11" - """GPT5_2_2025_12_11.""" - GPT5_2_CHAT_LATEST = "gpt-5.2-chat-latest" - """GPT5_2_CHAT_LATEST.""" - GPT5_2_PRO = "gpt-5.2-pro" - """GPT5_2_PRO.""" - GPT5_2_PRO2025_12_11 = "gpt-5.2-pro-2025-12-11" - """GPT5_2_PRO2025_12_11.""" - GPT5_1 = "gpt-5.1" - """GPT5_1.""" - GPT5_1_2025_11_13 = "gpt-5.1-2025-11-13" - """GPT5_1_2025_11_13.""" - GPT5_1_CODEX = "gpt-5.1-codex" - """GPT5_1_CODEX.""" - GPT5_1_MINI = "gpt-5.1-mini" - """GPT5_1_MINI.""" - GPT5_1_CHAT_LATEST = "gpt-5.1-chat-latest" - """GPT5_1_CHAT_LATEST.""" - GPT5 = "gpt-5" - """GPT5.""" - GPT5_MINI = "gpt-5-mini" - """GPT5_MINI.""" - GPT5_NANO = "gpt-5-nano" - """GPT5_NANO.""" - GPT5_2025_08_07 = "gpt-5-2025-08-07" - """GPT5_2025_08_07.""" - GPT5_MINI2025_08_07 = "gpt-5-mini-2025-08-07" - """GPT5_MINI2025_08_07.""" - GPT5_NANO2025_08_07 = "gpt-5-nano-2025-08-07" - """GPT5_NANO2025_08_07.""" - GPT5_CHAT_LATEST = "gpt-5-chat-latest" - """GPT5_CHAT_LATEST.""" - GPT4_1 = "gpt-4.1" - """GPT4_1.""" - GPT4_1_MINI = "gpt-4.1-mini" - """GPT4_1_MINI.""" - GPT4_1_NANO = "gpt-4.1-nano" - """GPT4_1_NANO.""" - GPT4_1_2025_04_14 = "gpt-4.1-2025-04-14" - """GPT4_1_2025_04_14.""" - GPT4_1_MINI2025_04_14 = "gpt-4.1-mini-2025-04-14" - """GPT4_1_MINI2025_04_14.""" - GPT4_1_NANO2025_04_14 = "gpt-4.1-nano-2025-04-14" - """GPT4_1_NANO2025_04_14.""" - O4_MINI = "o4-mini" - """O4_MINI.""" - O4_MINI2025_04_16 = "o4-mini-2025-04-16" - """O4_MINI2025_04_16.""" - O3 = "o3" - """O3.""" - O3_2025_04_16 = "o3-2025-04-16" - """O3_2025_04_16.""" - O3_MINI = "o3-mini" - """O3_MINI.""" - O3_MINI2025_01_31 = "o3-mini-2025-01-31" - """O3_MINI2025_01_31.""" - O1 = "o1" - """O1.""" - O1_2024_12_17 = "o1-2024-12-17" - """O1_2024_12_17.""" - O1_PREVIEW = "o1-preview" - """O1_PREVIEW.""" - O1_PREVIEW2024_09_12 = "o1-preview-2024-09-12" - """O1_PREVIEW2024_09_12.""" - O1_MINI = "o1-mini" - """O1_MINI.""" - O1_MINI2024_09_12 = "o1-mini-2024-09-12" - """O1_MINI2024_09_12.""" - GPT4_O = "gpt-4o" - """GPT4_O.""" - GPT4_O2024_11_20 = "gpt-4o-2024-11-20" - """GPT4_O2024_11_20.""" - GPT4_O2024_08_06 = "gpt-4o-2024-08-06" - """GPT4_O2024_08_06.""" - GPT4_O2024_05_13 = "gpt-4o-2024-05-13" - """GPT4_O2024_05_13.""" - GPT4_O_AUDIO_PREVIEW = "gpt-4o-audio-preview" - """GPT4_O_AUDIO_PREVIEW.""" - GPT4_O_AUDIO_PREVIEW2024_10_01 = "gpt-4o-audio-preview-2024-10-01" - """GPT4_O_AUDIO_PREVIEW2024_10_01.""" - GPT4_O_AUDIO_PREVIEW2024_12_17 = "gpt-4o-audio-preview-2024-12-17" - """GPT4_O_AUDIO_PREVIEW2024_12_17.""" - GPT4_O_AUDIO_PREVIEW2025_06_03 = "gpt-4o-audio-preview-2025-06-03" - """GPT4_O_AUDIO_PREVIEW2025_06_03.""" - GPT4_O_MINI_AUDIO_PREVIEW = "gpt-4o-mini-audio-preview" - """GPT4_O_MINI_AUDIO_PREVIEW.""" - GPT4_O_MINI_AUDIO_PREVIEW2024_12_17 = "gpt-4o-mini-audio-preview-2024-12-17" - """GPT4_O_MINI_AUDIO_PREVIEW2024_12_17.""" - GPT4_O_SEARCH_PREVIEW = "gpt-4o-search-preview" - """GPT4_O_SEARCH_PREVIEW.""" - GPT4_O_MINI_SEARCH_PREVIEW = "gpt-4o-mini-search-preview" - """GPT4_O_MINI_SEARCH_PREVIEW.""" - GPT4_O_SEARCH_PREVIEW2025_03_11 = "gpt-4o-search-preview-2025-03-11" - """GPT4_O_SEARCH_PREVIEW2025_03_11.""" - GPT4_O_MINI_SEARCH_PREVIEW2025_03_11 = "gpt-4o-mini-search-preview-2025-03-11" - """GPT4_O_MINI_SEARCH_PREVIEW2025_03_11.""" - CHATGPT4_O_LATEST = "chatgpt-4o-latest" - """CHATGPT4_O_LATEST.""" - CODEX_MINI_LATEST = "codex-mini-latest" - """CODEX_MINI_LATEST.""" - GPT4_O_MINI = "gpt-4o-mini" - """GPT4_O_MINI.""" - GPT4_O_MINI2024_07_18 = "gpt-4o-mini-2024-07-18" - """GPT4_O_MINI2024_07_18.""" - GPT4_TURBO = "gpt-4-turbo" - """GPT4_TURBO.""" - GPT4_TURBO2024_04_09 = "gpt-4-turbo-2024-04-09" - """GPT4_TURBO2024_04_09.""" - GPT4_0125_PREVIEW = "gpt-4-0125-preview" - """GPT4_0125_PREVIEW.""" - GPT4_TURBO_PREVIEW = "gpt-4-turbo-preview" - """GPT4_TURBO_PREVIEW.""" - GPT4_1106_PREVIEW = "gpt-4-1106-preview" - """GPT4_1106_PREVIEW.""" - GPT4_VISION_PREVIEW = "gpt-4-vision-preview" - """GPT4_VISION_PREVIEW.""" - GPT4 = "gpt-4" - """GPT4.""" - GPT4_0314 = "gpt-4-0314" - """GPT4_0314.""" - GPT4_0613 = "gpt-4-0613" - """GPT4_0613.""" - GPT4_32_K = "gpt-4-32k" - """GPT4_32_K.""" - GPT4_32_K0314 = "gpt-4-32k-0314" - """GPT4_32_K0314.""" - GPT4_32_K0613 = "gpt-4-32k-0613" - """GPT4_32_K0613.""" - GPT3_5_TURBO = "gpt-3.5-turbo" - """GPT3_5_TURBO.""" - GPT3_5_TURBO16_K = "gpt-3.5-turbo-16k" - """GPT3_5_TURBO16_K.""" - GPT3_5_TURBO0301 = "gpt-3.5-turbo-0301" - """GPT3_5_TURBO0301.""" - GPT3_5_TURBO0613 = "gpt-3.5-turbo-0613" - """GPT3_5_TURBO0613.""" - GPT3_5_TURBO1106 = "gpt-3.5-turbo-1106" - """GPT3_5_TURBO1106.""" - GPT3_5_TURBO0125 = "gpt-3.5-turbo-0125" - """GPT3_5_TURBO0125.""" - GPT3_5_TURBO16_K0613 = "gpt-3.5-turbo-16k-0613" - """GPT3_5_TURBO16_K0613.""" - O1_PRO = "o1-pro" - """O1_PRO.""" - O1_PRO2025_03_19 = "o1-pro-2025-03-19" - """O1_PRO2025_03_19.""" - O3_PRO = "o3-pro" - """O3_PRO.""" - O3_PRO2025_06_10 = "o3-pro-2025-06-10" - """O3_PRO2025_06_10.""" - O3_DEEP_RESEARCH = "o3-deep-research" - """O3_DEEP_RESEARCH.""" - O3_DEEP_RESEARCH2025_06_26 = "o3-deep-research-2025-06-26" - """O3_DEEP_RESEARCH2025_06_26.""" - O4_MINI_DEEP_RESEARCH = "o4-mini-deep-research" - """O4_MINI_DEEP_RESEARCH.""" - O4_MINI_DEEP_RESEARCH2025_06_26 = "o4-mini-deep-research-2025-06-26" - """O4_MINI_DEEP_RESEARCH2025_06_26.""" - COMPUTER_USE_PREVIEW = "computer-use-preview" - """COMPUTER_USE_PREVIEW.""" - COMPUTER_USE_PREVIEW2025_03_11 = "computer-use-preview-2025-03-11" - """COMPUTER_USE_PREVIEW2025_03_11.""" - GPT5_CODEX = "gpt-5-codex" - """GPT5_CODEX.""" - GPT5_PRO = "gpt-5-pro" - """GPT5_PRO.""" - GPT5_PRO2025_10_06 = "gpt-5-pro-2025-10-06" - """GPT5_PRO2025_10_06.""" - GPT5_1_CODEX_MAX = "gpt-5.1-codex-max" - """GPT5_1_CODEX_MAX.""" - - -class OpenApiAuthType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Authentication type for OpenApi endpoint. Allowed types are: - - * Anonymous (no authentication required) - * Project Connection (requires project_connection_id to endpoint, as setup in AI Foundry) - * Managed_Identity (requires audience for identity based auth). - """ - - ANONYMOUS = "anonymous" - """ANONYMOUS.""" - PROJECT_CONNECTION = "project_connection" - """PROJECT_CONNECTION.""" - MANAGED_IDENTITY = "managed_identity" - """MANAGED_IDENTITY.""" - - -class OutputContentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of OutputContentType.""" - - OUTPUT_TEXT = "output_text" - """OUTPUT_TEXT.""" - REFUSAL = "refusal" - """REFUSAL.""" - REASONING_TEXT = "reasoning_text" - """REASONING_TEXT.""" - - -class OutputItemType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of OutputItemType.""" - - OUTPUT_MESSAGE = "output_message" - """OUTPUT_MESSAGE.""" - FILE_SEARCH_CALL = "file_search_call" - """FILE_SEARCH_CALL.""" - FUNCTION_CALL = "function_call" - """FUNCTION_CALL.""" - WEB_SEARCH_CALL = "web_search_call" - """WEB_SEARCH_CALL.""" - COMPUTER_CALL = "computer_call" - """COMPUTER_CALL.""" - REASONING = "reasoning" - """REASONING.""" - COMPACTION = "compaction" - """COMPACTION.""" - IMAGE_GENERATION_CALL = "image_generation_call" - """IMAGE_GENERATION_CALL.""" - CODE_INTERPRETER_CALL = "code_interpreter_call" - """CODE_INTERPRETER_CALL.""" - LOCAL_SHELL_CALL = "local_shell_call" - """LOCAL_SHELL_CALL.""" - SHELL_CALL = "shell_call" - """SHELL_CALL.""" - SHELL_CALL_OUTPUT = "shell_call_output" - """SHELL_CALL_OUTPUT.""" - APPLY_PATCH_CALL = "apply_patch_call" - """APPLY_PATCH_CALL.""" - APPLY_PATCH_CALL_OUTPUT = "apply_patch_call_output" - """APPLY_PATCH_CALL_OUTPUT.""" - MCP_CALL = "mcp_call" - """MCP_CALL.""" - MCP_LIST_TOOLS = "mcp_list_tools" - """MCP_LIST_TOOLS.""" - MCP_APPROVAL_REQUEST = "mcp_approval_request" - """MCP_APPROVAL_REQUEST.""" - CUSTOM_TOOL_CALL = "custom_tool_call" - """CUSTOM_TOOL_CALL.""" - MESSAGE = "message" - """MESSAGE.""" - COMPUTER_CALL_OUTPUT = "computer_call_output" - """COMPUTER_CALL_OUTPUT.""" - FUNCTION_CALL_OUTPUT = "function_call_output" - """FUNCTION_CALL_OUTPUT.""" - LOCAL_SHELL_CALL_OUTPUT = "local_shell_call_output" - """LOCAL_SHELL_CALL_OUTPUT.""" - MCP_APPROVAL_RESPONSE = "mcp_approval_response" - """MCP_APPROVAL_RESPONSE.""" - CUSTOM_TOOL_CALL_OUTPUT = "custom_tool_call_output" - """CUSTOM_TOOL_CALL_OUTPUT.""" - STRUCTURED_OUTPUTS = "structured_outputs" - """STRUCTURED_OUTPUTS.""" - OAUTH_CONSENT_REQUEST = "oauth_consent_request" - """OAUTH_CONSENT_REQUEST.""" - MEMORY_SEARCH_CALL = "memory_search_call" - """MEMORY_SEARCH_CALL.""" - WORKFLOW_ACTION = "workflow_action" - """WORKFLOW_ACTION.""" - A2_A_PREVIEW_CALL = "a2a_preview_call" - """A2_A_PREVIEW_CALL.""" - A2_A_PREVIEW_CALL_OUTPUT = "a2a_preview_call_output" - """A2_A_PREVIEW_CALL_OUTPUT.""" - BING_GROUNDING_CALL = "bing_grounding_call" - """BING_GROUNDING_CALL.""" - BING_GROUNDING_CALL_OUTPUT = "bing_grounding_call_output" - """BING_GROUNDING_CALL_OUTPUT.""" - SHAREPOINT_GROUNDING_PREVIEW_CALL = "sharepoint_grounding_preview_call" - """SHAREPOINT_GROUNDING_PREVIEW_CALL.""" - SHAREPOINT_GROUNDING_PREVIEW_CALL_OUTPUT = "sharepoint_grounding_preview_call_output" - """SHAREPOINT_GROUNDING_PREVIEW_CALL_OUTPUT.""" - AZURE_AI_SEARCH_CALL = "azure_ai_search_call" - """AZURE_AI_SEARCH_CALL.""" - AZURE_AI_SEARCH_CALL_OUTPUT = "azure_ai_search_call_output" - """AZURE_AI_SEARCH_CALL_OUTPUT.""" - BING_CUSTOM_SEARCH_PREVIEW_CALL = "bing_custom_search_preview_call" - """BING_CUSTOM_SEARCH_PREVIEW_CALL.""" - BING_CUSTOM_SEARCH_PREVIEW_CALL_OUTPUT = "bing_custom_search_preview_call_output" - """BING_CUSTOM_SEARCH_PREVIEW_CALL_OUTPUT.""" - OPENAPI_CALL = "openapi_call" - """OPENAPI_CALL.""" - OPENAPI_CALL_OUTPUT = "openapi_call_output" - """OPENAPI_CALL_OUTPUT.""" - BROWSER_AUTOMATION_PREVIEW_CALL = "browser_automation_preview_call" - """BROWSER_AUTOMATION_PREVIEW_CALL.""" - BROWSER_AUTOMATION_PREVIEW_CALL_OUTPUT = "browser_automation_preview_call_output" - """BROWSER_AUTOMATION_PREVIEW_CALL_OUTPUT.""" - FABRIC_DATAAGENT_PREVIEW_CALL = "fabric_dataagent_preview_call" - """FABRIC_DATAAGENT_PREVIEW_CALL.""" - FABRIC_DATAAGENT_PREVIEW_CALL_OUTPUT = "fabric_dataagent_preview_call_output" - """FABRIC_DATAAGENT_PREVIEW_CALL_OUTPUT.""" - AZURE_FUNCTION_CALL = "azure_function_call" - """AZURE_FUNCTION_CALL.""" - AZURE_FUNCTION_CALL_OUTPUT = "azure_function_call_output" - """AZURE_FUNCTION_CALL_OUTPUT.""" - - -class OutputMessageContentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of OutputMessageContentType.""" - - OUTPUT_TEXT = "output_text" - """OUTPUT_TEXT.""" - REFUSAL = "refusal" - """REFUSAL.""" - - -class PageOrder(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of PageOrder.""" - - ASC = "asc" - """ASC.""" - DESC = "desc" - """DESC.""" - - -class RankerVersionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of RankerVersionType.""" - - AUTO = "auto" - """AUTO.""" - DEFAULT2024_11_15 = "default-2024-11-15" - """DEFAULT2024_11_15.""" - - -class ResponseErrorCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The error code for the response.""" - - SERVER_ERROR = "server_error" - """SERVER_ERROR.""" - RATE_LIMIT_EXCEEDED = "rate_limit_exceeded" - """RATE_LIMIT_EXCEEDED.""" - INVALID_PROMPT = "invalid_prompt" - """INVALID_PROMPT.""" - VECTOR_STORE_TIMEOUT = "vector_store_timeout" - """VECTOR_STORE_TIMEOUT.""" - INVALID_IMAGE = "invalid_image" - """INVALID_IMAGE.""" - INVALID_IMAGE_FORMAT = "invalid_image_format" - """INVALID_IMAGE_FORMAT.""" - INVALID_BASE64_IMAGE = "invalid_base64_image" - """INVALID_BASE64_IMAGE.""" - INVALID_IMAGE_URL = "invalid_image_url" - """INVALID_IMAGE_URL.""" - IMAGE_TOO_LARGE = "image_too_large" - """IMAGE_TOO_LARGE.""" - IMAGE_TOO_SMALL = "image_too_small" - """IMAGE_TOO_SMALL.""" - IMAGE_PARSE_ERROR = "image_parse_error" - """IMAGE_PARSE_ERROR.""" - IMAGE_CONTENT_POLICY_VIOLATION = "image_content_policy_violation" - """IMAGE_CONTENT_POLICY_VIOLATION.""" - INVALID_IMAGE_MODE = "invalid_image_mode" - """INVALID_IMAGE_MODE.""" - IMAGE_FILE_TOO_LARGE = "image_file_too_large" - """IMAGE_FILE_TOO_LARGE.""" - UNSUPPORTED_IMAGE_MEDIA_TYPE = "unsupported_image_media_type" - """UNSUPPORTED_IMAGE_MEDIA_TYPE.""" - EMPTY_IMAGE_FILE = "empty_image_file" - """EMPTY_IMAGE_FILE.""" - FAILED_TO_DOWNLOAD_IMAGE = "failed_to_download_image" - """FAILED_TO_DOWNLOAD_IMAGE.""" - IMAGE_FILE_NOT_FOUND = "image_file_not_found" - """IMAGE_FILE_NOT_FOUND.""" - - -class ResponseStreamEventType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of ResponseStreamEventType.""" - - RESPONSE_AUDIO_DELTA = "response.audio.delta" - """RESPONSE_AUDIO_DELTA.""" - RESPONSE_AUDIO_DONE = "response.audio.done" - """RESPONSE_AUDIO_DONE.""" - RESPONSE_AUDIO_TRANSCRIPT_DELTA = "response.audio.transcript.delta" - """RESPONSE_AUDIO_TRANSCRIPT_DELTA.""" - RESPONSE_AUDIO_TRANSCRIPT_DONE = "response.audio.transcript.done" - """RESPONSE_AUDIO_TRANSCRIPT_DONE.""" - RESPONSE_CODE_INTERPRETER_CALL_CODE_DELTA = "response.code_interpreter_call_code.delta" - """RESPONSE_CODE_INTERPRETER_CALL_CODE_DELTA.""" - RESPONSE_CODE_INTERPRETER_CALL_CODE_DONE = "response.code_interpreter_call_code.done" - """RESPONSE_CODE_INTERPRETER_CALL_CODE_DONE.""" - RESPONSE_CODE_INTERPRETER_CALL_COMPLETED = "response.code_interpreter_call.completed" - """RESPONSE_CODE_INTERPRETER_CALL_COMPLETED.""" - RESPONSE_CODE_INTERPRETER_CALL_IN_PROGRESS = "response.code_interpreter_call.in_progress" - """RESPONSE_CODE_INTERPRETER_CALL_IN_PROGRESS.""" - RESPONSE_CODE_INTERPRETER_CALL_INTERPRETING = "response.code_interpreter_call.interpreting" - """RESPONSE_CODE_INTERPRETER_CALL_INTERPRETING.""" - RESPONSE_COMPLETED = "response.completed" - """RESPONSE_COMPLETED.""" - RESPONSE_CONTENT_PART_ADDED = "response.content_part.added" - """RESPONSE_CONTENT_PART_ADDED.""" - RESPONSE_CONTENT_PART_DONE = "response.content_part.done" - """RESPONSE_CONTENT_PART_DONE.""" - RESPONSE_CREATED = "response.created" - """RESPONSE_CREATED.""" - ERROR = "error" - """ERROR.""" - RESPONSE_FILE_SEARCH_CALL_COMPLETED = "response.file_search_call.completed" - """RESPONSE_FILE_SEARCH_CALL_COMPLETED.""" - RESPONSE_FILE_SEARCH_CALL_IN_PROGRESS = "response.file_search_call.in_progress" - """RESPONSE_FILE_SEARCH_CALL_IN_PROGRESS.""" - RESPONSE_FILE_SEARCH_CALL_SEARCHING = "response.file_search_call.searching" - """RESPONSE_FILE_SEARCH_CALL_SEARCHING.""" - RESPONSE_FUNCTION_CALL_ARGUMENTS_DELTA = "response.function_call_arguments.delta" - """RESPONSE_FUNCTION_CALL_ARGUMENTS_DELTA.""" - RESPONSE_FUNCTION_CALL_ARGUMENTS_DONE = "response.function_call_arguments.done" - """RESPONSE_FUNCTION_CALL_ARGUMENTS_DONE.""" - RESPONSE_IN_PROGRESS = "response.in_progress" - """RESPONSE_IN_PROGRESS.""" - RESPONSE_FAILED = "response.failed" - """RESPONSE_FAILED.""" - RESPONSE_INCOMPLETE = "response.incomplete" - """RESPONSE_INCOMPLETE.""" - RESPONSE_OUTPUT_ITEM_ADDED = "response.output_item.added" - """RESPONSE_OUTPUT_ITEM_ADDED.""" - RESPONSE_OUTPUT_ITEM_DONE = "response.output_item.done" - """RESPONSE_OUTPUT_ITEM_DONE.""" - RESPONSE_REASONING_SUMMARY_PART_ADDED = "response.reasoning_summary_part.added" - """RESPONSE_REASONING_SUMMARY_PART_ADDED.""" - RESPONSE_REASONING_SUMMARY_PART_DONE = "response.reasoning_summary_part.done" - """RESPONSE_REASONING_SUMMARY_PART_DONE.""" - RESPONSE_REASONING_SUMMARY_TEXT_DELTA = "response.reasoning_summary_text.delta" - """RESPONSE_REASONING_SUMMARY_TEXT_DELTA.""" - RESPONSE_REASONING_SUMMARY_TEXT_DONE = "response.reasoning_summary_text.done" - """RESPONSE_REASONING_SUMMARY_TEXT_DONE.""" - RESPONSE_REASONING_TEXT_DELTA = "response.reasoning_text.delta" - """RESPONSE_REASONING_TEXT_DELTA.""" - RESPONSE_REASONING_TEXT_DONE = "response.reasoning_text.done" - """RESPONSE_REASONING_TEXT_DONE.""" - RESPONSE_REFUSAL_DELTA = "response.refusal.delta" - """RESPONSE_REFUSAL_DELTA.""" - RESPONSE_REFUSAL_DONE = "response.refusal.done" - """RESPONSE_REFUSAL_DONE.""" - RESPONSE_OUTPUT_TEXT_DELTA = "response.output_text.delta" - """RESPONSE_OUTPUT_TEXT_DELTA.""" - RESPONSE_OUTPUT_TEXT_DONE = "response.output_text.done" - """RESPONSE_OUTPUT_TEXT_DONE.""" - RESPONSE_WEB_SEARCH_CALL_COMPLETED = "response.web_search_call.completed" - """RESPONSE_WEB_SEARCH_CALL_COMPLETED.""" - RESPONSE_WEB_SEARCH_CALL_IN_PROGRESS = "response.web_search_call.in_progress" - """RESPONSE_WEB_SEARCH_CALL_IN_PROGRESS.""" - RESPONSE_WEB_SEARCH_CALL_SEARCHING = "response.web_search_call.searching" - """RESPONSE_WEB_SEARCH_CALL_SEARCHING.""" - RESPONSE_IMAGE_GENERATION_CALL_COMPLETED = "response.image_generation_call.completed" - """RESPONSE_IMAGE_GENERATION_CALL_COMPLETED.""" - RESPONSE_IMAGE_GENERATION_CALL_GENERATING = "response.image_generation_call.generating" - """RESPONSE_IMAGE_GENERATION_CALL_GENERATING.""" - RESPONSE_IMAGE_GENERATION_CALL_IN_PROGRESS = "response.image_generation_call.in_progress" - """RESPONSE_IMAGE_GENERATION_CALL_IN_PROGRESS.""" - RESPONSE_IMAGE_GENERATION_CALL_PARTIAL_IMAGE = "response.image_generation_call.partial_image" - """RESPONSE_IMAGE_GENERATION_CALL_PARTIAL_IMAGE.""" - RESPONSE_MCP_CALL_ARGUMENTS_DELTA = "response.mcp_call_arguments.delta" - """RESPONSE_MCP_CALL_ARGUMENTS_DELTA.""" - RESPONSE_MCP_CALL_ARGUMENTS_DONE = "response.mcp_call_arguments.done" - """RESPONSE_MCP_CALL_ARGUMENTS_DONE.""" - RESPONSE_MCP_CALL_COMPLETED = "response.mcp_call.completed" - """RESPONSE_MCP_CALL_COMPLETED.""" - RESPONSE_MCP_CALL_FAILED = "response.mcp_call.failed" - """RESPONSE_MCP_CALL_FAILED.""" - RESPONSE_MCP_CALL_IN_PROGRESS = "response.mcp_call.in_progress" - """RESPONSE_MCP_CALL_IN_PROGRESS.""" - RESPONSE_MCP_LIST_TOOLS_COMPLETED = "response.mcp_list_tools.completed" - """RESPONSE_MCP_LIST_TOOLS_COMPLETED.""" - RESPONSE_MCP_LIST_TOOLS_FAILED = "response.mcp_list_tools.failed" - """RESPONSE_MCP_LIST_TOOLS_FAILED.""" - RESPONSE_MCP_LIST_TOOLS_IN_PROGRESS = "response.mcp_list_tools.in_progress" - """RESPONSE_MCP_LIST_TOOLS_IN_PROGRESS.""" - RESPONSE_OUTPUT_TEXT_ANNOTATION_ADDED = "response.output_text.annotation.added" - """RESPONSE_OUTPUT_TEXT_ANNOTATION_ADDED.""" - RESPONSE_QUEUED = "response.queued" - """RESPONSE_QUEUED.""" - RESPONSE_CUSTOM_TOOL_CALL_INPUT_DELTA = "response.custom_tool_call_input.delta" - """RESPONSE_CUSTOM_TOOL_CALL_INPUT_DELTA.""" - RESPONSE_CUSTOM_TOOL_CALL_INPUT_DONE = "response.custom_tool_call_input.done" - """RESPONSE_CUSTOM_TOOL_CALL_INPUT_DONE.""" - - -class SearchContextSize(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of SearchContextSize.""" - - LOW = "low" - """LOW.""" - MEDIUM = "medium" - """MEDIUM.""" - HIGH = "high" - """HIGH.""" - - -class TextResponseFormatConfigurationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of TextResponseFormatConfigurationType.""" - - TEXT = "text" - """TEXT.""" - JSON_SCHEMA = "json_schema" - """JSON_SCHEMA.""" - JSON_OBJECT = "json_object" - """JSON_OBJECT.""" - - -class ToolCallStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The status of a tool call.""" - - IN_PROGRESS = "in_progress" - """IN_PROGRESS.""" - COMPLETED = "completed" - """COMPLETED.""" - INCOMPLETE = "incomplete" - """INCOMPLETE.""" - FAILED = "failed" - """FAILED.""" - - -class ToolChoiceOptions(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Tool choice mode.""" - - NONE = "none" - """NONE.""" - AUTO = "auto" - """AUTO.""" - REQUIRED = "required" - """REQUIRED.""" - - -class ToolChoiceParamType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of ToolChoiceParamType.""" - - ALLOWED_TOOLS = "allowed_tools" - """ALLOWED_TOOLS.""" - FUNCTION = "function" - """FUNCTION.""" - MCP = "mcp" - """MCP.""" - CUSTOM = "custom" - """CUSTOM.""" - APPLY_PATCH = "apply_patch" - """APPLY_PATCH.""" - SHELL = "shell" - """SHELL.""" - FILE_SEARCH = "file_search" - """FILE_SEARCH.""" - WEB_SEARCH_PREVIEW = "web_search_preview" - """WEB_SEARCH_PREVIEW.""" - COMPUTER_USE_PREVIEW = "computer_use_preview" - """COMPUTER_USE_PREVIEW.""" - WEB_SEARCH_PREVIEW2025_03_11 = "web_search_preview_2025_03_11" - """WEB_SEARCH_PREVIEW2025_03_11.""" - IMAGE_GENERATION = "image_generation" - """IMAGE_GENERATION.""" - CODE_INTERPRETER = "code_interpreter" - """CODE_INTERPRETER.""" - - -class ToolType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of ToolType.""" - - FUNCTION = "function" - """FUNCTION.""" - FILE_SEARCH = "file_search" - """FILE_SEARCH.""" - COMPUTER_USE_PREVIEW = "computer_use_preview" - """COMPUTER_USE_PREVIEW.""" - WEB_SEARCH = "web_search" - """WEB_SEARCH.""" - MCP = "mcp" - """MCP.""" - CODE_INTERPRETER = "code_interpreter" - """CODE_INTERPRETER.""" - IMAGE_GENERATION = "image_generation" - """IMAGE_GENERATION.""" - LOCAL_SHELL = "local_shell" - """LOCAL_SHELL.""" - SHELL = "shell" - """SHELL.""" - CUSTOM = "custom" - """CUSTOM.""" - WEB_SEARCH_PREVIEW = "web_search_preview" - """WEB_SEARCH_PREVIEW.""" - APPLY_PATCH = "apply_patch" - """APPLY_PATCH.""" - A2_A_PREVIEW = "a2a_preview" - """A2_A_PREVIEW.""" - BING_CUSTOM_SEARCH_PREVIEW = "bing_custom_search_preview" - """BING_CUSTOM_SEARCH_PREVIEW.""" - BROWSER_AUTOMATION_PREVIEW = "browser_automation_preview" - """BROWSER_AUTOMATION_PREVIEW.""" - FABRIC_DATAAGENT_PREVIEW = "fabric_dataagent_preview" - """FABRIC_DATAAGENT_PREVIEW.""" - SHAREPOINT_GROUNDING_PREVIEW = "sharepoint_grounding_preview" - """SHAREPOINT_GROUNDING_PREVIEW.""" - MEMORY_SEARCH_PREVIEW = "memory_search_preview" - """MEMORY_SEARCH_PREVIEW.""" - WORK_IQ_PREVIEW = "work_iq_preview" - """WORK_IQ_PREVIEW.""" - AZURE_AI_SEARCH = "azure_ai_search" - """AZURE_AI_SEARCH.""" - AZURE_FUNCTION = "azure_function" - """AZURE_FUNCTION.""" - BING_GROUNDING = "bing_grounding" - """BING_GROUNDING.""" - CAPTURE_STRUCTURED_OUTPUTS = "capture_structured_outputs" - """CAPTURE_STRUCTURED_OUTPUTS.""" - OPENAPI = "openapi" - """OPENAPI.""" diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/models/_models.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/models/_models.py deleted file mode 100644 index 7e15ca44d5eb..000000000000 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/models/_models.py +++ /dev/null @@ -1,17025 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# pylint: disable=useless-super-delegation - -import datetime -from typing import Any, Literal, Mapping, Optional, TYPE_CHECKING, Union, overload - -from .._utils.model_base import Model as _Model, rest_discriminator, rest_field -from ._enums import ( - AnnotationType, - ApplyPatchFileOperationType, - ApplyPatchOperationParamType, - ComputerActionType, - ContainerNetworkPolicyParamType, - ContainerSkillType, - CustomToolParamFormatType, - FunctionAndCustomToolCallOutputType, - FunctionShellCallEnvironmentType, - FunctionShellCallItemParamEnvironmentType, - FunctionShellCallOutputOutcomeParamType, - FunctionShellCallOutputOutcomeType, - FunctionShellToolParamEnvironmentType, - ItemFieldType, - ItemType, - MemoryItemKind, - MessageContentType, - OpenApiAuthType, - OutputContentType, - OutputItemType, - OutputMessageContentType, - ResponseStreamEventType, - TextResponseFormatConfigurationType, - ToolChoiceParamType, - ToolType, -) - -if TYPE_CHECKING: - from .. import _types, models as _models - - -class Tool(_Model): - """A tool that can be used to generate a response. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - A2APreviewTool, ApplyPatchToolParam, AzureAISearchTool, AzureFunctionTool, - BingCustomSearchPreviewTool, BingGroundingTool, BrowserAutomationPreviewTool, - CaptureStructuredOutputsTool, CodeInterpreterTool, ComputerUsePreviewTool, CustomToolParam, - MicrosoftFabricPreviewTool, FileSearchTool, FunctionTool, ImageGenTool, LocalShellToolParam, - MCPTool, MemorySearchPreviewTool, OpenApiTool, SharepointPreviewTool, FunctionShellToolParam, - WebSearchTool, WebSearchPreviewTool, WorkIQPreviewTool - - :ivar type: Required. Known values are: "function", "file_search", "computer_use_preview", - "web_search", "mcp", "code_interpreter", "image_generation", "local_shell", "shell", "custom", - "web_search_preview", "apply_patch", "a2a_preview", "bing_custom_search_preview", - "browser_automation_preview", "fabric_dataagent_preview", "sharepoint_grounding_preview", - "memory_search_preview", "work_iq_preview", "azure_ai_search", "azure_function", - "bing_grounding", "capture_structured_outputs", and "openapi". - :vartype type: str or ~azure.ai.agentserver.responses.models.models.ToolType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"function\", \"file_search\", \"computer_use_preview\", - \"web_search\", \"mcp\", \"code_interpreter\", \"image_generation\", \"local_shell\", - \"shell\", \"custom\", \"web_search_preview\", \"apply_patch\", \"a2a_preview\", - \"bing_custom_search_preview\", \"browser_automation_preview\", \"fabric_dataagent_preview\", - \"sharepoint_grounding_preview\", \"memory_search_preview\", \"work_iq_preview\", - \"azure_ai_search\", \"azure_function\", \"bing_grounding\", \"capture_structured_outputs\", - and \"openapi\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class A2APreviewTool(Tool, discriminator="a2a_preview"): - """An agent implementing the A2A protocol. - - :ivar type: The type of the tool. Always ``"a2a_preview``. Required. A2_A_PREVIEW. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.A2_A_PREVIEW - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar base_url: Base URL of the agent. - :vartype base_url: str - :ivar agent_card_path: The path to the agent card relative to the ``base_url``. If not - provided, defaults to ``/.well-known/agent-card.json``. - :vartype agent_card_path: str - :ivar project_connection_id: The connection ID in the project for the A2A server. The - connection stores authentication and other connection details needed to connect to the A2A - server. - :vartype project_connection_id: str - """ - - type: Literal[ToolType.A2_A_PREVIEW] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the tool. Always ``\"a2a_preview``. Required. A2_A_PREVIEW.""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - base_url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Base URL of the agent.""" - agent_card_path: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The path to the agent card relative to the ``base_url``. If not provided, defaults to - ``/.well-known/agent-card.json``.""" - project_connection_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The connection ID in the project for the A2A server. The connection stores authentication and - other connection details needed to connect to the A2A server.""" - - @overload - def __init__( - self, - *, - name: Optional[str] = None, - description: Optional[str] = None, - base_url: Optional[str] = None, - agent_card_path: Optional[str] = None, - project_connection_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.A2_A_PREVIEW # type: ignore - - -class OutputItem(_Model): - """OutputItem. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - A2AToolCall, A2AToolCallOutput, OutputItemApplyPatchToolCall, - OutputItemApplyPatchToolCallOutput, AzureAISearchToolCall, AzureAISearchToolCallOutput, - AzureFunctionToolCall, AzureFunctionToolCallOutput, BingCustomSearchToolCall, - BingCustomSearchToolCallOutput, BingGroundingToolCall, BingGroundingToolCallOutput, - BrowserAutomationToolCall, BrowserAutomationToolCallOutput, OutputItemCodeInterpreterToolCall, - OutputItemCompactionBody, OutputItemComputerToolCall, OutputItemComputerToolCallOutputResource, - OutputItemCustomToolCall, OutputItemCustomToolCallOutput, FabricDataAgentToolCall, - FabricDataAgentToolCallOutput, OutputItemFileSearchToolCall, OutputItemFunctionToolCall, - FunctionToolCallOutputResource, OutputItemImageGenToolCall, OutputItemLocalShellToolCall, - OutputItemLocalShellToolCallOutput, OutputItemMcpApprovalRequest, - OutputItemMcpApprovalResponseResource, OutputItemMcpToolCall, OutputItemMcpListTools, - MemorySearchToolCallItemResource, OutputItemMessage, OAuthConsentRequestOutputItem, - OpenApiToolCall, OpenApiToolCallOutput, OutputItemOutputMessage, OutputItemReasoningItem, - SharepointGroundingToolCall, SharepointGroundingToolCallOutput, OutputItemFunctionShellCall, - OutputItemFunctionShellCallOutput, StructuredOutputsOutputItem, OutputItemWebSearchToolCall, - WorkflowActionOutputItem - - :ivar type: Required. Known values are: "output_message", "file_search_call", "function_call", - "web_search_call", "computer_call", "reasoning", "compaction", "image_generation_call", - "code_interpreter_call", "local_shell_call", "shell_call", "shell_call_output", - "apply_patch_call", "apply_patch_call_output", "mcp_call", "mcp_list_tools", - "mcp_approval_request", "custom_tool_call", "message", "computer_call_output", - "function_call_output", "local_shell_call_output", "mcp_approval_response", - "custom_tool_call_output", "structured_outputs", "oauth_consent_request", "memory_search_call", - "workflow_action", "a2a_preview_call", "a2a_preview_call_output", "bing_grounding_call", - "bing_grounding_call_output", "sharepoint_grounding_preview_call", - "sharepoint_grounding_preview_call_output", "azure_ai_search_call", - "azure_ai_search_call_output", "bing_custom_search_preview_call", - "bing_custom_search_preview_call_output", "openapi_call", "openapi_call_output", - "browser_automation_preview_call", "browser_automation_preview_call_output", - "fabric_dataagent_preview_call", "fabric_dataagent_preview_call_output", "azure_function_call", - and "azure_function_call_output". - :vartype type: str or ~azure.ai.agentserver.responses.models.models.OutputItemType - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"output_message\", \"file_search_call\", \"function_call\", - \"web_search_call\", \"computer_call\", \"reasoning\", \"compaction\", - \"image_generation_call\", \"code_interpreter_call\", \"local_shell_call\", \"shell_call\", - \"shell_call_output\", \"apply_patch_call\", \"apply_patch_call_output\", \"mcp_call\", - \"mcp_list_tools\", \"mcp_approval_request\", \"custom_tool_call\", \"message\", - \"computer_call_output\", \"function_call_output\", \"local_shell_call_output\", - \"mcp_approval_response\", \"custom_tool_call_output\", \"structured_outputs\", - \"oauth_consent_request\", \"memory_search_call\", \"workflow_action\", \"a2a_preview_call\", - \"a2a_preview_call_output\", \"bing_grounding_call\", \"bing_grounding_call_output\", - \"sharepoint_grounding_preview_call\", \"sharepoint_grounding_preview_call_output\", - \"azure_ai_search_call\", \"azure_ai_search_call_output\", \"bing_custom_search_preview_call\", - \"bing_custom_search_preview_call_output\", \"openapi_call\", \"openapi_call_output\", - \"browser_automation_preview_call\", \"browser_automation_preview_call_output\", - \"fabric_dataagent_preview_call\", \"fabric_dataagent_preview_call_output\", - \"azure_function_call\", and \"azure_function_call_output\".""" - agent_reference: Optional["_models.AgentReference"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The agent that created the item.""" - response_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The response on which the item is created.""" - - @overload - def __init__( - self, - *, - type: str, - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class A2AToolCall(OutputItem, discriminator="a2a_preview_call"): - """An A2A (Agent-to-Agent) tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. A2_A_PREVIEW_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.A2_A_PREVIEW_CALL - :ivar call_id: The unique ID of the tool call generated by the model. Required. - :vartype call_id: str - :ivar name: The name of the A2A agent card being called. Required. - :vartype name: str - :ivar arguments: A JSON string of the arguments to pass to the tool. Required. - :vartype arguments: str - :ivar status: The status of the tool call. Required. Known values are: "in_progress", - "completed", "incomplete", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ToolCallStatus - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.A2_A_PREVIEW_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. A2_A_PREVIEW_CALL.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call generated by the model. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the A2A agent card being called. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of the arguments to pass to the tool. Required.""" - status: Union[str, "_models.ToolCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. Required. Known values are: \"in_progress\", \"completed\", - \"incomplete\", and \"failed\".""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - name: str, - arguments: str, - status: Union[str, "_models.ToolCallStatus"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.A2_A_PREVIEW_CALL # type: ignore - - -class A2AToolCallOutput(OutputItem, discriminator="a2a_preview_call_output"): - """The output of an A2A (Agent-to-Agent) tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. A2_A_PREVIEW_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.A2_A_PREVIEW_CALL_OUTPUT - :ivar call_id: The unique ID of the tool call generated by the model. Required. - :vartype call_id: str - :ivar name: The name of the A2A agent card that was called. Required. - :vartype name: str - :ivar output: The output from the A2A tool call. Is one of the following types: {str: Any}, - str, [Any] - :vartype output: dict[str, any] or str or list[any] - :ivar status: The status of the tool call. Required. Known values are: "in_progress", - "completed", "incomplete", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ToolCallStatus - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.A2_A_PREVIEW_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. A2_A_PREVIEW_CALL_OUTPUT.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call generated by the model. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the A2A agent card that was called. Required.""" - output: Optional["_types.ToolCallOutputContent"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The output from the A2A tool call. Is one of the following types: {str: Any}, str, [Any]""" - status: Union[str, "_models.ToolCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. Required. Known values are: \"in_progress\", \"completed\", - \"incomplete\", and \"failed\".""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - name: str, - status: Union[str, "_models.ToolCallStatus"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - output: Optional["_types.ToolCallOutputContent"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.A2_A_PREVIEW_CALL_OUTPUT # type: ignore - - -class AgentReference(_Model): - """AgentReference. - - :ivar type: Required. Default value is "agent_reference". - :vartype type: str - :ivar name: The name of the agent. Required. - :vartype name: str - :ivar version: The version identifier of the agent. - :vartype version: str - """ - - type: Literal["agent_reference"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required. Default value is \"agent_reference\".""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the agent. Required.""" - version: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The version identifier of the agent.""" - - @overload - def __init__( - self, - *, - name: str, - version: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["agent_reference"] = "agent_reference" - - -class AISearchIndexResource(_Model): - """A AI Search Index resource. - - :ivar project_connection_id: An index connection ID in an IndexResource attached to this agent. - :vartype project_connection_id: str - :ivar index_name: The name of an index in an IndexResource attached to this agent. - :vartype index_name: str - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar query_type: Type of query in an AIIndexResource attached to this agent. Known values are: - "simple", "semantic", "vector", "vector_simple_hybrid", and "vector_semantic_hybrid". - :vartype query_type: str or - ~azure.ai.agentserver.responses.models.models.AzureAISearchQueryType - :ivar top_k: Number of documents to retrieve from search and present to the model. - :vartype top_k: int - :ivar filter: filter string for search resource. `Learn more here - `_. - :vartype filter: str - :ivar index_asset_id: Index asset id for search resource. - :vartype index_asset_id: str - """ - - project_connection_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """An index connection ID in an IndexResource attached to this agent.""" - index_name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of an index in an IndexResource attached to this agent.""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - query_type: Optional[Union[str, "_models.AzureAISearchQueryType"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Type of query in an AIIndexResource attached to this agent. Known values are: \"simple\", - \"semantic\", \"vector\", \"vector_simple_hybrid\", and \"vector_semantic_hybrid\".""" - top_k: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Number of documents to retrieve from search and present to the model.""" - filter: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """filter string for search resource. `Learn more here - `_.""" - index_asset_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Index asset id for search resource.""" - - @overload - def __init__( - self, - *, - project_connection_id: Optional[str] = None, - index_name: Optional[str] = None, - name: Optional[str] = None, - description: Optional[str] = None, - query_type: Optional[Union[str, "_models.AzureAISearchQueryType"]] = None, - top_k: Optional[int] = None, - filter: Optional[str] = None, # pylint: disable=redefined-builtin - index_asset_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class Annotation(_Model): - """An annotation that applies to a span of output text. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ContainerFileCitationBody, FileCitationBody, FilePath, UrlCitationBody - - :ivar type: Required. Known values are: "file_citation", "url_citation", - "container_file_citation", and "file_path". - :vartype type: str or ~azure.ai.agentserver.responses.models.models.AnnotationType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"file_citation\", \"url_citation\", \"container_file_citation\", - and \"file_path\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ApiErrorResponse(_Model): - """Error response for API failures. - - :ivar error: Required. - :vartype error: ~azure.ai.agentserver.responses.models.models.Error - """ - - error: "_models.Error" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - error: "_models.Error", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ApplyPatchFileOperation(_Model): - """Apply patch operation. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ApplyPatchCreateFileOperation, ApplyPatchDeleteFileOperation, ApplyPatchUpdateFileOperation - - :ivar type: Required. Known values are: "create_file", "delete_file", and "update_file". - :vartype type: str or ~azure.ai.agentserver.responses.models.models.ApplyPatchFileOperationType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"create_file\", \"delete_file\", and \"update_file\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ApplyPatchCreateFileOperation(ApplyPatchFileOperation, discriminator="create_file"): - """Apply patch create file operation. - - :ivar type: Create a new file with the provided diff. Required. CREATE_FILE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CREATE_FILE - :ivar path: Path of the file to create. Required. - :vartype path: str - :ivar diff: Diff to apply. Required. - :vartype diff: str - """ - - type: Literal[ApplyPatchFileOperationType.CREATE_FILE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Create a new file with the provided diff. Required. CREATE_FILE.""" - path: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Path of the file to create. Required.""" - diff: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Diff to apply. Required.""" - - @overload - def __init__( - self, - *, - path: str, - diff: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ApplyPatchFileOperationType.CREATE_FILE # type: ignore - - -class ApplyPatchOperationParam(_Model): - """Apply patch operation. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ApplyPatchCreateFileOperationParam, ApplyPatchDeleteFileOperationParam, - ApplyPatchUpdateFileOperationParam - - :ivar type: Required. Known values are: "create_file", "delete_file", and "update_file". - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.ApplyPatchOperationParamType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"create_file\", \"delete_file\", and \"update_file\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ApplyPatchCreateFileOperationParam(ApplyPatchOperationParam, discriminator="create_file"): - """Apply patch create file operation. - - :ivar type: The operation type. Always ``create_file``. Required. CREATE_FILE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CREATE_FILE - :ivar path: Path of the file to create relative to the workspace root. Required. - :vartype path: str - :ivar diff: Unified diff content to apply when creating the file. Required. - :vartype diff: str - """ - - type: Literal[ApplyPatchOperationParamType.CREATE_FILE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The operation type. Always ``create_file``. Required. CREATE_FILE.""" - path: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Path of the file to create relative to the workspace root. Required.""" - diff: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Unified diff content to apply when creating the file. Required.""" - - @overload - def __init__( - self, - *, - path: str, - diff: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ApplyPatchOperationParamType.CREATE_FILE # type: ignore - - -class ApplyPatchDeleteFileOperation(ApplyPatchFileOperation, discriminator="delete_file"): - """Apply patch delete file operation. - - :ivar type: Delete the specified file. Required. DELETE_FILE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.DELETE_FILE - :ivar path: Path of the file to delete. Required. - :vartype path: str - """ - - type: Literal[ApplyPatchFileOperationType.DELETE_FILE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Delete the specified file. Required. DELETE_FILE.""" - path: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Path of the file to delete. Required.""" - - @overload - def __init__( - self, - *, - path: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ApplyPatchFileOperationType.DELETE_FILE # type: ignore - - -class ApplyPatchDeleteFileOperationParam(ApplyPatchOperationParam, discriminator="delete_file"): - """Apply patch delete file operation. - - :ivar type: The operation type. Always ``delete_file``. Required. DELETE_FILE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.DELETE_FILE - :ivar path: Path of the file to delete relative to the workspace root. Required. - :vartype path: str - """ - - type: Literal[ApplyPatchOperationParamType.DELETE_FILE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The operation type. Always ``delete_file``. Required. DELETE_FILE.""" - path: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Path of the file to delete relative to the workspace root. Required.""" - - @overload - def __init__( - self, - *, - path: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ApplyPatchOperationParamType.DELETE_FILE # type: ignore - - -class Item(_Model): - """Content item used to generate a response. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ApplyPatchToolCallItemParam, ApplyPatchToolCallOutputItemParam, ItemCodeInterpreterToolCall, - CompactionSummaryItemParam, ItemComputerToolCall, ComputerCallOutputItemParam, - ItemCustomToolCall, ItemCustomToolCallOutput, ItemFileSearchToolCall, ItemFunctionToolCall, - FunctionCallOutputItemParam, ItemImageGenToolCall, ItemReferenceParam, ItemLocalShellToolCall, - ItemLocalShellToolCallOutput, ItemMcpApprovalRequest, MCPApprovalResponse, ItemMcpToolCall, - ItemMcpListTools, MemorySearchToolCallItemParam, ItemMessage, ItemOutputMessage, - ItemReasoningItem, FunctionShellCallItemParam, FunctionShellCallOutputItemParam, - ItemWebSearchToolCall - - :ivar type: Required. Known values are: "message", "output_message", "file_search_call", - "computer_call", "computer_call_output", "web_search_call", "function_call", - "function_call_output", "reasoning", "compaction", "image_generation_call", - "code_interpreter_call", "local_shell_call", "local_shell_call_output", "shell_call", - "shell_call_output", "apply_patch_call", "apply_patch_call_output", "mcp_list_tools", - "mcp_approval_request", "mcp_approval_response", "mcp_call", "custom_tool_call_output", - "custom_tool_call", "item_reference", "structured_outputs", "oauth_consent_request", - "memory_search_call", "workflow_action", "a2a_preview_call", "a2a_preview_call_output", - "bing_grounding_call", "bing_grounding_call_output", "sharepoint_grounding_preview_call", - "sharepoint_grounding_preview_call_output", "azure_ai_search_call", - "azure_ai_search_call_output", "bing_custom_search_preview_call", - "bing_custom_search_preview_call_output", "openapi_call", "openapi_call_output", - "browser_automation_preview_call", "browser_automation_preview_call_output", - "fabric_dataagent_preview_call", "fabric_dataagent_preview_call_output", "azure_function_call", - and "azure_function_call_output". - :vartype type: str or ~azure.ai.agentserver.responses.models.models.ItemType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"message\", \"output_message\", \"file_search_call\", - \"computer_call\", \"computer_call_output\", \"web_search_call\", \"function_call\", - \"function_call_output\", \"reasoning\", \"compaction\", \"image_generation_call\", - \"code_interpreter_call\", \"local_shell_call\", \"local_shell_call_output\", \"shell_call\", - \"shell_call_output\", \"apply_patch_call\", \"apply_patch_call_output\", \"mcp_list_tools\", - \"mcp_approval_request\", \"mcp_approval_response\", \"mcp_call\", \"custom_tool_call_output\", - \"custom_tool_call\", \"item_reference\", \"structured_outputs\", \"oauth_consent_request\", - \"memory_search_call\", \"workflow_action\", \"a2a_preview_call\", \"a2a_preview_call_output\", - \"bing_grounding_call\", \"bing_grounding_call_output\", \"sharepoint_grounding_preview_call\", - \"sharepoint_grounding_preview_call_output\", \"azure_ai_search_call\", - \"azure_ai_search_call_output\", \"bing_custom_search_preview_call\", - \"bing_custom_search_preview_call_output\", \"openapi_call\", \"openapi_call_output\", - \"browser_automation_preview_call\", \"browser_automation_preview_call_output\", - \"fabric_dataagent_preview_call\", \"fabric_dataagent_preview_call_output\", - \"azure_function_call\", and \"azure_function_call_output\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ApplyPatchToolCallItemParam(Item, discriminator="apply_patch_call"): - """Apply patch tool call. - - :ivar type: The type of the item. Always ``apply_patch_call``. Required. APPLY_PATCH_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.APPLY_PATCH_CALL - :ivar id: - :vartype id: str - :ivar call_id: The unique ID of the apply patch tool call generated by the model. Required. - :vartype call_id: str - :ivar status: The status of the apply patch tool call. One of ``in_progress`` or ``completed``. - Required. Known values are: "in_progress" and "completed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ApplyPatchCallStatusParam - :ivar operation: The specific create, delete, or update instruction for the apply_patch tool - call. Required. - :vartype operation: ~azure.ai.agentserver.responses.models.models.ApplyPatchOperationParam - """ - - type: Literal[ItemType.APPLY_PATCH_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``apply_patch_call``. Required. APPLY_PATCH_CALL.""" - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the apply patch tool call generated by the model. Required.""" - status: Union[str, "_models.ApplyPatchCallStatusParam"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the apply patch tool call. One of ``in_progress`` or ``completed``. Required. - Known values are: \"in_progress\" and \"completed\".""" - operation: "_models.ApplyPatchOperationParam" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The specific create, delete, or update instruction for the apply_patch tool call. Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - status: Union[str, "_models.ApplyPatchCallStatusParam"], - operation: "_models.ApplyPatchOperationParam", - id: Optional[str] = None, # pylint: disable=redefined-builtin - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.APPLY_PATCH_CALL # type: ignore - - -class ApplyPatchToolCallOutputItemParam(Item, discriminator="apply_patch_call_output"): - """Apply patch tool call output. - - :ivar type: The type of the item. Always ``apply_patch_call_output``. Required. - APPLY_PATCH_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.APPLY_PATCH_CALL_OUTPUT - :ivar id: - :vartype id: str - :ivar call_id: The unique ID of the apply patch tool call generated by the model. Required. - :vartype call_id: str - :ivar status: The status of the apply patch tool call output. One of ``completed`` or - ``failed``. Required. Known values are: "completed" and "failed". - :vartype status: str or - ~azure.ai.agentserver.responses.models.models.ApplyPatchCallOutputStatusParam - :ivar output: - :vartype output: str - """ - - type: Literal[ItemType.APPLY_PATCH_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``apply_patch_call_output``. Required. APPLY_PATCH_CALL_OUTPUT.""" - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the apply patch tool call generated by the model. Required.""" - status: Union[str, "_models.ApplyPatchCallOutputStatusParam"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the apply patch tool call output. One of ``completed`` or ``failed``. Required. - Known values are: \"completed\" and \"failed\".""" - output: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - call_id: str, - status: Union[str, "_models.ApplyPatchCallOutputStatusParam"], - id: Optional[str] = None, # pylint: disable=redefined-builtin - output: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.APPLY_PATCH_CALL_OUTPUT # type: ignore - - -class ApplyPatchToolParam(Tool, discriminator="apply_patch"): - """Apply patch tool. - - :ivar type: The type of the tool. Always ``apply_patch``. Required. APPLY_PATCH. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.APPLY_PATCH - """ - - type: Literal[ToolType.APPLY_PATCH] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the tool. Always ``apply_patch``. Required. APPLY_PATCH.""" - - @overload - def __init__( - self, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.APPLY_PATCH # type: ignore - - -class ApplyPatchUpdateFileOperation(ApplyPatchFileOperation, discriminator="update_file"): - """Apply patch update file operation. - - :ivar type: Update an existing file with the provided diff. Required. UPDATE_FILE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.UPDATE_FILE - :ivar path: Path of the file to update. Required. - :vartype path: str - :ivar diff: Diff to apply. Required. - :vartype diff: str - """ - - type: Literal[ApplyPatchFileOperationType.UPDATE_FILE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Update an existing file with the provided diff. Required. UPDATE_FILE.""" - path: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Path of the file to update. Required.""" - diff: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Diff to apply. Required.""" - - @overload - def __init__( - self, - *, - path: str, - diff: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ApplyPatchFileOperationType.UPDATE_FILE # type: ignore - - -class ApplyPatchUpdateFileOperationParam(ApplyPatchOperationParam, discriminator="update_file"): - """Apply patch update file operation. - - :ivar type: The operation type. Always ``update_file``. Required. UPDATE_FILE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.UPDATE_FILE - :ivar path: Path of the file to update relative to the workspace root. Required. - :vartype path: str - :ivar diff: Unified diff content to apply to the existing file. Required. - :vartype diff: str - """ - - type: Literal[ApplyPatchOperationParamType.UPDATE_FILE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The operation type. Always ``update_file``. Required. UPDATE_FILE.""" - path: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Path of the file to update relative to the workspace root. Required.""" - diff: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Unified diff content to apply to the existing file. Required.""" - - @overload - def __init__( - self, - *, - path: str, - diff: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ApplyPatchOperationParamType.UPDATE_FILE # type: ignore - - -class ApproximateLocation(_Model): - """ApproximateLocation. - - :ivar type: The type of location approximation. Always ``approximate``. Required. Default value - is "approximate". - :vartype type: str - :ivar country: - :vartype country: str - :ivar region: - :vartype region: str - :ivar city: - :vartype city: str - :ivar timezone: - :vartype timezone: str - """ - - type: Literal["approximate"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The type of location approximation. Always ``approximate``. Required. Default value is - \"approximate\".""" - country: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - region: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - city: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - timezone: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - country: Optional[str] = None, - region: Optional[str] = None, - city: Optional[str] = None, - timezone: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["approximate"] = "approximate" - - -class AutoCodeInterpreterToolParam(_Model): - """Automatic Code Interpreter Tool Parameters. - - :ivar type: Always ``auto``. Required. Default value is "auto". - :vartype type: str - :ivar file_ids: An optional list of uploaded files to make available to your code. - :vartype file_ids: list[str] - :ivar memory_limit: Known values are: "1g", "4g", "16g", and "64g". - :vartype memory_limit: str or - ~azure.ai.agentserver.responses.models.models.ContainerMemoryLimit - :ivar network_policy: - :vartype network_policy: - ~azure.ai.agentserver.responses.models.models.ContainerNetworkPolicyParam - """ - - type: Literal["auto"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Always ``auto``. Required. Default value is \"auto\".""" - file_ids: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """An optional list of uploaded files to make available to your code.""" - memory_limit: Optional[Union[str, "_models.ContainerMemoryLimit"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Known values are: \"1g\", \"4g\", \"16g\", and \"64g\".""" - network_policy: Optional["_models.ContainerNetworkPolicyParam"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - - @overload - def __init__( - self, - *, - file_ids: Optional[list[str]] = None, - memory_limit: Optional[Union[str, "_models.ContainerMemoryLimit"]] = None, - network_policy: Optional["_models.ContainerNetworkPolicyParam"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["auto"] = "auto" - - -class AzureAISearchTool(Tool, discriminator="azure_ai_search"): - """The input definition information for an Azure AI search tool as used to configure an agent. - - :ivar type: The object type, which is always 'azure_ai_search'. Required. AZURE_AI_SEARCH. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.AZURE_AI_SEARCH - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar azure_ai_search: The azure ai search index resource. Required. - :vartype azure_ai_search: - ~azure.ai.agentserver.responses.models.models.AzureAISearchToolResource - """ - - type: Literal[ToolType.AZURE_AI_SEARCH] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'azure_ai_search'. Required. AZURE_AI_SEARCH.""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - azure_ai_search: "_models.AzureAISearchToolResource" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The azure ai search index resource. Required.""" - - @overload - def __init__( - self, - *, - azure_ai_search: "_models.AzureAISearchToolResource", - name: Optional[str] = None, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.AZURE_AI_SEARCH # type: ignore - - -class AzureAISearchToolCall(OutputItem, discriminator="azure_ai_search_call"): - """An Azure AI Search tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. AZURE_AI_SEARCH_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.AZURE_AI_SEARCH_CALL - :ivar call_id: The unique ID of the tool call generated by the model. Required. - :vartype call_id: str - :ivar arguments: A JSON string of the arguments to pass to the tool. Required. - :vartype arguments: str - :ivar status: The status of the tool call. Required. Known values are: "in_progress", - "completed", "incomplete", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ToolCallStatus - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.AZURE_AI_SEARCH_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. AZURE_AI_SEARCH_CALL.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call generated by the model. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of the arguments to pass to the tool. Required.""" - status: Union[str, "_models.ToolCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. Required. Known values are: \"in_progress\", \"completed\", - \"incomplete\", and \"failed\".""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - arguments: str, - status: Union[str, "_models.ToolCallStatus"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.AZURE_AI_SEARCH_CALL # type: ignore - - -class AzureAISearchToolCallOutput(OutputItem, discriminator="azure_ai_search_call_output"): - """The output of an Azure AI Search tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. AZURE_AI_SEARCH_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.AZURE_AI_SEARCH_CALL_OUTPUT - :ivar call_id: The unique ID of the tool call generated by the model. Required. - :vartype call_id: str - :ivar output: The output from the Azure AI Search tool call. Is one of the following types: - {str: Any}, str, [Any] - :vartype output: dict[str, any] or str or list[any] - :ivar status: The status of the tool call. Required. Known values are: "in_progress", - "completed", "incomplete", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ToolCallStatus - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.AZURE_AI_SEARCH_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. AZURE_AI_SEARCH_CALL_OUTPUT.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call generated by the model. Required.""" - output: Optional["_types.ToolCallOutputContent"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The output from the Azure AI Search tool call. Is one of the following types: {str: Any}, str, - [Any]""" - status: Union[str, "_models.ToolCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. Required. Known values are: \"in_progress\", \"completed\", - \"incomplete\", and \"failed\".""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - status: Union[str, "_models.ToolCallStatus"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - output: Optional["_types.ToolCallOutputContent"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.AZURE_AI_SEARCH_CALL_OUTPUT # type: ignore - - -class AzureAISearchToolResource(_Model): - """A set of index resources used by the ``azure_ai_search`` tool. - - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar indexes: The indices attached to this agent. There can be a maximum of 1 index resource - attached to the agent. Required. - :vartype indexes: list[~azure.ai.agentserver.responses.models.models.AISearchIndexResource] - """ - - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - indexes: list["_models.AISearchIndexResource"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The indices attached to this agent. There can be a maximum of 1 index resource attached to the - agent. Required.""" - - @overload - def __init__( - self, - *, - indexes: list["_models.AISearchIndexResource"], - name: Optional[str] = None, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class AzureFunctionBinding(_Model): - """The structure for keeping storage queue name and URI. - - :ivar type: The type of binding, which is always 'storage_queue'. Required. Default value is - "storage_queue". - :vartype type: str - :ivar storage_queue: Storage queue. Required. - :vartype storage_queue: ~azure.ai.agentserver.responses.models.models.AzureFunctionStorageQueue - """ - - type: Literal["storage_queue"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The type of binding, which is always 'storage_queue'. Required. Default value is - \"storage_queue\".""" - storage_queue: "_models.AzureFunctionStorageQueue" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Storage queue. Required.""" - - @overload - def __init__( - self, - *, - storage_queue: "_models.AzureFunctionStorageQueue", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["storage_queue"] = "storage_queue" - - -class AzureFunctionDefinition(_Model): - """The definition of Azure function. - - :ivar function: The definition of azure function and its parameters. Required. - :vartype function: - ~azure.ai.agentserver.responses.models.models.AzureFunctionDefinitionFunction - :ivar input_binding: Input storage queue. The queue storage trigger runs a function as messages - are added to it. Required. - :vartype input_binding: ~azure.ai.agentserver.responses.models.models.AzureFunctionBinding - :ivar output_binding: Output storage queue. The function writes output to this queue when the - input items are processed. Required. - :vartype output_binding: ~azure.ai.agentserver.responses.models.models.AzureFunctionBinding - """ - - function: "_models.AzureFunctionDefinitionFunction" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The definition of azure function and its parameters. Required.""" - input_binding: "_models.AzureFunctionBinding" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Input storage queue. The queue storage trigger runs a function as messages are added to it. - Required.""" - output_binding: "_models.AzureFunctionBinding" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Output storage queue. The function writes output to this queue when the input items are - processed. Required.""" - - @overload - def __init__( - self, - *, - function: "_models.AzureFunctionDefinitionFunction", - input_binding: "_models.AzureFunctionBinding", - output_binding: "_models.AzureFunctionBinding", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class AzureFunctionDefinitionFunction(_Model): - """AzureFunctionDefinitionFunction. - - :ivar name: The name of the function to be called. Required. - :vartype name: str - :ivar description: A description of what the function does, used by the model to choose when - and how to call the function. - :vartype description: str - :ivar parameters: The parameters the functions accepts, described as a JSON Schema object. - Required. - :vartype parameters: dict[str, any] - """ - - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the function to be called. Required.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A description of what the function does, used by the model to choose when and how to call the - function.""" - parameters: dict[str, Any] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The parameters the functions accepts, described as a JSON Schema object. Required.""" - - @overload - def __init__( - self, - *, - name: str, - parameters: dict[str, Any], - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class AzureFunctionStorageQueue(_Model): - """The structure for keeping storage queue name and URI. - - :ivar queue_service_endpoint: URI to the Azure Storage Queue service allowing you to manipulate - a queue. Required. - :vartype queue_service_endpoint: str - :ivar queue_name: The name of an Azure function storage queue. Required. - :vartype queue_name: str - """ - - queue_service_endpoint: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """URI to the Azure Storage Queue service allowing you to manipulate a queue. Required.""" - queue_name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of an Azure function storage queue. Required.""" - - @overload - def __init__( - self, - *, - queue_service_endpoint: str, - queue_name: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class AzureFunctionTool(Tool, discriminator="azure_function"): - """The input definition information for an Azure Function Tool, as used to configure an Agent. - - :ivar type: The object type, which is always 'browser_automation'. Required. AZURE_FUNCTION. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.AZURE_FUNCTION - :ivar azure_function: The Azure Function Tool definition. Required. - :vartype azure_function: ~azure.ai.agentserver.responses.models.models.AzureFunctionDefinition - """ - - type: Literal[ToolType.AZURE_FUNCTION] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'browser_automation'. Required. AZURE_FUNCTION.""" - azure_function: "_models.AzureFunctionDefinition" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The Azure Function Tool definition. Required.""" - - @overload - def __init__( - self, - *, - azure_function: "_models.AzureFunctionDefinition", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.AZURE_FUNCTION # type: ignore - - -class AzureFunctionToolCall(OutputItem, discriminator="azure_function_call"): - """An Azure Function tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. AZURE_FUNCTION_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.AZURE_FUNCTION_CALL - :ivar call_id: The unique ID of the tool call generated by the model. Required. - :vartype call_id: str - :ivar name: The name of the Azure Function being called. Required. - :vartype name: str - :ivar arguments: A JSON string of the arguments to pass to the tool. Required. - :vartype arguments: str - :ivar status: The status of the tool call. Required. Known values are: "in_progress", - "completed", "incomplete", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ToolCallStatus - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.AZURE_FUNCTION_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. AZURE_FUNCTION_CALL.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call generated by the model. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the Azure Function being called. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of the arguments to pass to the tool. Required.""" - status: Union[str, "_models.ToolCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. Required. Known values are: \"in_progress\", \"completed\", - \"incomplete\", and \"failed\".""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - name: str, - arguments: str, - status: Union[str, "_models.ToolCallStatus"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.AZURE_FUNCTION_CALL # type: ignore - - -class AzureFunctionToolCallOutput(OutputItem, discriminator="azure_function_call_output"): - """The output of an Azure Function tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. AZURE_FUNCTION_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.AZURE_FUNCTION_CALL_OUTPUT - :ivar call_id: The unique ID of the tool call generated by the model. Required. - :vartype call_id: str - :ivar name: The name of the Azure Function that was called. Required. - :vartype name: str - :ivar output: The output from the Azure Function tool call. Is one of the following types: - {str: Any}, str, [Any] - :vartype output: dict[str, any] or str or list[any] - :ivar status: The status of the tool call. Required. Known values are: "in_progress", - "completed", "incomplete", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ToolCallStatus - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.AZURE_FUNCTION_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. AZURE_FUNCTION_CALL_OUTPUT.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call generated by the model. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the Azure Function that was called. Required.""" - output: Optional["_types.ToolCallOutputContent"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The output from the Azure Function tool call. Is one of the following types: {str: Any}, str, - [Any]""" - status: Union[str, "_models.ToolCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. Required. Known values are: \"in_progress\", \"completed\", - \"incomplete\", and \"failed\".""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - name: str, - status: Union[str, "_models.ToolCallStatus"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - output: Optional["_types.ToolCallOutputContent"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.AZURE_FUNCTION_CALL_OUTPUT # type: ignore - - -class BingCustomSearchConfiguration(_Model): - """A bing custom search configuration. - - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar project_connection_id: Project connection id for grounding with bing search. Required. - :vartype project_connection_id: str - :ivar instance_name: Name of the custom configuration instance given to config. Required. - :vartype instance_name: str - :ivar market: The market where the results come from. - :vartype market: str - :ivar set_lang: The language to use for user interface strings when calling Bing API. - :vartype set_lang: str - :ivar count: The number of search results to return in the bing api response. - :vartype count: int - :ivar freshness: Filter search results by a specific time range. See `accepted values here - `_. - :vartype freshness: str - """ - - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - project_connection_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Project connection id for grounding with bing search. Required.""" - instance_name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Name of the custom configuration instance given to config. Required.""" - market: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The market where the results come from.""" - set_lang: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The language to use for user interface strings when calling Bing API.""" - count: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The number of search results to return in the bing api response.""" - freshness: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Filter search results by a specific time range. See `accepted values here - `_.""" - - @overload - def __init__( - self, - *, - project_connection_id: str, - instance_name: str, - name: Optional[str] = None, - description: Optional[str] = None, - market: Optional[str] = None, - set_lang: Optional[str] = None, - count: Optional[int] = None, - freshness: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class BingCustomSearchPreviewTool(Tool, discriminator="bing_custom_search_preview"): - """The input definition information for a Bing custom search tool as used to configure an agent. - - :ivar type: The object type, which is always 'bing_custom_search_preview'. Required. - BING_CUSTOM_SEARCH_PREVIEW. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.BING_CUSTOM_SEARCH_PREVIEW - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar bing_custom_search_preview: The bing custom search tool parameters. Required. - :vartype bing_custom_search_preview: - ~azure.ai.agentserver.responses.models.models.BingCustomSearchToolParameters - """ - - type: Literal[ToolType.BING_CUSTOM_SEARCH_PREVIEW] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'bing_custom_search_preview'. Required. - BING_CUSTOM_SEARCH_PREVIEW.""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - bing_custom_search_preview: "_models.BingCustomSearchToolParameters" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The bing custom search tool parameters. Required.""" - - @overload - def __init__( - self, - *, - bing_custom_search_preview: "_models.BingCustomSearchToolParameters", - name: Optional[str] = None, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.BING_CUSTOM_SEARCH_PREVIEW # type: ignore - - -class BingCustomSearchToolCall(OutputItem, discriminator="bing_custom_search_preview_call"): - """A Bing custom search tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. BING_CUSTOM_SEARCH_PREVIEW_CALL. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.BING_CUSTOM_SEARCH_PREVIEW_CALL - :ivar call_id: The unique ID of the tool call generated by the model. Required. - :vartype call_id: str - :ivar arguments: A JSON string of the arguments to pass to the tool. Required. - :vartype arguments: str - :ivar status: The status of the tool call. Required. Known values are: "in_progress", - "completed", "incomplete", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ToolCallStatus - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.BING_CUSTOM_SEARCH_PREVIEW_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. BING_CUSTOM_SEARCH_PREVIEW_CALL.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call generated by the model. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of the arguments to pass to the tool. Required.""" - status: Union[str, "_models.ToolCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. Required. Known values are: \"in_progress\", \"completed\", - \"incomplete\", and \"failed\".""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - arguments: str, - status: Union[str, "_models.ToolCallStatus"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.BING_CUSTOM_SEARCH_PREVIEW_CALL # type: ignore - - -class BingCustomSearchToolCallOutput(OutputItem, discriminator="bing_custom_search_preview_call_output"): - """The output of a Bing custom search tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. BING_CUSTOM_SEARCH_PREVIEW_CALL_OUTPUT. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.BING_CUSTOM_SEARCH_PREVIEW_CALL_OUTPUT - :ivar call_id: The unique ID of the tool call generated by the model. Required. - :vartype call_id: str - :ivar output: The output from the Bing custom search tool call. Is one of the following types: - {str: Any}, str, [Any] - :vartype output: dict[str, any] or str or list[any] - :ivar status: The status of the tool call. Required. Known values are: "in_progress", - "completed", "incomplete", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ToolCallStatus - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.BING_CUSTOM_SEARCH_PREVIEW_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. BING_CUSTOM_SEARCH_PREVIEW_CALL_OUTPUT.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call generated by the model. Required.""" - output: Optional["_types.ToolCallOutputContent"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The output from the Bing custom search tool call. Is one of the following types: {str: Any}, - str, [Any]""" - status: Union[str, "_models.ToolCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. Required. Known values are: \"in_progress\", \"completed\", - \"incomplete\", and \"failed\".""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - status: Union[str, "_models.ToolCallStatus"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - output: Optional["_types.ToolCallOutputContent"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.BING_CUSTOM_SEARCH_PREVIEW_CALL_OUTPUT # type: ignore - - -class BingCustomSearchToolParameters(_Model): - """The bing custom search tool parameters. - - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar search_configurations: The project connections attached to this tool. There can be a - maximum of 1 connection resource attached to the tool. Required. - :vartype search_configurations: - list[~azure.ai.agentserver.responses.models.models.BingCustomSearchConfiguration] - """ - - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - search_configurations: list["_models.BingCustomSearchConfiguration"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The project connections attached to this tool. There can be a maximum of 1 connection resource - attached to the tool. Required.""" - - @overload - def __init__( - self, - *, - search_configurations: list["_models.BingCustomSearchConfiguration"], - name: Optional[str] = None, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class BingGroundingSearchConfiguration(_Model): - """Search configuration for Bing Grounding. - - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar project_connection_id: Project connection id for grounding with bing search. Required. - :vartype project_connection_id: str - :ivar market: The market where the results come from. - :vartype market: str - :ivar set_lang: The language to use for user interface strings when calling Bing API. - :vartype set_lang: str - :ivar count: The number of search results to return in the bing api response. - :vartype count: int - :ivar freshness: Filter search results by a specific time range. See `accepted values here - `_. - :vartype freshness: str - """ - - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - project_connection_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Project connection id for grounding with bing search. Required.""" - market: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The market where the results come from.""" - set_lang: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The language to use for user interface strings when calling Bing API.""" - count: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The number of search results to return in the bing api response.""" - freshness: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Filter search results by a specific time range. See `accepted values here - `_.""" - - @overload - def __init__( - self, - *, - project_connection_id: str, - name: Optional[str] = None, - description: Optional[str] = None, - market: Optional[str] = None, - set_lang: Optional[str] = None, - count: Optional[int] = None, - freshness: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class BingGroundingSearchToolParameters(_Model): - """The bing grounding search tool parameters. - - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar search_configurations: The search configurations attached to this tool. There can be a - maximum of 1 search configuration resource attached to the tool. Required. - :vartype search_configurations: - list[~azure.ai.agentserver.responses.models.models.BingGroundingSearchConfiguration] - """ - - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - search_configurations: list["_models.BingGroundingSearchConfiguration"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The search configurations attached to this tool. There can be a maximum of 1 search - configuration resource attached to the tool. Required.""" - - @overload - def __init__( - self, - *, - search_configurations: list["_models.BingGroundingSearchConfiguration"], - name: Optional[str] = None, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class BingGroundingTool(Tool, discriminator="bing_grounding"): - """The input definition information for a bing grounding search tool as used to configure an - agent. - - :ivar type: The object type, which is always 'bing_grounding'. Required. BING_GROUNDING. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.BING_GROUNDING - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar bing_grounding: The bing grounding search tool parameters. Required. - :vartype bing_grounding: - ~azure.ai.agentserver.responses.models.models.BingGroundingSearchToolParameters - """ - - type: Literal[ToolType.BING_GROUNDING] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'bing_grounding'. Required. BING_GROUNDING.""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - bing_grounding: "_models.BingGroundingSearchToolParameters" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The bing grounding search tool parameters. Required.""" - - @overload - def __init__( - self, - *, - bing_grounding: "_models.BingGroundingSearchToolParameters", - name: Optional[str] = None, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.BING_GROUNDING # type: ignore - - -class BingGroundingToolCall(OutputItem, discriminator="bing_grounding_call"): - """A Bing grounding tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. BING_GROUNDING_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.BING_GROUNDING_CALL - :ivar call_id: The unique ID of the tool call generated by the model. Required. - :vartype call_id: str - :ivar arguments: A JSON string of the arguments to pass to the tool. Required. - :vartype arguments: str - :ivar status: The status of the tool call. Required. Known values are: "in_progress", - "completed", "incomplete", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ToolCallStatus - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.BING_GROUNDING_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. BING_GROUNDING_CALL.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call generated by the model. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of the arguments to pass to the tool. Required.""" - status: Union[str, "_models.ToolCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. Required. Known values are: \"in_progress\", \"completed\", - \"incomplete\", and \"failed\".""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - arguments: str, - status: Union[str, "_models.ToolCallStatus"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.BING_GROUNDING_CALL # type: ignore - - -class BingGroundingToolCallOutput(OutputItem, discriminator="bing_grounding_call_output"): - """The output of a Bing grounding tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. BING_GROUNDING_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.BING_GROUNDING_CALL_OUTPUT - :ivar call_id: The unique ID of the tool call generated by the model. Required. - :vartype call_id: str - :ivar output: The output from the Bing grounding tool call. Is one of the following types: - {str: Any}, str, [Any] - :vartype output: dict[str, any] or str or list[any] - :ivar status: The status of the tool call. Required. Known values are: "in_progress", - "completed", "incomplete", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ToolCallStatus - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.BING_GROUNDING_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. BING_GROUNDING_CALL_OUTPUT.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call generated by the model. Required.""" - output: Optional["_types.ToolCallOutputContent"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The output from the Bing grounding tool call. Is one of the following types: {str: Any}, str, - [Any]""" - status: Union[str, "_models.ToolCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. Required. Known values are: \"in_progress\", \"completed\", - \"incomplete\", and \"failed\".""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - status: Union[str, "_models.ToolCallStatus"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - output: Optional["_types.ToolCallOutputContent"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.BING_GROUNDING_CALL_OUTPUT # type: ignore - - -class BrowserAutomationPreviewTool(Tool, discriminator="browser_automation_preview"): - """The input definition information for a Browser Automation Tool, as used to configure an Agent. - - :ivar type: The object type, which is always 'browser_automation_preview'. Required. - BROWSER_AUTOMATION_PREVIEW. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.BROWSER_AUTOMATION_PREVIEW - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar browser_automation_preview: The Browser Automation Tool parameters. Required. - :vartype browser_automation_preview: - ~azure.ai.agentserver.responses.models.models.BrowserAutomationToolParameters - """ - - type: Literal[ToolType.BROWSER_AUTOMATION_PREVIEW] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'browser_automation_preview'. Required. - BROWSER_AUTOMATION_PREVIEW.""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - browser_automation_preview: "_models.BrowserAutomationToolParameters" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The Browser Automation Tool parameters. Required.""" - - @overload - def __init__( - self, - *, - browser_automation_preview: "_models.BrowserAutomationToolParameters", - name: Optional[str] = None, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.BROWSER_AUTOMATION_PREVIEW # type: ignore - - -class BrowserAutomationToolCall(OutputItem, discriminator="browser_automation_preview_call"): - """A browser automation tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. BROWSER_AUTOMATION_PREVIEW_CALL. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.BROWSER_AUTOMATION_PREVIEW_CALL - :ivar call_id: The unique ID of the tool call generated by the model. Required. - :vartype call_id: str - :ivar arguments: A JSON string of the arguments to pass to the tool. Required. - :vartype arguments: str - :ivar status: The status of the tool call. Required. Known values are: "in_progress", - "completed", "incomplete", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ToolCallStatus - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.BROWSER_AUTOMATION_PREVIEW_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. BROWSER_AUTOMATION_PREVIEW_CALL.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call generated by the model. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of the arguments to pass to the tool. Required.""" - status: Union[str, "_models.ToolCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. Required. Known values are: \"in_progress\", \"completed\", - \"incomplete\", and \"failed\".""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - arguments: str, - status: Union[str, "_models.ToolCallStatus"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.BROWSER_AUTOMATION_PREVIEW_CALL # type: ignore - - -class BrowserAutomationToolCallOutput(OutputItem, discriminator="browser_automation_preview_call_output"): - """The output of a browser automation tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. BROWSER_AUTOMATION_PREVIEW_CALL_OUTPUT. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.BROWSER_AUTOMATION_PREVIEW_CALL_OUTPUT - :ivar call_id: The unique ID of the tool call generated by the model. Required. - :vartype call_id: str - :ivar output: The output from the browser automation tool call. Is one of the following types: - {str: Any}, str, [Any] - :vartype output: dict[str, any] or str or list[any] - :ivar status: The status of the tool call. Required. Known values are: "in_progress", - "completed", "incomplete", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ToolCallStatus - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.BROWSER_AUTOMATION_PREVIEW_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. BROWSER_AUTOMATION_PREVIEW_CALL_OUTPUT.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call generated by the model. Required.""" - output: Optional["_types.ToolCallOutputContent"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The output from the browser automation tool call. Is one of the following types: {str: Any}, - str, [Any]""" - status: Union[str, "_models.ToolCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. Required. Known values are: \"in_progress\", \"completed\", - \"incomplete\", and \"failed\".""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - status: Union[str, "_models.ToolCallStatus"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - output: Optional["_types.ToolCallOutputContent"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.BROWSER_AUTOMATION_PREVIEW_CALL_OUTPUT # type: ignore - - -class BrowserAutomationToolConnectionParameters(_Model): # pylint: disable=name-too-long - """Definition of input parameters for the connection used by the Browser Automation Tool. - - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar project_connection_id: The ID of the project connection to your Azure Playwright - resource. Required. - :vartype project_connection_id: str - """ - - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - project_connection_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the project connection to your Azure Playwright resource. Required.""" - - @overload - def __init__( - self, - *, - project_connection_id: str, - name: Optional[str] = None, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class BrowserAutomationToolParameters(_Model): - """Definition of input parameters for the Browser Automation Tool. - - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar connection: The project connection parameters associated with the Browser Automation - Tool. Required. - :vartype connection: - ~azure.ai.agentserver.responses.models.models.BrowserAutomationToolConnectionParameters - """ - - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - connection: "_models.BrowserAutomationToolConnectionParameters" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The project connection parameters associated with the Browser Automation Tool. Required.""" - - @overload - def __init__( - self, - *, - connection: "_models.BrowserAutomationToolConnectionParameters", - name: Optional[str] = None, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class CaptureStructuredOutputsTool(Tool, discriminator="capture_structured_outputs"): - """A tool for capturing structured outputs. - - :ivar type: The type of the tool. Always ``capture_structured_outputs``. Required. - CAPTURE_STRUCTURED_OUTPUTS. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CAPTURE_STRUCTURED_OUTPUTS - :ivar outputs: The structured outputs to capture from the model. Required. - :vartype outputs: ~azure.ai.agentserver.responses.models.models.StructuredOutputDefinition - """ - - type: Literal[ToolType.CAPTURE_STRUCTURED_OUTPUTS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the tool. Always ``capture_structured_outputs``. Required. - CAPTURE_STRUCTURED_OUTPUTS.""" - outputs: "_models.StructuredOutputDefinition" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The structured outputs to capture from the model. Required.""" - - @overload - def __init__( - self, - *, - outputs: "_models.StructuredOutputDefinition", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.CAPTURE_STRUCTURED_OUTPUTS # type: ignore - - -class MemoryItem(_Model): - """A single memory item stored in the memory store, containing content and metadata. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ChatSummaryMemoryItem, UserProfileMemoryItem - - :ivar memory_id: The unique ID of the memory item. Required. - :vartype memory_id: str - :ivar updated_at: The last update time of the memory item. Required. - :vartype updated_at: ~datetime.datetime - :ivar scope: The namespace that logically groups and isolates memories, such as a user ID. - Required. - :vartype scope: str - :ivar content: The content of the memory. Required. - :vartype content: str - :ivar kind: The kind of the memory item. Required. Known values are: "user_profile" and - "chat_summary". - :vartype kind: str or ~azure.ai.agentserver.responses.models.models.MemoryItemKind - """ - - __mapping__: dict[str, _Model] = {} - memory_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the memory item. Required.""" - updated_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The last update time of the memory item. Required.""" - scope: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The namespace that logically groups and isolates memories, such as a user ID. Required.""" - content: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The content of the memory. Required.""" - kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) - """The kind of the memory item. Required. Known values are: \"user_profile\" and \"chat_summary\".""" - - @overload - def __init__( - self, - *, - memory_id: str, - updated_at: datetime.datetime, - scope: str, - content: str, - kind: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ChatSummaryMemoryItem(MemoryItem, discriminator="chat_summary"): - """A memory item containing a summary extracted from conversations. - - :ivar memory_id: The unique ID of the memory item. Required. - :vartype memory_id: str - :ivar updated_at: The last update time of the memory item. Required. - :vartype updated_at: ~datetime.datetime - :ivar scope: The namespace that logically groups and isolates memories, such as a user ID. - Required. - :vartype scope: str - :ivar content: The content of the memory. Required. - :vartype content: str - :ivar kind: The kind of the memory item. Required. Summary of chat conversations. - :vartype kind: str or ~azure.ai.agentserver.responses.models.models.CHAT_SUMMARY - """ - - kind: Literal[MemoryItemKind.CHAT_SUMMARY] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The kind of the memory item. Required. Summary of chat conversations.""" - - @overload - def __init__( - self, - *, - memory_id: str, - updated_at: datetime.datetime, - scope: str, - content: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.kind = MemoryItemKind.CHAT_SUMMARY # type: ignore - - -class ComputerAction(_Model): - """ComputerAction. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ClickParam, DoubleClickAction, DragParam, KeyPressAction, MoveParam, ScreenshotParam, - ScrollParam, TypeParam, WaitParam - - :ivar type: Required. Known values are: "click", "double_click", "drag", "keypress", "move", - "screenshot", "scroll", "type", and "wait". - :vartype type: str or ~azure.ai.agentserver.responses.models.models.ComputerActionType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"click\", \"double_click\", \"drag\", \"keypress\", \"move\", - \"screenshot\", \"scroll\", \"type\", and \"wait\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ClickParam(ComputerAction, discriminator="click"): - """Click. - - :ivar type: Specifies the event type. For a click action, this property is always ``click``. - Required. CLICK. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CLICK - :ivar button: Indicates which mouse button was pressed during the click. One of ``left``, - ``right``, ``wheel``, ``back``, or ``forward``. Required. Known values are: "left", "right", - "wheel", "back", and "forward". - :vartype button: str or ~azure.ai.agentserver.responses.models.models.ClickButtonType - :ivar x: The x-coordinate where the click occurred. Required. - :vartype x: int - :ivar y: The y-coordinate where the click occurred. Required. - :vartype y: int - """ - - type: Literal[ComputerActionType.CLICK] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Specifies the event type. For a click action, this property is always ``click``. Required. - CLICK.""" - button: Union[str, "_models.ClickButtonType"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Indicates which mouse button was pressed during the click. One of ``left``, ``right``, - ``wheel``, ``back``, or ``forward``. Required. Known values are: \"left\", \"right\", - \"wheel\", \"back\", and \"forward\".""" - x: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The x-coordinate where the click occurred. Required.""" - y: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The y-coordinate where the click occurred. Required.""" - - @overload - def __init__( - self, - *, - button: Union[str, "_models.ClickButtonType"], - x: int, - y: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ComputerActionType.CLICK # type: ignore - - -class CodeInterpreterOutputImage(_Model): - """Code interpreter output image. - - :ivar type: The type of the output. Always ``image``. Required. Default value is "image". - :vartype type: str - :ivar url: The URL of the image output from the code interpreter. Required. - :vartype url: str - """ - - type: Literal["image"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The type of the output. Always ``image``. Required. Default value is \"image\".""" - url: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The URL of the image output from the code interpreter. Required.""" - - @overload - def __init__( - self, - *, - url: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["image"] = "image" - - -class CodeInterpreterOutputLogs(_Model): - """Code interpreter output logs. - - :ivar type: The type of the output. Always ``logs``. Required. Default value is "logs". - :vartype type: str - :ivar logs: The logs output from the code interpreter. Required. - :vartype logs: str - """ - - type: Literal["logs"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The type of the output. Always ``logs``. Required. Default value is \"logs\".""" - logs: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The logs output from the code interpreter. Required.""" - - @overload - def __init__( - self, - *, - logs: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["logs"] = "logs" - - -class CodeInterpreterTool(Tool, discriminator="code_interpreter"): - """Code interpreter. - - :ivar type: The type of the code interpreter tool. Always ``code_interpreter``. Required. - CODE_INTERPRETER. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CODE_INTERPRETER - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar container: The code interpreter container. Can be a container ID or an object that - specifies uploaded file IDs to make available to your code, along with an optional - ``memory_limit`` setting. If not provided, the service assumes auto. Is either a str type or a - AutoCodeInterpreterToolParam type. - :vartype container: str or - ~azure.ai.agentserver.responses.models.models.AutoCodeInterpreterToolParam - """ - - type: Literal[ToolType.CODE_INTERPRETER] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the code interpreter tool. Always ``code_interpreter``. Required. CODE_INTERPRETER.""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - container: Optional[Union[str, "_models.AutoCodeInterpreterToolParam"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The code interpreter container. Can be a container ID or an object that specifies uploaded file - IDs to make available to your code, along with an optional ``memory_limit`` setting. If not - provided, the service assumes auto. Is either a str type or a AutoCodeInterpreterToolParam - type.""" - - @overload - def __init__( - self, - *, - name: Optional[str] = None, - description: Optional[str] = None, - container: Optional[Union[str, "_models.AutoCodeInterpreterToolParam"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.CODE_INTERPRETER # type: ignore - - -class CompactionSummaryItemParam(Item, discriminator="compaction"): - """Compaction item. - - :ivar id: - :vartype id: str - :ivar type: The type of the item. Always ``compaction``. Required. COMPACTION. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.COMPACTION - :ivar encrypted_content: The encrypted content of the compaction summary. Required. - :vartype encrypted_content: str - """ - - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - type: Literal[ItemType.COMPACTION] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``compaction``. Required. COMPACTION.""" - encrypted_content: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The encrypted content of the compaction summary. Required.""" - - @overload - def __init__( - self, - *, - encrypted_content: str, - id: Optional[str] = None, # pylint: disable=redefined-builtin - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.COMPACTION # type: ignore - - -class CompactResource(_Model): - """The compacted response object. - - :ivar id: The unique identifier for the compacted response. Required. - :vartype id: str - :ivar object: The object type. Always ``response.compaction``. Required. Default value is - "response.compaction". - :vartype object: str - :ivar output: The compacted list of output items. Required. - :vartype output: list[~azure.ai.agentserver.responses.models.models.ItemField] - :ivar created_at: Unix timestamp (in seconds) when the compacted conversation was created. - Required. - :vartype created_at: ~datetime.datetime - :ivar usage: Token accounting for the compaction pass, including cached, reasoning, and total - tokens. Required. - :vartype usage: ~azure.ai.agentserver.responses.models.models.ResponseUsage - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique identifier for the compacted response. Required.""" - object: Literal["response.compaction"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type. Always ``response.compaction``. Required. Default value is - \"response.compaction\".""" - output: list["_models.ItemField"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The compacted list of output items. Required.""" - created_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """Unix timestamp (in seconds) when the compacted conversation was created. Required.""" - usage: "_models.ResponseUsage" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Token accounting for the compaction pass, including cached, reasoning, and total tokens. - Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - output: list["_models.ItemField"], - created_at: datetime.datetime, - usage: "_models.ResponseUsage", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.object: Literal["response.compaction"] = "response.compaction" - - -class ComparisonFilter(_Model): - """Comparison Filter. - - :ivar type: Specifies the comparison operator: ``eq``, ``ne``, ``gt``, ``gte``, ``lt``, - ``lte``, ``in``, ``nin``. - - * `eq`: equals - * `ne`: not equal - * `gt`: greater than - * `gte`: greater than or equal - * `lt`: less than - * `lte`: less than or equal - * `in`: in - * `nin`: not in. Required. Is one of the following types: Literal["eq"], Literal["ne"], - Literal["gt"], Literal["gte"], Literal["lt"], Literal["lte"] - :vartype type: str or str or str or str or str or str - :ivar key: The key to compare against the value. Required. - :vartype key: str - :ivar value: The value to compare against the attribute key; supports string, number, or - boolean types. Required. Is one of the following types: str, int, bool, [Union[str, int]] - :vartype value: str or int or bool or list[str or int] - """ - - type: Literal["eq", "ne", "gt", "gte", "lt", "lte"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Specifies the comparison operator: ``eq``, ``ne``, ``gt``, ``gte``, ``lt``, ``lte``, ``in``, - ``nin``. - - * `eq`: equals - * `ne`: not equal - * `gt`: greater than - * `gte`: greater than or equal - * `lt`: less than - * `lte`: less than or equal - * `in`: in - * `nin`: not in. Required. Is one of the following types: Literal[\"eq\"], - Literal[\"ne\"], Literal[\"gt\"], Literal[\"gte\"], Literal[\"lt\"], Literal[\"lte\"]""" - key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The key to compare against the value. Required.""" - value: Union[str, int, bool, list[Union[str, int]]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The value to compare against the attribute key; supports string, number, or boolean types. - Required. Is one of the following types: str, int, bool, [Union[str, int]]""" - - @overload - def __init__( - self, - *, - type: Literal["eq", "ne", "gt", "gte", "lt", "lte"], - key: str, - value: Union[str, int, bool, list[Union[str, int]]], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class CompoundFilter(_Model): - """Compound Filter. - - :ivar type: Type of operation: ``and`` or ``or``. Required. Is either a Literal["and"] type or - a Literal["or"] type. - :vartype type: str or str - :ivar filters: Array of filters to combine. Items can be ``ComparisonFilter`` or - ``CompoundFilter``. Required. - :vartype filters: list[~azure.ai.agentserver.responses.models.models.ComparisonFilter or any] - """ - - type: Literal["and", "or"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Type of operation: ``and`` or ``or``. Required. Is either a Literal[\"and\"] type or a - Literal[\"or\"] type.""" - filters: list[Union["_models.ComparisonFilter", Any]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Array of filters to combine. Items can be ``ComparisonFilter`` or ``CompoundFilter``. Required.""" - - @overload - def __init__( - self, - *, - type: Literal["and", "or"], - filters: list[Union["_models.ComparisonFilter", Any]], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ComputerCallOutputItemParam(Item, discriminator="computer_call_output"): - """Computer tool call output. - - :ivar id: - :vartype id: str - :ivar call_id: The ID of the computer tool call that produced the output. Required. - :vartype call_id: str - :ivar type: The type of the computer tool call output. Always ``computer_call_output``. - Required. COMPUTER_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.COMPUTER_CALL_OUTPUT - :ivar output: Required. - :vartype output: ~azure.ai.agentserver.responses.models.models.ComputerScreenshotImage - :ivar acknowledged_safety_checks: - :vartype acknowledged_safety_checks: - list[~azure.ai.agentserver.responses.models.models.ComputerCallSafetyCheckParam] - :ivar status: Known values are: "in_progress", "completed", and "incomplete". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.FunctionCallItemStatus - """ - - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the computer tool call that produced the output. Required.""" - type: Literal[ItemType.COMPUTER_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the computer tool call output. Always ``computer_call_output``. Required. - COMPUTER_CALL_OUTPUT.""" - output: "_models.ComputerScreenshotImage" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - acknowledged_safety_checks: Optional[list["_models.ComputerCallSafetyCheckParam"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - status: Optional[Union[str, "_models.FunctionCallItemStatus"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Known values are: \"in_progress\", \"completed\", and \"incomplete\".""" - - @overload - def __init__( - self, - *, - call_id: str, - output: "_models.ComputerScreenshotImage", - id: Optional[str] = None, # pylint: disable=redefined-builtin - acknowledged_safety_checks: Optional[list["_models.ComputerCallSafetyCheckParam"]] = None, - status: Optional[Union[str, "_models.FunctionCallItemStatus"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.COMPUTER_CALL_OUTPUT # type: ignore - - -class ComputerCallSafetyCheckParam(_Model): - """A pending safety check for the computer call. - - :ivar id: The ID of the pending safety check. Required. - :vartype id: str - :ivar code: - :vartype code: str - :ivar message: - :vartype message: str - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the pending safety check. Required.""" - code: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - code: Optional[str] = None, - message: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class MessageContent(_Model): - """A content part that makes up an input or output item. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ComputerScreenshotContent, MessageContentInputFileContent, MessageContentInputImageContent, - MessageContentInputTextContent, MessageContentOutputTextContent, - MessageContentReasoningTextContent, MessageContentRefusalContent, SummaryTextContent, - TextContent - - :ivar type: Required. Known values are: "input_text", "output_text", "text", "summary_text", - "reasoning_text", "refusal", "input_image", "computer_screenshot", and "input_file". - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MessageContentType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"input_text\", \"output_text\", \"text\", \"summary_text\", - \"reasoning_text\", \"refusal\", \"input_image\", \"computer_screenshot\", and \"input_file\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ComputerScreenshotContent(MessageContent, discriminator="computer_screenshot"): - """Computer screenshot. - - :ivar type: Specifies the event type. For a computer screenshot, this property is always set to - ``computer_screenshot``. Required. COMPUTER_SCREENSHOT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.COMPUTER_SCREENSHOT - :ivar image_url: Required. - :vartype image_url: str - :ivar file_id: Required. - :vartype file_id: str - """ - - type: Literal[MessageContentType.COMPUTER_SCREENSHOT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Specifies the event type. For a computer screenshot, this property is always set to - ``computer_screenshot``. Required. COMPUTER_SCREENSHOT.""" - image_url: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - file_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - image_url: str, - file_id: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = MessageContentType.COMPUTER_SCREENSHOT # type: ignore - - -class ComputerScreenshotImage(_Model): - """A computer screenshot image used with the computer use tool. - - :ivar type: Specifies the event type. For a computer screenshot, this property is always set to - ``computer_screenshot``. Required. Default value is "computer_screenshot". - :vartype type: str - :ivar image_url: The URL of the screenshot image. - :vartype image_url: str - :ivar file_id: The identifier of an uploaded file that contains the screenshot. - :vartype file_id: str - """ - - type: Literal["computer_screenshot"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Specifies the event type. For a computer screenshot, this property is always set to - ``computer_screenshot``. Required. Default value is \"computer_screenshot\".""" - image_url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The URL of the screenshot image.""" - file_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The identifier of an uploaded file that contains the screenshot.""" - - @overload - def __init__( - self, - *, - image_url: Optional[str] = None, - file_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["computer_screenshot"] = "computer_screenshot" - - -class ComputerUsePreviewTool(Tool, discriminator="computer_use_preview"): - """Computer use preview. - - :ivar type: The type of the computer use tool. Always ``computer_use_preview``. Required. - COMPUTER_USE_PREVIEW. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.COMPUTER_USE_PREVIEW - :ivar environment: The type of computer environment to control. Required. Known values are: - "windows", "mac", "linux", "ubuntu", and "browser". - :vartype environment: str or ~azure.ai.agentserver.responses.models.models.ComputerEnvironment - :ivar display_width: The width of the computer display. Required. - :vartype display_width: int - :ivar display_height: The height of the computer display. Required. - :vartype display_height: int - """ - - type: Literal[ToolType.COMPUTER_USE_PREVIEW] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the computer use tool. Always ``computer_use_preview``. Required. - COMPUTER_USE_PREVIEW.""" - environment: Union[str, "_models.ComputerEnvironment"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The type of computer environment to control. Required. Known values are: \"windows\", \"mac\", - \"linux\", \"ubuntu\", and \"browser\".""" - display_width: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The width of the computer display. Required.""" - display_height: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The height of the computer display. Required.""" - - @overload - def __init__( - self, - *, - environment: Union[str, "_models.ComputerEnvironment"], - display_width: int, - display_height: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.COMPUTER_USE_PREVIEW # type: ignore - - -class FunctionShellToolParamEnvironment(_Model): - """FunctionShellToolParamEnvironment. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ContainerAutoParam, FunctionShellToolParamEnvironmentContainerReferenceParam, - FunctionShellToolParamEnvironmentLocalEnvironmentParam - - :ivar type: Required. Known values are: "container_auto", "local", and "container_reference". - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.FunctionShellToolParamEnvironmentType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"container_auto\", \"local\", and \"container_reference\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ContainerAutoParam(FunctionShellToolParamEnvironment, discriminator="container_auto"): - """ContainerAutoParam. - - :ivar type: Automatically creates a container for this request. Required. CONTAINER_AUTO. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CONTAINER_AUTO - :ivar file_ids: An optional list of uploaded files to make available to your code. - :vartype file_ids: list[str] - :ivar memory_limit: Known values are: "1g", "4g", "16g", and "64g". - :vartype memory_limit: str or - ~azure.ai.agentserver.responses.models.models.ContainerMemoryLimit - :ivar skills: An optional list of skills referenced by id or inline data. - :vartype skills: list[~azure.ai.agentserver.responses.models.models.ContainerSkill] - :ivar network_policy: - :vartype network_policy: - ~azure.ai.agentserver.responses.models.models.ContainerNetworkPolicyParam - """ - - type: Literal[FunctionShellToolParamEnvironmentType.CONTAINER_AUTO] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Automatically creates a container for this request. Required. CONTAINER_AUTO.""" - file_ids: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """An optional list of uploaded files to make available to your code.""" - memory_limit: Optional[Union[str, "_models.ContainerMemoryLimit"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Known values are: \"1g\", \"4g\", \"16g\", and \"64g\".""" - skills: Optional[list["_models.ContainerSkill"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """An optional list of skills referenced by id or inline data.""" - network_policy: Optional["_models.ContainerNetworkPolicyParam"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - - @overload - def __init__( - self, - *, - file_ids: Optional[list[str]] = None, - memory_limit: Optional[Union[str, "_models.ContainerMemoryLimit"]] = None, - skills: Optional[list["_models.ContainerSkill"]] = None, - network_policy: Optional["_models.ContainerNetworkPolicyParam"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = FunctionShellToolParamEnvironmentType.CONTAINER_AUTO # type: ignore - - -class ContainerFileCitationBody(Annotation, discriminator="container_file_citation"): - """Container file citation. - - :ivar type: The type of the container file citation. Always ``container_file_citation``. - Required. CONTAINER_FILE_CITATION. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CONTAINER_FILE_CITATION - :ivar container_id: The ID of the container file. Required. - :vartype container_id: str - :ivar file_id: The ID of the file. Required. - :vartype file_id: str - :ivar start_index: The index of the first character of the container file citation in the - message. Required. - :vartype start_index: int - :ivar end_index: The index of the last character of the container file citation in the message. - Required. - :vartype end_index: int - :ivar filename: The filename of the container file cited. Required. - :vartype filename: str - """ - - type: Literal[AnnotationType.CONTAINER_FILE_CITATION] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the container file citation. Always ``container_file_citation``. Required. - CONTAINER_FILE_CITATION.""" - container_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the container file. Required.""" - file_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the file. Required.""" - start_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the first character of the container file citation in the message. Required.""" - end_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the last character of the container file citation in the message. Required.""" - filename: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The filename of the container file cited. Required.""" - - @overload - def __init__( - self, - *, - container_id: str, - file_id: str, - start_index: int, - end_index: int, - filename: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = AnnotationType.CONTAINER_FILE_CITATION # type: ignore - - -class ContainerNetworkPolicyParam(_Model): - """Network access policy for the container. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ContainerNetworkPolicyAllowlistParam, ContainerNetworkPolicyDisabledParam - - :ivar type: Required. Known values are: "disabled" and "allowlist". - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.ContainerNetworkPolicyParamType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"disabled\" and \"allowlist\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ContainerNetworkPolicyAllowlistParam(ContainerNetworkPolicyParam, discriminator="allowlist"): - """ContainerNetworkPolicyAllowlistParam. - - :ivar type: Allow outbound network access only to specified domains. Always ``allowlist``. - Required. ALLOWLIST. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.ALLOWLIST - :ivar allowed_domains: A list of allowed domains when type is ``allowlist``. Required. - :vartype allowed_domains: list[str] - :ivar domain_secrets: Optional domain-scoped secrets for allowlisted domains. - :vartype domain_secrets: - list[~azure.ai.agentserver.responses.models.models.ContainerNetworkPolicyDomainSecretParam] - """ - - type: Literal[ContainerNetworkPolicyParamType.ALLOWLIST] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Allow outbound network access only to specified domains. Always ``allowlist``. Required. - ALLOWLIST.""" - allowed_domains: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A list of allowed domains when type is ``allowlist``. Required.""" - domain_secrets: Optional[list["_models.ContainerNetworkPolicyDomainSecretParam"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Optional domain-scoped secrets for allowlisted domains.""" - - @overload - def __init__( - self, - *, - allowed_domains: list[str], - domain_secrets: Optional[list["_models.ContainerNetworkPolicyDomainSecretParam"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ContainerNetworkPolicyParamType.ALLOWLIST # type: ignore - - -class ContainerNetworkPolicyDisabledParam(ContainerNetworkPolicyParam, discriminator="disabled"): - """ContainerNetworkPolicyDisabledParam. - - :ivar type: Disable outbound network access. Always ``disabled``. Required. DISABLED. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.DISABLED - """ - - type: Literal[ContainerNetworkPolicyParamType.DISABLED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Disable outbound network access. Always ``disabled``. Required. DISABLED.""" - - @overload - def __init__( - self, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ContainerNetworkPolicyParamType.DISABLED # type: ignore - - -class ContainerNetworkPolicyDomainSecretParam(_Model): - """ContainerNetworkPolicyDomainSecretParam. - - :ivar domain: The domain associated with the secret. Required. - :vartype domain: str - :ivar name: The name of the secret to inject for the domain. Required. - :vartype name: str - :ivar value: The secret value to inject for the domain. Required. - :vartype value: str - """ - - domain: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The domain associated with the secret. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the secret to inject for the domain. Required.""" - value: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The secret value to inject for the domain. Required.""" - - @overload - def __init__( - self, - *, - domain: str, - name: str, - value: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class FunctionShellCallEnvironment(_Model): - """FunctionShellCallEnvironment. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ContainerReferenceResource, LocalEnvironmentResource - - :ivar type: Required. Known values are: "local" and "container_reference". - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.FunctionShellCallEnvironmentType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"local\" and \"container_reference\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ContainerReferenceResource(FunctionShellCallEnvironment, discriminator="container_reference"): - """Container Reference. - - :ivar type: The environment type. Always ``container_reference``. Required. - CONTAINER_REFERENCE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CONTAINER_REFERENCE - :ivar container_id: Required. - :vartype container_id: str - """ - - type: Literal[FunctionShellCallEnvironmentType.CONTAINER_REFERENCE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The environment type. Always ``container_reference``. Required. CONTAINER_REFERENCE.""" - container_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - container_id: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = FunctionShellCallEnvironmentType.CONTAINER_REFERENCE # type: ignore - - -class ContainerSkill(_Model): - """ContainerSkill. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - InlineSkillParam, SkillReferenceParam - - :ivar type: Required. Known values are: "skill_reference" and "inline". - :vartype type: str or ~azure.ai.agentserver.responses.models.models.ContainerSkillType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"skill_reference\" and \"inline\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ContextManagementParam(_Model): - """ContextManagementParam. - - :ivar type: The context management entry type. Currently only 'compaction' is supported. - Required. - :vartype type: str - :ivar compact_threshold: - :vartype compact_threshold: int - """ - - type: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The context management entry type. Currently only 'compaction' is supported. Required.""" - compact_threshold: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - type: str, - compact_threshold: Optional[int] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ConversationParam_2(_Model): - """Conversation object. - - :ivar id: The unique ID of the conversation. Required. - :vartype id: str - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the conversation. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ConversationReference(_Model): - """Conversation. - - :ivar id: The unique ID of the conversation that this response was associated with. Required. - :vartype id: str - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the conversation that this response was associated with. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class CoordParam(_Model): - """Coordinate. - - :ivar x: The x-coordinate. Required. - :vartype x: int - :ivar y: The y-coordinate. Required. - :vartype y: int - """ - - x: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The x-coordinate. Required.""" - y: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The y-coordinate. Required.""" - - @overload - def __init__( - self, - *, - x: int, - y: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class CreateResponse(_Model): - """CreateResponse. - - :ivar metadata: - :vartype metadata: ~azure.ai.agentserver.responses.models.models.Metadata - :ivar top_logprobs: - :vartype top_logprobs: int - :ivar temperature: - :vartype temperature: int - :ivar top_p: - :vartype top_p: int - :ivar user: This field is being replaced by ``safety_identifier`` and ``prompt_cache_key``. Use - ``prompt_cache_key`` instead to maintain caching optimizations. A stable identifier for your - end-users. Used to boost cache hit rates by better bucketing similar requests and to help - OpenAI detect and prevent abuse. `Learn more - `_. - :vartype user: str - :ivar safety_identifier: A stable identifier used to help detect users of your application that - may be violating OpenAI's usage policies. The IDs should be a string that uniquely identifies - each user. We recommend hashing their username or email address, in order to avoid sending us - any identifying information. `Learn more - `_. - :vartype safety_identifier: str - :ivar prompt_cache_key: Used by OpenAI to cache responses for similar requests to optimize your - cache hit rates. Replaces the ``user`` field. `Learn more `_. - :vartype prompt_cache_key: str - :ivar service_tier: Is one of the following types: Literal["auto"], Literal["default"], - Literal["flex"], Literal["scale"], Literal["priority"] - :vartype service_tier: str or str or str or str or str - :ivar prompt_cache_retention: Is either a Literal["in-memory"] type or a Literal["24h"] type. - :vartype prompt_cache_retention: str or str - :ivar previous_response_id: - :vartype previous_response_id: str - :ivar model: The model deployment to use for the creation of this response. - :vartype model: str - :ivar reasoning: - :vartype reasoning: ~azure.ai.agentserver.responses.models.models.Reasoning - :ivar background: - :vartype background: bool - :ivar max_output_tokens: - :vartype max_output_tokens: int - :ivar max_tool_calls: - :vartype max_tool_calls: int - :ivar text: - :vartype text: ~azure.ai.agentserver.responses.models.models.ResponseTextParam - :ivar tools: - :vartype tools: list[~azure.ai.agentserver.responses.models.models.Tool] - :ivar tool_choice: Is either a Union[str, "_models.ToolChoiceOptions"] type or a - ToolChoiceParam type. - :vartype tool_choice: str or ~azure.ai.agentserver.responses.models.models.ToolChoiceOptions or - ~azure.ai.agentserver.responses.models.models.ToolChoiceParam - :ivar prompt: - :vartype prompt: ~azure.ai.agentserver.responses.models.models.Prompt - :ivar truncation: Is either a Literal["auto"] type or a Literal["disabled"] type. - :vartype truncation: str or str - :ivar input: Is either a str type or a [Item] type. - :vartype input: str or list[~azure.ai.agentserver.responses.models.models.Item] - :ivar include: - :vartype include: list[str or ~azure.ai.agentserver.responses.models.models.IncludeEnum] - :ivar parallel_tool_calls: - :vartype parallel_tool_calls: bool - :ivar store: - :vartype store: bool - :ivar instructions: - :vartype instructions: str - :ivar stream: - :vartype stream: bool - :ivar stream_options: - :vartype stream_options: ~azure.ai.agentserver.responses.models.models.ResponseStreamOptions - :ivar conversation: Is either a str type or a ConversationParam_2 type. - :vartype conversation: str or ~azure.ai.agentserver.responses.models.models.ConversationParam_2 - :ivar context_management: Context management configuration for this request. - :vartype context_management: - list[~azure.ai.agentserver.responses.models.models.ContextManagementParam] - :ivar agent_reference: The agent to use for generating the response. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar structured_inputs: The structured inputs to the response that can participate in prompt - template substitution or tool argument bindings. - :vartype structured_inputs: dict[str, any] - """ - - metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - top_logprobs: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - temperature: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - top_p: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - user: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """This field is being replaced by ``safety_identifier`` and ``prompt_cache_key``. Use - ``prompt_cache_key`` instead to maintain caching optimizations. A stable identifier for your - end-users. Used to boost cache hit rates by better bucketing similar requests and to help - OpenAI detect and prevent abuse. `Learn more - `_.""" - safety_identifier: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A stable identifier used to help detect users of your application that may be violating - OpenAI's usage policies. The IDs should be a string that uniquely identifies each user. We - recommend hashing their username or email address, in order to avoid sending us any identifying - information. `Learn more `_.""" - prompt_cache_key: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. - Replaces the ``user`` field. `Learn more `_.""" - service_tier: Optional[Literal["auto", "default", "flex", "scale", "priority"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Is one of the following types: Literal[\"auto\"], Literal[\"default\"], Literal[\"flex\"], - Literal[\"scale\"], Literal[\"priority\"]""" - prompt_cache_retention: Optional[Literal["in-memory", "24h"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Is either a Literal[\"in-memory\"] type or a Literal[\"24h\"] type.""" - previous_response_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - model: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The model deployment to use for the creation of this response.""" - reasoning: Optional["_models.Reasoning"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - background: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - max_output_tokens: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - max_tool_calls: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - text: Optional["_models.ResponseTextParam"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - tools: Optional[list["_models.Tool"]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - tool_choice: Optional[Union[str, "_models.ToolChoiceOptions", "_models.ToolChoiceParam"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Is either a Union[str, \"_models.ToolChoiceOptions\"] type or a ToolChoiceParam type.""" - prompt: Optional["_models.Prompt"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - truncation: Optional[Literal["auto", "disabled"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Is either a Literal[\"auto\"] type or a Literal[\"disabled\"] type.""" - input: Optional["_types.InputParam"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Is either a str type or a [Item] type.""" - include: Optional[list[Union[str, "_models.IncludeEnum"]]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - parallel_tool_calls: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - store: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - instructions: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - stream: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - stream_options: Optional["_models.ResponseStreamOptions"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - conversation: Optional["_types.ConversationParam"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Is either a str type or a ConversationParam_2 type.""" - context_management: Optional[list["_models.ContextManagementParam"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Context management configuration for this request.""" - agent_reference: Optional["_models.AgentReference"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The agent to use for generating the response.""" - structured_inputs: Optional[dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The structured inputs to the response that can participate in prompt template substitution or - tool argument bindings.""" - - @overload - def __init__( # pylint: disable=too-many-locals - self, - *, - metadata: Optional["_models.Metadata"] = None, - top_logprobs: Optional[int] = None, - temperature: Optional[int] = None, - top_p: Optional[int] = None, - user: Optional[str] = None, - safety_identifier: Optional[str] = None, - prompt_cache_key: Optional[str] = None, - service_tier: Optional[Literal["auto", "default", "flex", "scale", "priority"]] = None, - prompt_cache_retention: Optional[Literal["in-memory", "24h"]] = None, - previous_response_id: Optional[str] = None, - model: Optional[str] = None, - reasoning: Optional["_models.Reasoning"] = None, - background: Optional[bool] = None, - max_output_tokens: Optional[int] = None, - max_tool_calls: Optional[int] = None, - text: Optional["_models.ResponseTextParam"] = None, - tools: Optional[list["_models.Tool"]] = None, - tool_choice: Optional[Union[str, "_models.ToolChoiceOptions", "_models.ToolChoiceParam"]] = None, - prompt: Optional["_models.Prompt"] = None, - truncation: Optional[Literal["auto", "disabled"]] = None, - input: Optional["_types.InputParam"] = None, - include: Optional[list[Union[str, "_models.IncludeEnum"]]] = None, - parallel_tool_calls: Optional[bool] = None, - store: Optional[bool] = None, - instructions: Optional[str] = None, - stream: Optional[bool] = None, - stream_options: Optional["_models.ResponseStreamOptions"] = None, - conversation: Optional["_types.ConversationParam"] = None, - context_management: Optional[list["_models.ContextManagementParam"]] = None, - agent_reference: Optional["_models.AgentReference"] = None, - structured_inputs: Optional[dict[str, Any]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class CustomToolParamFormat(_Model): - """The input format for the custom tool. Default is unconstrained text. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - CustomGrammarFormatParam, CustomTextFormatParam - - :ivar type: Required. Known values are: "text" and "grammar". - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CustomToolParamFormatType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"text\" and \"grammar\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class CustomGrammarFormatParam(CustomToolParamFormat, discriminator="grammar"): - """Grammar format. - - :ivar type: Grammar format. Always ``grammar``. Required. GRAMMAR. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.GRAMMAR - :ivar syntax: The syntax of the grammar definition. One of ``lark`` or ``regex``. Required. - Known values are: "lark" and "regex". - :vartype syntax: str or ~azure.ai.agentserver.responses.models.models.GrammarSyntax1 - :ivar definition: The grammar definition. Required. - :vartype definition: str - """ - - type: Literal[CustomToolParamFormatType.GRAMMAR] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Grammar format. Always ``grammar``. Required. GRAMMAR.""" - syntax: Union[str, "_models.GrammarSyntax1"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The syntax of the grammar definition. One of ``lark`` or ``regex``. Required. Known values are: - \"lark\" and \"regex\".""" - definition: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The grammar definition. Required.""" - - @overload - def __init__( - self, - *, - syntax: Union[str, "_models.GrammarSyntax1"], - definition: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = CustomToolParamFormatType.GRAMMAR # type: ignore - - -class CustomTextFormatParam(CustomToolParamFormat, discriminator="text"): - """Text format. - - :ivar type: Unconstrained text format. Always ``text``. Required. TEXT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.TEXT - """ - - type: Literal[CustomToolParamFormatType.TEXT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Unconstrained text format. Always ``text``. Required. TEXT.""" - - @overload - def __init__( - self, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = CustomToolParamFormatType.TEXT # type: ignore - - -class CustomToolParam(Tool, discriminator="custom"): - """Custom tool. - - :ivar type: The type of the custom tool. Always ``custom``. Required. CUSTOM. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CUSTOM - :ivar name: The name of the custom tool, used to identify it in tool calls. Required. - :vartype name: str - :ivar description: Optional description of the custom tool, used to provide more context. - :vartype description: str - :ivar format: The input format for the custom tool. Default is unconstrained text. - :vartype format: ~azure.ai.agentserver.responses.models.models.CustomToolParamFormat - """ - - type: Literal[ToolType.CUSTOM] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the custom tool. Always ``custom``. Required. CUSTOM.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the custom tool, used to identify it in tool calls. Required.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional description of the custom tool, used to provide more context.""" - format: Optional["_models.CustomToolParamFormat"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The input format for the custom tool. Default is unconstrained text.""" - - @overload - def __init__( - self, - *, - name: str, - description: Optional[str] = None, - format: Optional["_models.CustomToolParamFormat"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.CUSTOM # type: ignore - - -class DeleteResponseResult(_Model): - """The result of a delete response operation. - - :ivar id: The operation ID. Required. - :vartype id: str - :ivar deleted: Always return true. Required. Default value is True. - :vartype deleted: bool - :ivar object: Required. Default value is "response". - :vartype object: str - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The operation ID. Required.""" - deleted: Literal[True] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Always return true. Required. Default value is True.""" - object: Literal["response"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required. Default value is \"response\".""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.deleted: Literal[True] = True - self.object: Literal["response"] = "response" - - -class DoubleClickAction(ComputerAction, discriminator="double_click"): - """DoubleClick. - - :ivar type: Specifies the event type. For a double click action, this property is always set to - ``double_click``. Required. DOUBLE_CLICK. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.DOUBLE_CLICK - :ivar x: The x-coordinate where the double click occurred. Required. - :vartype x: int - :ivar y: The y-coordinate where the double click occurred. Required. - :vartype y: int - """ - - type: Literal[ComputerActionType.DOUBLE_CLICK] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Specifies the event type. For a double click action, this property is always set to - ``double_click``. Required. DOUBLE_CLICK.""" - x: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The x-coordinate where the double click occurred. Required.""" - y: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The y-coordinate where the double click occurred. Required.""" - - @overload - def __init__( - self, - *, - x: int, - y: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ComputerActionType.DOUBLE_CLICK # type: ignore - - -class DragParam(ComputerAction, discriminator="drag"): - """Drag. - - :ivar type: Specifies the event type. For a drag action, this property is always set to - ``drag``. Required. DRAG. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.DRAG - :ivar path: An array of coordinates representing the path of the drag action. Coordinates will - appear as an array of objects, eg - - .. code-block:: - - [ - { x: 100, y: 200 }, - { x: 200, y: 300 } - ]. Required. - :vartype path: list[~azure.ai.agentserver.responses.models.models.CoordParam] - """ - - type: Literal[ComputerActionType.DRAG] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Specifies the event type. For a drag action, this property is always set to ``drag``. Required. - DRAG.""" - path: list["_models.CoordParam"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """An array of coordinates representing the path of the drag action. Coordinates will appear as an - array of objects, eg - - .. code-block:: - - [ - { x: 100, y: 200 }, - { x: 200, y: 300 } - ]. Required.""" - - @overload - def __init__( - self, - *, - path: list["_models.CoordParam"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ComputerActionType.DRAG # type: ignore - - -class Error(_Model): - """Error. - - :ivar code: Required. - :vartype code: str - :ivar message: Required. - :vartype message: str - :ivar param: - :vartype param: str - :ivar type: - :vartype type: str - :ivar details: - :vartype details: list[~azure.ai.agentserver.responses.models.models.Error] - :ivar additional_info: - :vartype additional_info: dict[str, any] - :ivar debug_info: - :vartype debug_info: dict[str, any] - """ - - code: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - message: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - param: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - type: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - details: Optional[list["_models.Error"]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - additional_info: Optional[dict[str, Any]] = rest_field( - name="additionalInfo", visibility=["read", "create", "update", "delete", "query"] - ) - debug_info: Optional[dict[str, Any]] = rest_field( - name="debugInfo", visibility=["read", "create", "update", "delete", "query"] - ) - - @overload - def __init__( - self, - *, - code: str, - message: str, - param: Optional[str] = None, - type: Optional[str] = None, - details: Optional[list["_models.Error"]] = None, - additional_info: Optional[dict[str, Any]] = None, - debug_info: Optional[dict[str, Any]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class FabricDataAgentToolCall(OutputItem, discriminator="fabric_dataagent_preview_call"): - """A Fabric data agent tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. FABRIC_DATAAGENT_PREVIEW_CALL. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.FABRIC_DATAAGENT_PREVIEW_CALL - :ivar call_id: The unique ID of the tool call generated by the model. Required. - :vartype call_id: str - :ivar arguments: A JSON string of the arguments to pass to the tool. Required. - :vartype arguments: str - :ivar status: The status of the tool call. Required. Known values are: "in_progress", - "completed", "incomplete", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ToolCallStatus - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.FABRIC_DATAAGENT_PREVIEW_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. FABRIC_DATAAGENT_PREVIEW_CALL.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call generated by the model. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of the arguments to pass to the tool. Required.""" - status: Union[str, "_models.ToolCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. Required. Known values are: \"in_progress\", \"completed\", - \"incomplete\", and \"failed\".""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - arguments: str, - status: Union[str, "_models.ToolCallStatus"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.FABRIC_DATAAGENT_PREVIEW_CALL # type: ignore - - -class FabricDataAgentToolCallOutput(OutputItem, discriminator="fabric_dataagent_preview_call_output"): - """The output of a Fabric data agent tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. FABRIC_DATAAGENT_PREVIEW_CALL_OUTPUT. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.FABRIC_DATAAGENT_PREVIEW_CALL_OUTPUT - :ivar call_id: The unique ID of the tool call generated by the model. Required. - :vartype call_id: str - :ivar output: The output from the Fabric data agent tool call. Is one of the following types: - {str: Any}, str, [Any] - :vartype output: dict[str, any] or str or list[any] - :ivar status: The status of the tool call. Required. Known values are: "in_progress", - "completed", "incomplete", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ToolCallStatus - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.FABRIC_DATAAGENT_PREVIEW_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. FABRIC_DATAAGENT_PREVIEW_CALL_OUTPUT.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call generated by the model. Required.""" - output: Optional["_types.ToolCallOutputContent"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The output from the Fabric data agent tool call. Is one of the following types: {str: Any}, - str, [Any]""" - status: Union[str, "_models.ToolCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. Required. Known values are: \"in_progress\", \"completed\", - \"incomplete\", and \"failed\".""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - status: Union[str, "_models.ToolCallStatus"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - output: Optional["_types.ToolCallOutputContent"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.FABRIC_DATAAGENT_PREVIEW_CALL_OUTPUT # type: ignore - - -class FabricDataAgentToolParameters(_Model): - """The fabric data agent tool parameters. - - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar project_connections: The project connections attached to this tool. There can be a - maximum of 1 connection resource attached to the tool. - :vartype project_connections: - list[~azure.ai.agentserver.responses.models.models.ToolProjectConnection] - """ - - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - project_connections: Optional[list["_models.ToolProjectConnection"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The project connections attached to this tool. There can be a maximum of 1 connection resource - attached to the tool.""" - - @overload - def __init__( - self, - *, - name: Optional[str] = None, - description: Optional[str] = None, - project_connections: Optional[list["_models.ToolProjectConnection"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class FileCitationBody(Annotation, discriminator="file_citation"): - """File citation. - - :ivar type: The type of the file citation. Always ``file_citation``. Required. FILE_CITATION. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.FILE_CITATION - :ivar file_id: The ID of the file. Required. - :vartype file_id: str - :ivar index: The index of the file in the list of files. Required. - :vartype index: int - :ivar filename: The filename of the file cited. Required. - :vartype filename: str - """ - - type: Literal[AnnotationType.FILE_CITATION] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the file citation. Always ``file_citation``. Required. FILE_CITATION.""" - file_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the file. Required.""" - index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the file in the list of files. Required.""" - filename: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The filename of the file cited. Required.""" - - @overload - def __init__( - self, - *, - file_id: str, - index: int, - filename: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = AnnotationType.FILE_CITATION # type: ignore - - -class FilePath(Annotation, discriminator="file_path"): - """File path. - - :ivar type: The type of the file path. Always ``file_path``. Required. FILE_PATH. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.FILE_PATH - :ivar file_id: The ID of the file. Required. - :vartype file_id: str - :ivar index: The index of the file in the list of files. Required. - :vartype index: int - """ - - type: Literal[AnnotationType.FILE_PATH] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the file path. Always ``file_path``. Required. FILE_PATH.""" - file_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the file. Required.""" - index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the file in the list of files. Required.""" - - @overload - def __init__( - self, - *, - file_id: str, - index: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = AnnotationType.FILE_PATH # type: ignore - - -class FileSearchTool(Tool, discriminator="file_search"): - """File search. - - :ivar type: The type of the file search tool. Always ``file_search``. Required. FILE_SEARCH. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.FILE_SEARCH - :ivar vector_store_ids: The IDs of the vector stores to search. Required. - :vartype vector_store_ids: list[str] - :ivar max_num_results: The maximum number of results to return. This number should be between 1 - and 50 inclusive. - :vartype max_num_results: int - :ivar ranking_options: Ranking options for search. - :vartype ranking_options: ~azure.ai.agentserver.responses.models.models.RankingOptions - :ivar filters: Is either a ComparisonFilter type or a CompoundFilter type. - :vartype filters: ~azure.ai.agentserver.responses.models.models.ComparisonFilter or - ~azure.ai.agentserver.responses.models.models.CompoundFilter - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - """ - - type: Literal[ToolType.FILE_SEARCH] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the file search tool. Always ``file_search``. Required. FILE_SEARCH.""" - vector_store_ids: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The IDs of the vector stores to search. Required.""" - max_num_results: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The maximum number of results to return. This number should be between 1 and 50 inclusive.""" - ranking_options: Optional["_models.RankingOptions"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Ranking options for search.""" - filters: Optional["_types.Filters"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Is either a ComparisonFilter type or a CompoundFilter type.""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - - @overload - def __init__( - self, - *, - vector_store_ids: list[str], - max_num_results: Optional[int] = None, - ranking_options: Optional["_models.RankingOptions"] = None, - filters: Optional["_types.Filters"] = None, - name: Optional[str] = None, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.FILE_SEARCH # type: ignore - - -class FileSearchToolCallResults(_Model): - """FileSearchToolCallResults. - - :ivar file_id: - :vartype file_id: str - :ivar text: - :vartype text: str - :ivar filename: - :vartype filename: str - :ivar attributes: - :vartype attributes: ~azure.ai.agentserver.responses.models.models.VectorStoreFileAttributes - :ivar score: - :vartype score: float - """ - - file_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - text: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - filename: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - attributes: Optional["_models.VectorStoreFileAttributes"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - score: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - file_id: Optional[str] = None, - text: Optional[str] = None, - filename: Optional[str] = None, - attributes: Optional["_models.VectorStoreFileAttributes"] = None, - score: Optional[float] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class FunctionAndCustomToolCallOutput(_Model): - """FunctionAndCustomToolCallOutput. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - FunctionAndCustomToolCallOutputInputFileContent, - FunctionAndCustomToolCallOutputInputImageContent, - FunctionAndCustomToolCallOutputInputTextContent - - :ivar type: Required. Known values are: "input_text", "input_image", and "input_file". - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.FunctionAndCustomToolCallOutputType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"input_text\", \"input_image\", and \"input_file\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class FunctionAndCustomToolCallOutputInputFileContent( - FunctionAndCustomToolCallOutput, discriminator="input_file" -): # pylint: disable=name-too-long - """Input file. - - :ivar type: The type of the input item. Always ``input_file``. Required. INPUT_FILE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.INPUT_FILE - :ivar file_id: - :vartype file_id: str - :ivar filename: The name of the file to be sent to the model. - :vartype filename: str - :ivar file_url: The URL of the file to be sent to the model. - :vartype file_url: str - :ivar file_data: The content of the file to be sent to the model. - :vartype file_data: str - """ - - type: Literal[FunctionAndCustomToolCallOutputType.INPUT_FILE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the input item. Always ``input_file``. Required. INPUT_FILE.""" - file_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - filename: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the file to be sent to the model.""" - file_url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The URL of the file to be sent to the model.""" - file_data: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The content of the file to be sent to the model.""" - - @overload - def __init__( - self, - *, - file_id: Optional[str] = None, - filename: Optional[str] = None, - file_url: Optional[str] = None, - file_data: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = FunctionAndCustomToolCallOutputType.INPUT_FILE # type: ignore - - -class FunctionAndCustomToolCallOutputInputImageContent( - FunctionAndCustomToolCallOutput, discriminator="input_image" -): # pylint: disable=name-too-long - """Input image. - - :ivar type: The type of the input item. Always ``input_image``. Required. INPUT_IMAGE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.INPUT_IMAGE - :ivar image_url: - :vartype image_url: str - :ivar file_id: - :vartype file_id: str - :ivar detail: The detail level of the image to be sent to the model. One of ``high``, ``low``, - or ``auto``. Defaults to ``auto``. Required. Known values are: "low", "high", and "auto". - :vartype detail: str or ~azure.ai.agentserver.responses.models.models.ImageDetail - """ - - type: Literal[FunctionAndCustomToolCallOutputType.INPUT_IMAGE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the input item. Always ``input_image``. Required. INPUT_IMAGE.""" - image_url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - file_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - detail: Union[str, "_models.ImageDetail"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The detail level of the image to be sent to the model. One of ``high``, ``low``, or ``auto``. - Defaults to ``auto``. Required. Known values are: \"low\", \"high\", and \"auto\".""" - - @overload - def __init__( - self, - *, - detail: Union[str, "_models.ImageDetail"], - image_url: Optional[str] = None, - file_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = FunctionAndCustomToolCallOutputType.INPUT_IMAGE # type: ignore - - -class FunctionAndCustomToolCallOutputInputTextContent( - FunctionAndCustomToolCallOutput, discriminator="input_text" -): # pylint: disable=name-too-long - """Input text. - - :ivar type: The type of the input item. Always ``input_text``. Required. INPUT_TEXT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.INPUT_TEXT - :ivar text: The text input to the model. Required. - :vartype text: str - """ - - type: Literal[FunctionAndCustomToolCallOutputType.INPUT_TEXT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the input item. Always ``input_text``. Required. INPUT_TEXT.""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The text input to the model. Required.""" - - @overload - def __init__( - self, - *, - text: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = FunctionAndCustomToolCallOutputType.INPUT_TEXT # type: ignore - - -class FunctionCallOutputItemParam(Item, discriminator="function_call_output"): - """Function tool call output. - - :ivar id: - :vartype id: str - :ivar call_id: The unique ID of the function tool call generated by the model. Required. - :vartype call_id: str - :ivar type: The type of the function tool call output. Always ``function_call_output``. - Required. FUNCTION_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.FUNCTION_CALL_OUTPUT - :ivar output: Text, image, or file output of the function tool call. Required. Is either a str - type or a [Union["_models.InputTextContentParam", "_models.InputImageContentParamAutoParam", - "_models.InputFileContentParam"]] type. - :vartype output: str or - list[~azure.ai.agentserver.responses.models.models.InputTextContentParam or - ~azure.ai.agentserver.responses.models.models.InputImageContentParamAutoParam or - ~azure.ai.agentserver.responses.models.models.InputFileContentParam] - :ivar status: Known values are: "in_progress", "completed", and "incomplete". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.FunctionCallItemStatus - """ - - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the function tool call generated by the model. Required.""" - type: Literal[ItemType.FUNCTION_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the function tool call output. Always ``function_call_output``. Required. - FUNCTION_CALL_OUTPUT.""" - output: Union[ - str, - list[ - Union[ - "_models.InputTextContentParam", - "_models.InputImageContentParamAutoParam", - "_models.InputFileContentParam", - ] - ], - ] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Text, image, or file output of the function tool call. Required. Is either a str type or a - [Union[\"_models.InputTextContentParam\", \"_models.InputImageContentParamAutoParam\", - \"_models.InputFileContentParam\"]] type.""" - status: Optional[Union[str, "_models.FunctionCallItemStatus"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Known values are: \"in_progress\", \"completed\", and \"incomplete\".""" - - @overload - def __init__( - self, - *, - call_id: str, - output: Union[ - str, - list[ - Union[ - "_models.InputTextContentParam", - "_models.InputImageContentParamAutoParam", - "_models.InputFileContentParam", - ] - ], - ], - id: Optional[str] = None, # pylint: disable=redefined-builtin - status: Optional[Union[str, "_models.FunctionCallItemStatus"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.FUNCTION_CALL_OUTPUT # type: ignore - - -class FunctionShellAction(_Model): - """Shell exec action. - - :ivar commands: Required. - :vartype commands: list[str] - :ivar timeout_ms: Required. - :vartype timeout_ms: int - :ivar max_output_length: Required. - :vartype max_output_length: int - """ - - commands: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - timeout_ms: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - max_output_length: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - commands: list[str], - timeout_ms: int, - max_output_length: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class FunctionShellActionParam(_Model): - """Shell action. - - :ivar commands: Ordered shell commands for the execution environment to run. Required. - :vartype commands: list[str] - :ivar timeout_ms: - :vartype timeout_ms: int - :ivar max_output_length: - :vartype max_output_length: int - """ - - commands: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Ordered shell commands for the execution environment to run. Required.""" - timeout_ms: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - max_output_length: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - commands: list[str], - timeout_ms: Optional[int] = None, - max_output_length: Optional[int] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class FunctionShellCallItemParam(Item, discriminator="shell_call"): - """Shell tool call. - - :ivar id: - :vartype id: str - :ivar call_id: The unique ID of the shell tool call generated by the model. Required. - :vartype call_id: str - :ivar type: The type of the item. Always ``shell_call``. Required. SHELL_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.SHELL_CALL - :ivar action: The shell commands and limits that describe how to run the tool call. Required. - :vartype action: ~azure.ai.agentserver.responses.models.models.FunctionShellActionParam - :ivar status: Known values are: "in_progress", "completed", and "incomplete". - :vartype status: str or - ~azure.ai.agentserver.responses.models.models.FunctionShellCallItemStatus - :ivar environment: - :vartype environment: - ~azure.ai.agentserver.responses.models.models.FunctionShellCallItemParamEnvironment - """ - - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the shell tool call generated by the model. Required.""" - type: Literal[ItemType.SHELL_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``shell_call``. Required. SHELL_CALL.""" - action: "_models.FunctionShellActionParam" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The shell commands and limits that describe how to run the tool call. Required.""" - status: Optional[Union[str, "_models.FunctionShellCallItemStatus"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Known values are: \"in_progress\", \"completed\", and \"incomplete\".""" - environment: Optional["_models.FunctionShellCallItemParamEnvironment"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - - @overload - def __init__( - self, - *, - call_id: str, - action: "_models.FunctionShellActionParam", - id: Optional[str] = None, # pylint: disable=redefined-builtin - status: Optional[Union[str, "_models.FunctionShellCallItemStatus"]] = None, - environment: Optional["_models.FunctionShellCallItemParamEnvironment"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.SHELL_CALL # type: ignore - - -class FunctionShellCallItemParamEnvironment(_Model): - """The environment to execute the shell commands in. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - FunctionShellCallItemParamEnvironmentContainerReferenceParam, - FunctionShellCallItemParamEnvironmentLocalEnvironmentParam - - :ivar type: Required. Known values are: "local" and "container_reference". - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.FunctionShellCallItemParamEnvironmentType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"local\" and \"container_reference\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class FunctionShellCallItemParamEnvironmentContainerReferenceParam( - FunctionShellCallItemParamEnvironment, discriminator="container_reference" -): # pylint: disable=name-too-long - """FunctionShellCallItemParamEnvironmentContainerReferenceParam. - - :ivar type: References a container created with the /v1/containers endpoint. Required. - CONTAINER_REFERENCE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CONTAINER_REFERENCE - :ivar container_id: The ID of the referenced container. Required. - :vartype container_id: str - """ - - type: Literal[FunctionShellCallItemParamEnvironmentType.CONTAINER_REFERENCE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """References a container created with the /v1/containers endpoint. Required. CONTAINER_REFERENCE.""" - container_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the referenced container. Required.""" - - @overload - def __init__( - self, - *, - container_id: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = FunctionShellCallItemParamEnvironmentType.CONTAINER_REFERENCE # type: ignore - - -class FunctionShellCallItemParamEnvironmentLocalEnvironmentParam( - FunctionShellCallItemParamEnvironment, discriminator="local" -): # pylint: disable=name-too-long - """FunctionShellCallItemParamEnvironmentLocalEnvironmentParam. - - :ivar type: Use a local computer environment. Required. LOCAL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.LOCAL - :ivar skills: An optional list of skills. - :vartype skills: list[~azure.ai.agentserver.responses.models.models.LocalSkillParam] - """ - - type: Literal[FunctionShellCallItemParamEnvironmentType.LOCAL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Use a local computer environment. Required. LOCAL.""" - skills: Optional[list["_models.LocalSkillParam"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """An optional list of skills.""" - - @overload - def __init__( - self, - *, - skills: Optional[list["_models.LocalSkillParam"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = FunctionShellCallItemParamEnvironmentType.LOCAL # type: ignore - - -class FunctionShellCallOutputContent(_Model): - """Shell call output content. - - :ivar stdout: The standard output that was captured. Required. - :vartype stdout: str - :ivar stderr: The standard error output that was captured. Required. - :vartype stderr: str - :ivar outcome: Shell call outcome. Required. - :vartype outcome: ~azure.ai.agentserver.responses.models.models.FunctionShellCallOutputOutcome - :ivar created_by: The identifier of the actor that created the item. - :vartype created_by: str - """ - - stdout: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The standard output that was captured. Required.""" - stderr: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The standard error output that was captured. Required.""" - outcome: "_models.FunctionShellCallOutputOutcome" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Shell call outcome. Required.""" - created_by: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The identifier of the actor that created the item.""" - - @overload - def __init__( - self, - *, - stdout: str, - stderr: str, - outcome: "_models.FunctionShellCallOutputOutcome", - created_by: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class FunctionShellCallOutputContentParam(_Model): - """Shell output content. - - :ivar stdout: Captured stdout output for the shell call. Required. - :vartype stdout: str - :ivar stderr: Captured stderr output for the shell call. Required. - :vartype stderr: str - :ivar outcome: The exit or timeout outcome associated with this shell call. Required. - :vartype outcome: - ~azure.ai.agentserver.responses.models.models.FunctionShellCallOutputOutcomeParam - """ - - stdout: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Captured stdout output for the shell call. Required.""" - stderr: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Captured stderr output for the shell call. Required.""" - outcome: "_models.FunctionShellCallOutputOutcomeParam" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The exit or timeout outcome associated with this shell call. Required.""" - - @overload - def __init__( - self, - *, - stdout: str, - stderr: str, - outcome: "_models.FunctionShellCallOutputOutcomeParam", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class FunctionShellCallOutputOutcome(_Model): - """Shell call outcome. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - FunctionShellCallOutputExitOutcome, FunctionShellCallOutputTimeoutOutcome - - :ivar type: Required. Known values are: "timeout" and "exit". - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.FunctionShellCallOutputOutcomeType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"timeout\" and \"exit\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class FunctionShellCallOutputExitOutcome(FunctionShellCallOutputOutcome, discriminator="exit"): - """Shell call exit outcome. - - :ivar type: The outcome type. Always ``exit``. Required. EXIT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.EXIT - :ivar exit_code: Exit code from the shell process. Required. - :vartype exit_code: int - """ - - type: Literal[FunctionShellCallOutputOutcomeType.EXIT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The outcome type. Always ``exit``. Required. EXIT.""" - exit_code: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Exit code from the shell process. Required.""" - - @overload - def __init__( - self, - *, - exit_code: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = FunctionShellCallOutputOutcomeType.EXIT # type: ignore - - -class FunctionShellCallOutputOutcomeParam(_Model): - """Shell call outcome. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - FunctionShellCallOutputExitOutcomeParam, FunctionShellCallOutputTimeoutOutcomeParam - - :ivar type: Required. Known values are: "timeout" and "exit". - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.FunctionShellCallOutputOutcomeParamType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"timeout\" and \"exit\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class FunctionShellCallOutputExitOutcomeParam(FunctionShellCallOutputOutcomeParam, discriminator="exit"): - """Shell call exit outcome. - - :ivar type: The outcome type. Always ``exit``. Required. EXIT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.EXIT - :ivar exit_code: The exit code returned by the shell process. Required. - :vartype exit_code: int - """ - - type: Literal[FunctionShellCallOutputOutcomeParamType.EXIT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The outcome type. Always ``exit``. Required. EXIT.""" - exit_code: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The exit code returned by the shell process. Required.""" - - @overload - def __init__( - self, - *, - exit_code: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = FunctionShellCallOutputOutcomeParamType.EXIT # type: ignore - - -class FunctionShellCallOutputItemParam(Item, discriminator="shell_call_output"): - """Shell tool call output. - - :ivar id: - :vartype id: str - :ivar call_id: The unique ID of the shell tool call generated by the model. Required. - :vartype call_id: str - :ivar type: The type of the item. Always ``shell_call_output``. Required. SHELL_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.SHELL_CALL_OUTPUT - :ivar output: Captured chunks of stdout and stderr output, along with their associated - outcomes. Required. - :vartype output: - list[~azure.ai.agentserver.responses.models.models.FunctionShellCallOutputContentParam] - :ivar status: Known values are: "in_progress", "completed", and "incomplete". - :vartype status: str or - ~azure.ai.agentserver.responses.models.models.FunctionShellCallItemStatus - :ivar max_output_length: - :vartype max_output_length: int - """ - - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the shell tool call generated by the model. Required.""" - type: Literal[ItemType.SHELL_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``shell_call_output``. Required. SHELL_CALL_OUTPUT.""" - output: list["_models.FunctionShellCallOutputContentParam"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Captured chunks of stdout and stderr output, along with their associated outcomes. Required.""" - status: Optional[Union[str, "_models.FunctionShellCallItemStatus"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Known values are: \"in_progress\", \"completed\", and \"incomplete\".""" - max_output_length: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - call_id: str, - output: list["_models.FunctionShellCallOutputContentParam"], - id: Optional[str] = None, # pylint: disable=redefined-builtin - status: Optional[Union[str, "_models.FunctionShellCallItemStatus"]] = None, - max_output_length: Optional[int] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.SHELL_CALL_OUTPUT # type: ignore - - -class FunctionShellCallOutputTimeoutOutcome(FunctionShellCallOutputOutcome, discriminator="timeout"): - """Shell call timeout outcome. - - :ivar type: The outcome type. Always ``timeout``. Required. TIMEOUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.TIMEOUT - """ - - type: Literal[FunctionShellCallOutputOutcomeType.TIMEOUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The outcome type. Always ``timeout``. Required. TIMEOUT.""" - - @overload - def __init__( - self, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = FunctionShellCallOutputOutcomeType.TIMEOUT # type: ignore - - -class FunctionShellCallOutputTimeoutOutcomeParam( - FunctionShellCallOutputOutcomeParam, discriminator="timeout" -): # pylint: disable=name-too-long - """Shell call timeout outcome. - - :ivar type: The outcome type. Always ``timeout``. Required. TIMEOUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.TIMEOUT - """ - - type: Literal[FunctionShellCallOutputOutcomeParamType.TIMEOUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The outcome type. Always ``timeout``. Required. TIMEOUT.""" - - @overload - def __init__( - self, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = FunctionShellCallOutputOutcomeParamType.TIMEOUT # type: ignore - - -class FunctionShellToolParam(Tool, discriminator="shell"): - """Shell tool. - - :ivar type: The type of the shell tool. Always ``shell``. Required. SHELL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.SHELL - :ivar environment: - :vartype environment: - ~azure.ai.agentserver.responses.models.models.FunctionShellToolParamEnvironment - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - """ - - type: Literal[ToolType.SHELL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the shell tool. Always ``shell``. Required. SHELL.""" - environment: Optional["_models.FunctionShellToolParamEnvironment"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - - @overload - def __init__( - self, - *, - environment: Optional["_models.FunctionShellToolParamEnvironment"] = None, - name: Optional[str] = None, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.SHELL # type: ignore - - -class FunctionShellToolParamEnvironmentContainerReferenceParam( - FunctionShellToolParamEnvironment, discriminator="container_reference" -): # pylint: disable=name-too-long - """FunctionShellToolParamEnvironmentContainerReferenceParam. - - :ivar type: References a container created with the /v1/containers endpoint. Required. - CONTAINER_REFERENCE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CONTAINER_REFERENCE - :ivar container_id: The ID of the referenced container. Required. - :vartype container_id: str - """ - - type: Literal[FunctionShellToolParamEnvironmentType.CONTAINER_REFERENCE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """References a container created with the /v1/containers endpoint. Required. CONTAINER_REFERENCE.""" - container_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the referenced container. Required.""" - - @overload - def __init__( - self, - *, - container_id: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = FunctionShellToolParamEnvironmentType.CONTAINER_REFERENCE # type: ignore - - -class FunctionShellToolParamEnvironmentLocalEnvironmentParam( - FunctionShellToolParamEnvironment, discriminator="local" -): # pylint: disable=name-too-long - """FunctionShellToolParamEnvironmentLocalEnvironmentParam. - - :ivar type: Use a local computer environment. Required. LOCAL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.LOCAL - :ivar skills: An optional list of skills. - :vartype skills: list[~azure.ai.agentserver.responses.models.models.LocalSkillParam] - """ - - type: Literal[FunctionShellToolParamEnvironmentType.LOCAL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Use a local computer environment. Required. LOCAL.""" - skills: Optional[list["_models.LocalSkillParam"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """An optional list of skills.""" - - @overload - def __init__( - self, - *, - skills: Optional[list["_models.LocalSkillParam"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = FunctionShellToolParamEnvironmentType.LOCAL # type: ignore - - -class FunctionTool(Tool, discriminator="function"): - """Function. - - :ivar type: The type of the function tool. Always ``function``. Required. FUNCTION. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.FUNCTION - :ivar name: The name of the function to call. Required. - :vartype name: str - :ivar description: - :vartype description: str - :ivar parameters: Required. - :vartype parameters: dict[str, any] - :ivar strict: Required. - :vartype strict: bool - """ - - type: Literal[ToolType.FUNCTION] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the function tool. Always ``function``. Required. FUNCTION.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the function to call. Required.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - parameters: dict[str, Any] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - strict: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - name: str, - parameters: dict[str, Any], - strict: bool, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.FUNCTION # type: ignore - - -class ItemField(_Model): - """An item representing a message, tool call, tool output, reasoning, or other response element. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ItemFieldApplyPatchToolCall, ItemFieldApplyPatchToolCallOutput, - ItemFieldCodeInterpreterToolCall, ItemFieldCompactionBody, ItemFieldComputerToolCall, - ItemFieldComputerToolCallOutputResource, ItemFieldCustomToolCall, - ItemFieldCustomToolCallOutput, ItemFieldFileSearchToolCall, ItemFieldFunctionToolCall, - FunctionToolCallOutput, ItemFieldImageGenToolCall, ItemFieldLocalShellToolCall, - ItemFieldLocalShellToolCallOutput, ItemFieldMcpApprovalRequest, - ItemFieldMcpApprovalResponseResource, ItemFieldMcpToolCall, ItemFieldMcpListTools, - ItemFieldMessage, ItemFieldReasoningItem, ItemFieldFunctionShellCall, - ItemFieldFunctionShellCallOutput, ItemFieldWebSearchToolCall - - :ivar type: Required. Known values are: "message", "function_call", "function_call_output", - "file_search_call", "web_search_call", "image_generation_call", "computer_call", - "computer_call_output", "reasoning", "compaction", "code_interpreter_call", "local_shell_call", - "local_shell_call_output", "shell_call", "shell_call_output", "apply_patch_call", - "apply_patch_call_output", "mcp_list_tools", "mcp_approval_request", "mcp_approval_response", - "mcp_call", "custom_tool_call", and "custom_tool_call_output". - :vartype type: str or ~azure.ai.agentserver.responses.models.models.ItemFieldType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"message\", \"function_call\", \"function_call_output\", - \"file_search_call\", \"web_search_call\", \"image_generation_call\", \"computer_call\", - \"computer_call_output\", \"reasoning\", \"compaction\", \"code_interpreter_call\", - \"local_shell_call\", \"local_shell_call_output\", \"shell_call\", \"shell_call_output\", - \"apply_patch_call\", \"apply_patch_call_output\", \"mcp_list_tools\", - \"mcp_approval_request\", \"mcp_approval_response\", \"mcp_call\", \"custom_tool_call\", and - \"custom_tool_call_output\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class FunctionToolCallOutput(ItemField, discriminator="function_call_output"): - """Function tool call output. - - :ivar id: The unique ID of the function tool call output. Populated when this item is returned - via API. - :vartype id: str - :ivar type: The type of the function tool call output. Always ``function_call_output``. - Required. FUNCTION_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.FUNCTION_CALL_OUTPUT - :ivar call_id: The unique ID of the function tool call generated by the model. Required. - :vartype call_id: str - :ivar output: The output from the function call generated by your code. Can be a string or an - list of output content. Required. Is either a str type or a [FunctionAndCustomToolCallOutput] - type. - :vartype output: str or - list[~azure.ai.agentserver.responses.models.models.FunctionAndCustomToolCallOutput] - :ivar status: The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. - Populated when items are returned via API. Is one of the following types: - Literal["in_progress"], Literal["completed"], Literal["incomplete"] - :vartype status: str or str or str - """ - - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the function tool call output. Populated when this item is returned via API.""" - type: Literal[ItemFieldType.FUNCTION_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the function tool call output. Always ``function_call_output``. Required. - FUNCTION_CALL_OUTPUT.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the function tool call generated by the model. Required.""" - output: Union[str, list["_models.FunctionAndCustomToolCallOutput"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The output from the function call generated by your code. Can be a string or an list of output - content. Required. Is either a str type or a [FunctionAndCustomToolCallOutput] type.""" - status: Optional[Literal["in_progress", "completed", "incomplete"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. Populated - when items are returned via API. Is one of the following types: Literal[\"in_progress\"], - Literal[\"completed\"], Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - call_id: str, - output: Union[str, list["_models.FunctionAndCustomToolCallOutput"]], - id: Optional[str] = None, # pylint: disable=redefined-builtin - status: Optional[Literal["in_progress", "completed", "incomplete"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.FUNCTION_CALL_OUTPUT # type: ignore - - -class FunctionToolCallOutputResource(OutputItem, discriminator="function_call_output"): - """FunctionToolCallOutputResource. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar id: The unique ID of the function tool call output. Populated when this item is returned - via API. - :vartype id: str - :ivar type: The type of the function tool call output. Always ``function_call_output``. - Required. FUNCTION_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.FUNCTION_CALL_OUTPUT - :ivar call_id: The unique ID of the function tool call generated by the model. Required. - :vartype call_id: str - :ivar output: The output from the function call generated by your code. Can be a string or an - list of output content. Required. Is either a str type or a [FunctionAndCustomToolCallOutput] - type. - :vartype output: str or - list[~azure.ai.agentserver.responses.models.models.FunctionAndCustomToolCallOutput] - :ivar status: The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. - Populated when items are returned via API. Is one of the following types: - Literal["in_progress"], Literal["completed"], Literal["incomplete"] - :vartype status: str or str or str - """ - - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the function tool call output. Populated when this item is returned via API.""" - type: Literal[OutputItemType.FUNCTION_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the function tool call output. Always ``function_call_output``. Required. - FUNCTION_CALL_OUTPUT.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the function tool call generated by the model. Required.""" - output: Union[str, list["_models.FunctionAndCustomToolCallOutput"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The output from the function call generated by your code. Can be a string or an list of output - content. Required. Is either a str type or a [FunctionAndCustomToolCallOutput] type.""" - status: Optional[Literal["in_progress", "completed", "incomplete"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. Populated - when items are returned via API. Is one of the following types: Literal[\"in_progress\"], - Literal[\"completed\"], Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - call_id: str, - output: Union[str, list["_models.FunctionAndCustomToolCallOutput"]], - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - id: Optional[str] = None, # pylint: disable=redefined-builtin - status: Optional[Literal["in_progress", "completed", "incomplete"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.FUNCTION_CALL_OUTPUT # type: ignore - - -class HybridSearchOptions(_Model): - """HybridSearchOptions. - - :ivar embedding_weight: The weight of the embedding in the reciprocal ranking fusion. Required. - :vartype embedding_weight: int - :ivar text_weight: The weight of the text in the reciprocal ranking fusion. Required. - :vartype text_weight: int - """ - - embedding_weight: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The weight of the embedding in the reciprocal ranking fusion. Required.""" - text_weight: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The weight of the text in the reciprocal ranking fusion. Required.""" - - @overload - def __init__( - self, - *, - embedding_weight: int, - text_weight: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ImageGenTool(Tool, discriminator="image_generation"): - """Image generation tool. - - :ivar type: The type of the image generation tool. Always ``image_generation``. Required. - IMAGE_GENERATION. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.IMAGE_GENERATION - :ivar model: Is one of the following types: Literal["gpt-image-1"], - Literal["gpt-image-1-mini"], Literal["gpt-image-1.5"], str - :vartype model: str or str or str or str - :ivar quality: The quality of the generated image. One of ``low``, ``medium``, ``high``, or - ``auto``. Default: ``auto``. Is one of the following types: Literal["low"], Literal["medium"], - Literal["high"], Literal["auto"] - :vartype quality: str or str or str or str - :ivar size: The size of the generated image. One of ``1024x1024``, ``1024x1536``, - ``1536x1024``, or ``auto``. Default: ``auto``. Is one of the following types: - Literal["1024x1024"], Literal["1024x1536"], Literal["1536x1024"], Literal["auto"] - :vartype size: str or str or str or str - :ivar output_format: The output format of the generated image. One of ``png``, ``webp``, or - ``jpeg``. Default: ``png``. Is one of the following types: Literal["png"], Literal["webp"], - Literal["jpeg"] - :vartype output_format: str or str or str - :ivar output_compression: Compression level for the output image. Default: 100. - :vartype output_compression: int - :ivar moderation: Moderation level for the generated image. Default: ``auto``. Is either a - Literal["auto"] type or a Literal["low"] type. - :vartype moderation: str or str - :ivar background: Background type for the generated image. One of ``transparent``, ``opaque``, - or ``auto``. Default: ``auto``. Is one of the following types: Literal["transparent"], - Literal["opaque"], Literal["auto"] - :vartype background: str or str or str - :ivar input_fidelity: Known values are: "high" and "low". - :vartype input_fidelity: str or ~azure.ai.agentserver.responses.models.models.InputFidelity - :ivar input_image_mask: Optional mask for inpainting. Contains ``image_url`` (string, optional) - and ``file_id`` (string, optional). - :vartype input_image_mask: - ~azure.ai.agentserver.responses.models.models.ImageGenToolInputImageMask - :ivar partial_images: Number of partial images to generate in streaming mode, from 0 (default - value) to 3. - :vartype partial_images: int - :ivar action: Whether to generate a new image or edit an existing image. Default: ``auto``. - Known values are: "generate", "edit", and "auto". - :vartype action: str or ~azure.ai.agentserver.responses.models.models.ImageGenActionEnum - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - """ - - type: Literal[ToolType.IMAGE_GENERATION] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the image generation tool. Always ``image_generation``. Required. IMAGE_GENERATION.""" - model: Optional[Union[Literal["gpt-image-1"], Literal["gpt-image-1-mini"], Literal["gpt-image-1.5"], str]] = ( - rest_field(visibility=["read", "create", "update", "delete", "query"]) - ) - """Is one of the following types: Literal[\"gpt-image-1\"], Literal[\"gpt-image-1-mini\"], - Literal[\"gpt-image-1.5\"], str""" - quality: Optional[Literal["low", "medium", "high", "auto"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The quality of the generated image. One of ``low``, ``medium``, ``high``, or ``auto``. Default: - ``auto``. Is one of the following types: Literal[\"low\"], Literal[\"medium\"], - Literal[\"high\"], Literal[\"auto\"]""" - size: Optional[Literal["1024x1024", "1024x1536", "1536x1024", "auto"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The size of the generated image. One of ``1024x1024``, ``1024x1536``, ``1536x1024``, or - ``auto``. Default: ``auto``. Is one of the following types: Literal[\"1024x1024\"], - Literal[\"1024x1536\"], Literal[\"1536x1024\"], Literal[\"auto\"]""" - output_format: Optional[Literal["png", "webp", "jpeg"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The output format of the generated image. One of ``png``, ``webp``, or ``jpeg``. Default: - ``png``. Is one of the following types: Literal[\"png\"], Literal[\"webp\"], Literal[\"jpeg\"]""" - output_compression: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Compression level for the output image. Default: 100.""" - moderation: Optional[Literal["auto", "low"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Moderation level for the generated image. Default: ``auto``. Is either a Literal[\"auto\"] type - or a Literal[\"low\"] type.""" - background: Optional[Literal["transparent", "opaque", "auto"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Background type for the generated image. One of ``transparent``, ``opaque``, or ``auto``. - Default: ``auto``. Is one of the following types: Literal[\"transparent\"], - Literal[\"opaque\"], Literal[\"auto\"]""" - input_fidelity: Optional[Union[str, "_models.InputFidelity"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Known values are: \"high\" and \"low\".""" - input_image_mask: Optional["_models.ImageGenToolInputImageMask"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Optional mask for inpainting. Contains ``image_url`` (string, optional) and ``file_id`` - (string, optional).""" - partial_images: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Number of partial images to generate in streaming mode, from 0 (default value) to 3.""" - action: Optional[Union[str, "_models.ImageGenActionEnum"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Whether to generate a new image or edit an existing image. Default: ``auto``. Known values are: - \"generate\", \"edit\", and \"auto\".""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - - @overload - def __init__( - self, - *, - model: Optional[ - Union[Literal["gpt-image-1"], Literal["gpt-image-1-mini"], Literal["gpt-image-1.5"], str] - ] = None, - quality: Optional[Literal["low", "medium", "high", "auto"]] = None, - size: Optional[Literal["1024x1024", "1024x1536", "1536x1024", "auto"]] = None, - output_format: Optional[Literal["png", "webp", "jpeg"]] = None, - output_compression: Optional[int] = None, - moderation: Optional[Literal["auto", "low"]] = None, - background: Optional[Literal["transparent", "opaque", "auto"]] = None, - input_fidelity: Optional[Union[str, "_models.InputFidelity"]] = None, - input_image_mask: Optional["_models.ImageGenToolInputImageMask"] = None, - partial_images: Optional[int] = None, - action: Optional[Union[str, "_models.ImageGenActionEnum"]] = None, - name: Optional[str] = None, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.IMAGE_GENERATION # type: ignore - - -class ImageGenToolInputImageMask(_Model): - """ImageGenToolInputImageMask. - - :ivar image_url: - :vartype image_url: str - :ivar file_id: - :vartype file_id: str - """ - - image_url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - file_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - image_url: Optional[str] = None, - file_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class InlineSkillParam(ContainerSkill, discriminator="inline"): - """InlineSkillParam. - - :ivar type: Defines an inline skill for this request. Required. INLINE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.INLINE - :ivar name: The name of the skill. Required. - :vartype name: str - :ivar description: The description of the skill. Required. - :vartype description: str - :ivar source: Inline skill payload. Required. - :vartype source: ~azure.ai.agentserver.responses.models.models.InlineSkillSourceParam - """ - - type: Literal[ContainerSkillType.INLINE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Defines an inline skill for this request. Required. INLINE.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the skill. Required.""" - description: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The description of the skill. Required.""" - source: "_models.InlineSkillSourceParam" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Inline skill payload. Required.""" - - @overload - def __init__( - self, - *, - name: str, - description: str, - source: "_models.InlineSkillSourceParam", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ContainerSkillType.INLINE # type: ignore - - -class InlineSkillSourceParam(_Model): - """Inline skill payload. - - :ivar type: The type of the inline skill source. Must be ``base64``. Required. Default value is - "base64". - :vartype type: str - :ivar media_type: The media type of the inline skill payload. Must be ``application/zip``. - Required. Default value is "application/zip". - :vartype media_type: str - :ivar data: Base64-encoded skill zip bundle. Required. - :vartype data: str - """ - - type: Literal["base64"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The type of the inline skill source. Must be ``base64``. Required. Default value is \"base64\".""" - media_type: Literal["application/zip"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The media type of the inline skill payload. Must be ``application/zip``. Required. Default - value is \"application/zip\".""" - data: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Base64-encoded skill zip bundle. Required.""" - - @overload - def __init__( - self, - *, - data: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["base64"] = "base64" - self.media_type: Literal["application/zip"] = "application/zip" - - -class InputFileContent(_Model): - """Input file. - - :ivar type: The type of the input item. Always ``input_file``. Required. Default value is - "input_file". - :vartype type: str - :ivar file_id: - :vartype file_id: str - :ivar filename: The name of the file to be sent to the model. - :vartype filename: str - :ivar file_url: The URL of the file to be sent to the model. - :vartype file_url: str - :ivar file_data: The content of the file to be sent to the model. - :vartype file_data: str - """ - - type: Literal["input_file"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The type of the input item. Always ``input_file``. Required. Default value is \"input_file\".""" - file_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - filename: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the file to be sent to the model.""" - file_url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The URL of the file to be sent to the model.""" - file_data: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The content of the file to be sent to the model.""" - - @overload - def __init__( - self, - *, - file_id: Optional[str] = None, - filename: Optional[str] = None, - file_url: Optional[str] = None, - file_data: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["input_file"] = "input_file" - - -class InputFileContentParam(_Model): - """Input file. - - :ivar type: The type of the input item. Always ``input_file``. Required. Default value is - "input_file". - :vartype type: str - :ivar file_id: - :vartype file_id: str - :ivar filename: - :vartype filename: str - :ivar file_data: - :vartype file_data: str - :ivar file_url: - :vartype file_url: str - """ - - type: Literal["input_file"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The type of the input item. Always ``input_file``. Required. Default value is \"input_file\".""" - file_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - filename: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - file_data: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - file_url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - file_id: Optional[str] = None, - filename: Optional[str] = None, - file_data: Optional[str] = None, - file_url: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["input_file"] = "input_file" - - -class InputImageContent(_Model): - """Input image. - - :ivar type: The type of the input item. Always ``input_image``. Required. Default value is - "input_image". - :vartype type: str - :ivar image_url: - :vartype image_url: str - :ivar file_id: - :vartype file_id: str - :ivar detail: The detail level of the image to be sent to the model. One of ``high``, ``low``, - or ``auto``. Defaults to ``auto``. Required. Known values are: "low", "high", and "auto". - :vartype detail: str or ~azure.ai.agentserver.responses.models.models.ImageDetail - """ - - type: Literal["input_image"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The type of the input item. Always ``input_image``. Required. Default value is \"input_image\".""" - image_url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - file_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - detail: Union[str, "_models.ImageDetail"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The detail level of the image to be sent to the model. One of ``high``, ``low``, or ``auto``. - Defaults to ``auto``. Required. Known values are: \"low\", \"high\", and \"auto\".""" - - @overload - def __init__( - self, - *, - detail: Union[str, "_models.ImageDetail"], - image_url: Optional[str] = None, - file_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["input_image"] = "input_image" - - -class InputImageContentParamAutoParam(_Model): - """Input image. - - :ivar type: The type of the input item. Always ``input_image``. Required. Default value is - "input_image". - :vartype type: str - :ivar image_url: - :vartype image_url: str - :ivar file_id: - :vartype file_id: str - :ivar detail: Known values are: "low", "high", and "auto". - :vartype detail: str or ~azure.ai.agentserver.responses.models.models.DetailEnum - """ - - type: Literal["input_image"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The type of the input item. Always ``input_image``. Required. Default value is \"input_image\".""" - image_url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - file_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - detail: Optional[Union[str, "_models.DetailEnum"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Known values are: \"low\", \"high\", and \"auto\".""" - - @overload - def __init__( - self, - *, - image_url: Optional[str] = None, - file_id: Optional[str] = None, - detail: Optional[Union[str, "_models.DetailEnum"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["input_image"] = "input_image" - - -class InputTextContent(_Model): - """Input text. - - :ivar type: The type of the input item. Always ``input_text``. Required. Default value is - "input_text". - :vartype type: str - :ivar text: The text input to the model. Required. - :vartype text: str - """ - - type: Literal["input_text"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The type of the input item. Always ``input_text``. Required. Default value is \"input_text\".""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The text input to the model. Required.""" - - @overload - def __init__( - self, - *, - text: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["input_text"] = "input_text" - - -class InputTextContentParam(_Model): - """Input text. - - :ivar type: The type of the input item. Always ``input_text``. Required. Default value is - "input_text". - :vartype type: str - :ivar text: The text input to the model. Required. - :vartype text: str - """ - - type: Literal["input_text"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The type of the input item. Always ``input_text``. Required. Default value is \"input_text\".""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The text input to the model. Required.""" - - @overload - def __init__( - self, - *, - text: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["input_text"] = "input_text" - - -class ItemCodeInterpreterToolCall(Item, discriminator="code_interpreter_call"): - """Code interpreter tool call. - - :ivar type: The type of the code interpreter tool call. Always ``code_interpreter_call``. - Required. CODE_INTERPRETER_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CODE_INTERPRETER_CALL - :ivar id: The unique ID of the code interpreter tool call. Required. - :vartype id: str - :ivar status: The status of the code interpreter tool call. Valid values are ``in_progress``, - ``completed``, ``incomplete``, ``interpreting``, and ``failed``. Required. Is one of the - following types: Literal["in_progress"], Literal["completed"], Literal["incomplete"], - Literal["interpreting"], Literal["failed"] - :vartype status: str or str or str or str or str - :ivar container_id: The ID of the container used to run the code. Required. - :vartype container_id: str - :ivar code: Required. - :vartype code: str - :ivar outputs: Required. - :vartype outputs: list[~azure.ai.agentserver.responses.models.models.CodeInterpreterOutputLogs - or ~azure.ai.agentserver.responses.models.models.CodeInterpreterOutputImage] - """ - - type: Literal[ItemType.CODE_INTERPRETER_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the code interpreter tool call. Always ``code_interpreter_call``. Required. - CODE_INTERPRETER_CALL.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the code interpreter tool call. Required.""" - status: Literal["in_progress", "completed", "incomplete", "interpreting", "failed"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the code interpreter tool call. Valid values are ``in_progress``, ``completed``, - ``incomplete``, ``interpreting``, and ``failed``. Required. Is one of the following types: - Literal[\"in_progress\"], Literal[\"completed\"], Literal[\"incomplete\"], - Literal[\"interpreting\"], Literal[\"failed\"]""" - container_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the container used to run the code. Required.""" - code: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - outputs: list[Union["_models.CodeInterpreterOutputLogs", "_models.CodeInterpreterOutputImage"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - status: Literal["in_progress", "completed", "incomplete", "interpreting", "failed"], - container_id: str, - code: str, - outputs: list[Union["_models.CodeInterpreterOutputLogs", "_models.CodeInterpreterOutputImage"]], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.CODE_INTERPRETER_CALL # type: ignore - - -class ItemComputerToolCall(Item, discriminator="computer_call"): - """Computer tool call. - - :ivar type: The type of the computer call. Always ``computer_call``. Required. COMPUTER_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.COMPUTER_CALL - :ivar id: The unique ID of the computer call. Required. - :vartype id: str - :ivar call_id: An identifier used when responding to the tool call with output. Required. - :vartype call_id: str - :ivar action: Required. - :vartype action: ~azure.ai.agentserver.responses.models.models.ComputerAction - :ivar pending_safety_checks: The pending safety checks for the computer call. Required. - :vartype pending_safety_checks: - list[~azure.ai.agentserver.responses.models.models.ComputerCallSafetyCheckParam] - :ivar status: The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. - Populated when items are returned via API. Required. Is one of the following types: - Literal["in_progress"], Literal["completed"], Literal["incomplete"] - :vartype status: str or str or str - """ - - type: Literal[ItemType.COMPUTER_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the computer call. Always ``computer_call``. Required. COMPUTER_CALL.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the computer call. Required.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """An identifier used when responding to the tool call with output. Required.""" - action: "_models.ComputerAction" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - pending_safety_checks: list["_models.ComputerCallSafetyCheckParam"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The pending safety checks for the computer call. Required.""" - status: Literal["in_progress", "completed", "incomplete"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. Populated - when items are returned via API. Required. Is one of the following types: - Literal[\"in_progress\"], Literal[\"completed\"], Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - call_id: str, - action: "_models.ComputerAction", - pending_safety_checks: list["_models.ComputerCallSafetyCheckParam"], - status: Literal["in_progress", "completed", "incomplete"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.COMPUTER_CALL # type: ignore - - -class ItemCustomToolCall(Item, discriminator="custom_tool_call"): - """Custom tool call. - - :ivar type: The type of the custom tool call. Always ``custom_tool_call``. Required. - CUSTOM_TOOL_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CUSTOM_TOOL_CALL - :ivar id: The unique ID of the custom tool call in the OpenAI platform. - :vartype id: str - :ivar call_id: An identifier used to map this custom tool call to a tool call output. Required. - :vartype call_id: str - :ivar name: The name of the custom tool being called. Required. - :vartype name: str - :ivar input: The input for the custom tool call generated by the model. Required. - :vartype input: str - """ - - type: Literal[ItemType.CUSTOM_TOOL_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the custom tool call. Always ``custom_tool_call``. Required. CUSTOM_TOOL_CALL.""" - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the custom tool call in the OpenAI platform.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """An identifier used to map this custom tool call to a tool call output. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the custom tool being called. Required.""" - input: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The input for the custom tool call generated by the model. Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - name: str, - input: str, - id: Optional[str] = None, # pylint: disable=redefined-builtin - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.CUSTOM_TOOL_CALL # type: ignore - - -class ItemCustomToolCallOutput(Item, discriminator="custom_tool_call_output"): - """Custom tool call output. - - :ivar type: The type of the custom tool call output. Always ``custom_tool_call_output``. - Required. CUSTOM_TOOL_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CUSTOM_TOOL_CALL_OUTPUT - :ivar id: The unique ID of the custom tool call output in the OpenAI platform. - :vartype id: str - :ivar call_id: The call ID, used to map this custom tool call output to a custom tool call. - Required. - :vartype call_id: str - :ivar output: The output from the custom tool call generated by your code. Can be a string or - an list of output content. Required. Is either a str type or a - [FunctionAndCustomToolCallOutput] type. - :vartype output: str or - list[~azure.ai.agentserver.responses.models.models.FunctionAndCustomToolCallOutput] - """ - - type: Literal[ItemType.CUSTOM_TOOL_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the custom tool call output. Always ``custom_tool_call_output``. Required. - CUSTOM_TOOL_CALL_OUTPUT.""" - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the custom tool call output in the OpenAI platform.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The call ID, used to map this custom tool call output to a custom tool call. Required.""" - output: Union[str, list["_models.FunctionAndCustomToolCallOutput"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The output from the custom tool call generated by your code. Can be a string or an list of - output content. Required. Is either a str type or a [FunctionAndCustomToolCallOutput] type.""" - - @overload - def __init__( - self, - *, - call_id: str, - output: Union[str, list["_models.FunctionAndCustomToolCallOutput"]], - id: Optional[str] = None, # pylint: disable=redefined-builtin - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.CUSTOM_TOOL_CALL_OUTPUT # type: ignore - - -class ItemFieldApplyPatchToolCall(ItemField, discriminator="apply_patch_call"): - """Apply patch tool call. - - :ivar type: The type of the item. Always ``apply_patch_call``. Required. APPLY_PATCH_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.APPLY_PATCH_CALL - :ivar id: The unique ID of the apply patch tool call. Populated when this item is returned via - API. Required. - :vartype id: str - :ivar call_id: The unique ID of the apply patch tool call generated by the model. Required. - :vartype call_id: str - :ivar status: The status of the apply patch tool call. One of ``in_progress`` or ``completed``. - Required. Known values are: "in_progress" and "completed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ApplyPatchCallStatus - :ivar operation: Apply patch operation. Required. - :vartype operation: ~azure.ai.agentserver.responses.models.models.ApplyPatchFileOperation - :ivar created_by: The ID of the entity that created this tool call. - :vartype created_by: str - """ - - type: Literal[ItemFieldType.APPLY_PATCH_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``apply_patch_call``. Required. APPLY_PATCH_CALL.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the apply patch tool call. Populated when this item is returned via API. - Required.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the apply patch tool call generated by the model. Required.""" - status: Union[str, "_models.ApplyPatchCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the apply patch tool call. One of ``in_progress`` or ``completed``. Required. - Known values are: \"in_progress\" and \"completed\".""" - operation: "_models.ApplyPatchFileOperation" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Apply patch operation. Required.""" - created_by: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the entity that created this tool call.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - call_id: str, - status: Union[str, "_models.ApplyPatchCallStatus"], - operation: "_models.ApplyPatchFileOperation", - created_by: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.APPLY_PATCH_CALL # type: ignore - - -class ItemFieldApplyPatchToolCallOutput(ItemField, discriminator="apply_patch_call_output"): - """Apply patch tool call output. - - :ivar type: The type of the item. Always ``apply_patch_call_output``. Required. - APPLY_PATCH_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.APPLY_PATCH_CALL_OUTPUT - :ivar id: The unique ID of the apply patch tool call output. Populated when this item is - returned via API. Required. - :vartype id: str - :ivar call_id: The unique ID of the apply patch tool call generated by the model. Required. - :vartype call_id: str - :ivar status: The status of the apply patch tool call output. One of ``completed`` or - ``failed``. Required. Known values are: "completed" and "failed". - :vartype status: str or - ~azure.ai.agentserver.responses.models.models.ApplyPatchCallOutputStatus - :ivar output: - :vartype output: str - :ivar created_by: The ID of the entity that created this tool call output. - :vartype created_by: str - """ - - type: Literal[ItemFieldType.APPLY_PATCH_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``apply_patch_call_output``. Required. APPLY_PATCH_CALL_OUTPUT.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the apply patch tool call output. Populated when this item is returned via - API. Required.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the apply patch tool call generated by the model. Required.""" - status: Union[str, "_models.ApplyPatchCallOutputStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the apply patch tool call output. One of ``completed`` or ``failed``. Required. - Known values are: \"completed\" and \"failed\".""" - output: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - created_by: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the entity that created this tool call output.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - call_id: str, - status: Union[str, "_models.ApplyPatchCallOutputStatus"], - output: Optional[str] = None, - created_by: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.APPLY_PATCH_CALL_OUTPUT # type: ignore - - -class ItemFieldCodeInterpreterToolCall(ItemField, discriminator="code_interpreter_call"): - """Code interpreter tool call. - - :ivar type: The type of the code interpreter tool call. Always ``code_interpreter_call``. - Required. CODE_INTERPRETER_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CODE_INTERPRETER_CALL - :ivar id: The unique ID of the code interpreter tool call. Required. - :vartype id: str - :ivar status: The status of the code interpreter tool call. Valid values are ``in_progress``, - ``completed``, ``incomplete``, ``interpreting``, and ``failed``. Required. Is one of the - following types: Literal["in_progress"], Literal["completed"], Literal["incomplete"], - Literal["interpreting"], Literal["failed"] - :vartype status: str or str or str or str or str - :ivar container_id: The ID of the container used to run the code. Required. - :vartype container_id: str - :ivar code: Required. - :vartype code: str - :ivar outputs: Required. - :vartype outputs: list[~azure.ai.agentserver.responses.models.models.CodeInterpreterOutputLogs - or ~azure.ai.agentserver.responses.models.models.CodeInterpreterOutputImage] - """ - - type: Literal[ItemFieldType.CODE_INTERPRETER_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the code interpreter tool call. Always ``code_interpreter_call``. Required. - CODE_INTERPRETER_CALL.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the code interpreter tool call. Required.""" - status: Literal["in_progress", "completed", "incomplete", "interpreting", "failed"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the code interpreter tool call. Valid values are ``in_progress``, ``completed``, - ``incomplete``, ``interpreting``, and ``failed``. Required. Is one of the following types: - Literal[\"in_progress\"], Literal[\"completed\"], Literal[\"incomplete\"], - Literal[\"interpreting\"], Literal[\"failed\"]""" - container_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the container used to run the code. Required.""" - code: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - outputs: list[Union["_models.CodeInterpreterOutputLogs", "_models.CodeInterpreterOutputImage"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - status: Literal["in_progress", "completed", "incomplete", "interpreting", "failed"], - container_id: str, - code: str, - outputs: list[Union["_models.CodeInterpreterOutputLogs", "_models.CodeInterpreterOutputImage"]], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.CODE_INTERPRETER_CALL # type: ignore - - -class ItemFieldCompactionBody(ItemField, discriminator="compaction"): - """Compaction item. - - :ivar type: The type of the item. Always ``compaction``. Required. COMPACTION. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.COMPACTION - :ivar id: The unique ID of the compaction item. Required. - :vartype id: str - :ivar encrypted_content: The encrypted content that was produced by compaction. Required. - :vartype encrypted_content: str - :ivar created_by: The identifier of the actor that created the item. - :vartype created_by: str - """ - - type: Literal[ItemFieldType.COMPACTION] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``compaction``. Required. COMPACTION.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the compaction item. Required.""" - encrypted_content: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The encrypted content that was produced by compaction. Required.""" - created_by: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The identifier of the actor that created the item.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - encrypted_content: str, - created_by: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.COMPACTION # type: ignore - - -class ItemFieldComputerToolCall(ItemField, discriminator="computer_call"): - """Computer tool call. - - :ivar type: The type of the computer call. Always ``computer_call``. Required. COMPUTER_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.COMPUTER_CALL - :ivar id: The unique ID of the computer call. Required. - :vartype id: str - :ivar call_id: An identifier used when responding to the tool call with output. Required. - :vartype call_id: str - :ivar action: Required. - :vartype action: ~azure.ai.agentserver.responses.models.models.ComputerAction - :ivar pending_safety_checks: The pending safety checks for the computer call. Required. - :vartype pending_safety_checks: - list[~azure.ai.agentserver.responses.models.models.ComputerCallSafetyCheckParam] - :ivar status: The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. - Populated when items are returned via API. Required. Is one of the following types: - Literal["in_progress"], Literal["completed"], Literal["incomplete"] - :vartype status: str or str or str - """ - - type: Literal[ItemFieldType.COMPUTER_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the computer call. Always ``computer_call``. Required. COMPUTER_CALL.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the computer call. Required.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """An identifier used when responding to the tool call with output. Required.""" - action: "_models.ComputerAction" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - pending_safety_checks: list["_models.ComputerCallSafetyCheckParam"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The pending safety checks for the computer call. Required.""" - status: Literal["in_progress", "completed", "incomplete"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. Populated - when items are returned via API. Required. Is one of the following types: - Literal[\"in_progress\"], Literal[\"completed\"], Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - call_id: str, - action: "_models.ComputerAction", - pending_safety_checks: list["_models.ComputerCallSafetyCheckParam"], - status: Literal["in_progress", "completed", "incomplete"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.COMPUTER_CALL # type: ignore - - -class ItemFieldComputerToolCallOutputResource(ItemField, discriminator="computer_call_output"): - """ItemFieldComputerToolCallOutputResource. - - :ivar type: The type of the computer tool call output. Always ``computer_call_output``. - Required. COMPUTER_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.COMPUTER_CALL_OUTPUT - :ivar id: The ID of the computer tool call output. - :vartype id: str - :ivar call_id: The ID of the computer tool call that produced the output. Required. - :vartype call_id: str - :ivar acknowledged_safety_checks: The safety checks reported by the API that have been - acknowledged by the developer. - :vartype acknowledged_safety_checks: - list[~azure.ai.agentserver.responses.models.models.ComputerCallSafetyCheckParam] - :ivar output: Required. - :vartype output: ~azure.ai.agentserver.responses.models.models.ComputerScreenshotImage - :ivar status: The status of the message input. One of ``in_progress``, ``completed``, or - ``incomplete``. Populated when input items are returned via API. Is one of the following types: - Literal["in_progress"], Literal["completed"], Literal["incomplete"] - :vartype status: str or str or str - """ - - type: Literal[ItemFieldType.COMPUTER_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the computer tool call output. Always ``computer_call_output``. Required. - COMPUTER_CALL_OUTPUT.""" - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the computer tool call output.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the computer tool call that produced the output. Required.""" - acknowledged_safety_checks: Optional[list["_models.ComputerCallSafetyCheckParam"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The safety checks reported by the API that have been acknowledged by the developer.""" - output: "_models.ComputerScreenshotImage" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - status: Optional[Literal["in_progress", "completed", "incomplete"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the message input. One of ``in_progress``, ``completed``, or ``incomplete``. - Populated when input items are returned via API. Is one of the following types: - Literal[\"in_progress\"], Literal[\"completed\"], Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - call_id: str, - output: "_models.ComputerScreenshotImage", - id: Optional[str] = None, # pylint: disable=redefined-builtin - acknowledged_safety_checks: Optional[list["_models.ComputerCallSafetyCheckParam"]] = None, - status: Optional[Literal["in_progress", "completed", "incomplete"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.COMPUTER_CALL_OUTPUT # type: ignore - - -class ItemFieldCustomToolCall(ItemField, discriminator="custom_tool_call"): - """Custom tool call. - - :ivar type: The type of the custom tool call. Always ``custom_tool_call``. Required. - CUSTOM_TOOL_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CUSTOM_TOOL_CALL - :ivar id: The unique ID of the custom tool call in the OpenAI platform. - :vartype id: str - :ivar call_id: An identifier used to map this custom tool call to a tool call output. Required. - :vartype call_id: str - :ivar name: The name of the custom tool being called. Required. - :vartype name: str - :ivar input: The input for the custom tool call generated by the model. Required. - :vartype input: str - """ - - type: Literal[ItemFieldType.CUSTOM_TOOL_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the custom tool call. Always ``custom_tool_call``. Required. CUSTOM_TOOL_CALL.""" - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the custom tool call in the OpenAI platform.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """An identifier used to map this custom tool call to a tool call output. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the custom tool being called. Required.""" - input: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The input for the custom tool call generated by the model. Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - name: str, - input: str, - id: Optional[str] = None, # pylint: disable=redefined-builtin - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.CUSTOM_TOOL_CALL # type: ignore - - -class ItemFieldCustomToolCallOutput(ItemField, discriminator="custom_tool_call_output"): - """Custom tool call output. - - :ivar type: The type of the custom tool call output. Always ``custom_tool_call_output``. - Required. CUSTOM_TOOL_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CUSTOM_TOOL_CALL_OUTPUT - :ivar id: The unique ID of the custom tool call output in the OpenAI platform. - :vartype id: str - :ivar call_id: The call ID, used to map this custom tool call output to a custom tool call. - Required. - :vartype call_id: str - :ivar output: The output from the custom tool call generated by your code. Can be a string or - an list of output content. Required. Is either a str type or a - [FunctionAndCustomToolCallOutput] type. - :vartype output: str or - list[~azure.ai.agentserver.responses.models.models.FunctionAndCustomToolCallOutput] - """ - - type: Literal[ItemFieldType.CUSTOM_TOOL_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the custom tool call output. Always ``custom_tool_call_output``. Required. - CUSTOM_TOOL_CALL_OUTPUT.""" - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the custom tool call output in the OpenAI platform.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The call ID, used to map this custom tool call output to a custom tool call. Required.""" - output: Union[str, list["_models.FunctionAndCustomToolCallOutput"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The output from the custom tool call generated by your code. Can be a string or an list of - output content. Required. Is either a str type or a [FunctionAndCustomToolCallOutput] type.""" - - @overload - def __init__( - self, - *, - call_id: str, - output: Union[str, list["_models.FunctionAndCustomToolCallOutput"]], - id: Optional[str] = None, # pylint: disable=redefined-builtin - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.CUSTOM_TOOL_CALL_OUTPUT # type: ignore - - -class ItemFieldFileSearchToolCall(ItemField, discriminator="file_search_call"): - """File search tool call. - - :ivar id: The unique ID of the file search tool call. Required. - :vartype id: str - :ivar type: The type of the file search tool call. Always ``file_search_call``. Required. - FILE_SEARCH_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.FILE_SEARCH_CALL - :ivar status: The status of the file search tool call. One of ``in_progress``, ``searching``, - ``incomplete`` or ``failed``,. Required. Is one of the following types: Literal["in_progress"], - Literal["searching"], Literal["completed"], Literal["incomplete"], Literal["failed"] - :vartype status: str or str or str or str or str - :ivar queries: The queries used to search for files. Required. - :vartype queries: list[str] - :ivar results: - :vartype results: list[~azure.ai.agentserver.responses.models.models.FileSearchToolCallResults] - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the file search tool call. Required.""" - type: Literal[ItemFieldType.FILE_SEARCH_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the file search tool call. Always ``file_search_call``. Required. FILE_SEARCH_CALL.""" - status: Literal["in_progress", "searching", "completed", "incomplete", "failed"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the file search tool call. One of ``in_progress``, ``searching``, ``incomplete`` - or ``failed``,. Required. Is one of the following types: Literal[\"in_progress\"], - Literal[\"searching\"], Literal[\"completed\"], Literal[\"incomplete\"], Literal[\"failed\"]""" - queries: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The queries used to search for files. Required.""" - results: Optional[list["_models.FileSearchToolCallResults"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - status: Literal["in_progress", "searching", "completed", "incomplete", "failed"], - queries: list[str], - results: Optional[list["_models.FileSearchToolCallResults"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.FILE_SEARCH_CALL # type: ignore - - -class ItemFieldFunctionShellCall(ItemField, discriminator="shell_call"): - """Shell tool call. - - :ivar type: The type of the item. Always ``shell_call``. Required. SHELL_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.SHELL_CALL - :ivar id: The unique ID of the shell tool call. Populated when this item is returned via API. - Required. - :vartype id: str - :ivar call_id: The unique ID of the shell tool call generated by the model. Required. - :vartype call_id: str - :ivar action: The shell commands and limits that describe how to run the tool call. Required. - :vartype action: ~azure.ai.agentserver.responses.models.models.FunctionShellAction - :ivar status: The status of the shell call. One of ``in_progress``, ``completed``, or - ``incomplete``. Required. Known values are: "in_progress", "completed", and "incomplete". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.LocalShellCallStatus - :ivar environment: Required. - :vartype environment: - ~azure.ai.agentserver.responses.models.models.FunctionShellCallEnvironment - :ivar created_by: The ID of the entity that created this tool call. - :vartype created_by: str - """ - - type: Literal[ItemFieldType.SHELL_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``shell_call``. Required. SHELL_CALL.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the shell tool call. Populated when this item is returned via API. Required.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the shell tool call generated by the model. Required.""" - action: "_models.FunctionShellAction" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The shell commands and limits that describe how to run the tool call. Required.""" - status: Union[str, "_models.LocalShellCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the shell call. One of ``in_progress``, ``completed``, or ``incomplete``. - Required. Known values are: \"in_progress\", \"completed\", and \"incomplete\".""" - environment: "_models.FunctionShellCallEnvironment" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Required.""" - created_by: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the entity that created this tool call.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - call_id: str, - action: "_models.FunctionShellAction", - status: Union[str, "_models.LocalShellCallStatus"], - environment: "_models.FunctionShellCallEnvironment", - created_by: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.SHELL_CALL # type: ignore - - -class ItemFieldFunctionShellCallOutput(ItemField, discriminator="shell_call_output"): - """Shell call output. - - :ivar type: The type of the shell call output. Always ``shell_call_output``. Required. - SHELL_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.SHELL_CALL_OUTPUT - :ivar id: The unique ID of the shell call output. Populated when this item is returned via API. - Required. - :vartype id: str - :ivar call_id: The unique ID of the shell tool call generated by the model. Required. - :vartype call_id: str - :ivar status: The status of the shell call output. One of ``in_progress``, ``completed``, or - ``incomplete``. Required. Known values are: "in_progress", "completed", and "incomplete". - :vartype status: str or - ~azure.ai.agentserver.responses.models.models.LocalShellCallOutputStatusEnum - :ivar output: An array of shell call output contents. Required. - :vartype output: - list[~azure.ai.agentserver.responses.models.models.FunctionShellCallOutputContent] - :ivar max_output_length: Required. - :vartype max_output_length: int - :ivar created_by: The identifier of the actor that created the item. - :vartype created_by: str - """ - - type: Literal[ItemFieldType.SHELL_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the shell call output. Always ``shell_call_output``. Required. SHELL_CALL_OUTPUT.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the shell call output. Populated when this item is returned via API. Required.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the shell tool call generated by the model. Required.""" - status: Union[str, "_models.LocalShellCallOutputStatusEnum"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the shell call output. One of ``in_progress``, ``completed``, or ``incomplete``. - Required. Known values are: \"in_progress\", \"completed\", and \"incomplete\".""" - output: list["_models.FunctionShellCallOutputContent"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """An array of shell call output contents. Required.""" - max_output_length: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - created_by: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The identifier of the actor that created the item.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - call_id: str, - status: Union[str, "_models.LocalShellCallOutputStatusEnum"], - output: list["_models.FunctionShellCallOutputContent"], - max_output_length: int, - created_by: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.SHELL_CALL_OUTPUT # type: ignore - - -class ItemFieldFunctionToolCall(ItemField, discriminator="function_call"): - """Function tool call. - - :ivar id: The unique ID of the function tool call. - :vartype id: str - :ivar type: The type of the function tool call. Always ``function_call``. Required. - FUNCTION_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.FUNCTION_CALL - :ivar call_id: The unique ID of the function tool call generated by the model. Required. - :vartype call_id: str - :ivar name: The name of the function to run. Required. - :vartype name: str - :ivar arguments: A JSON string of the arguments to pass to the function. Required. - :vartype arguments: str - :ivar status: The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. - Populated when items are returned via API. Is one of the following types: - Literal["in_progress"], Literal["completed"], Literal["incomplete"] - :vartype status: str or str or str - """ - - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the function tool call.""" - type: Literal[ItemFieldType.FUNCTION_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the function tool call. Always ``function_call``. Required. FUNCTION_CALL.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the function tool call generated by the model. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the function to run. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of the arguments to pass to the function. Required.""" - status: Optional[Literal["in_progress", "completed", "incomplete"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. Populated - when items are returned via API. Is one of the following types: Literal[\"in_progress\"], - Literal[\"completed\"], Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - call_id: str, - name: str, - arguments: str, - id: Optional[str] = None, # pylint: disable=redefined-builtin - status: Optional[Literal["in_progress", "completed", "incomplete"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.FUNCTION_CALL # type: ignore - - -class ItemFieldImageGenToolCall(ItemField, discriminator="image_generation_call"): - """Image generation call. - - :ivar type: The type of the image generation call. Always ``image_generation_call``. Required. - IMAGE_GENERATION_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.IMAGE_GENERATION_CALL - :ivar id: The unique ID of the image generation call. Required. - :vartype id: str - :ivar status: The status of the image generation call. Required. Is one of the following types: - Literal["in_progress"], Literal["completed"], Literal["generating"], Literal["failed"] - :vartype status: str or str or str or str - :ivar result: Required. - :vartype result: str - """ - - type: Literal[ItemFieldType.IMAGE_GENERATION_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the image generation call. Always ``image_generation_call``. Required. - IMAGE_GENERATION_CALL.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the image generation call. Required.""" - status: Literal["in_progress", "completed", "generating", "failed"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the image generation call. Required. Is one of the following types: - Literal[\"in_progress\"], Literal[\"completed\"], Literal[\"generating\"], Literal[\"failed\"]""" - result: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - status: Literal["in_progress", "completed", "generating", "failed"], - result: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.IMAGE_GENERATION_CALL # type: ignore - - -class ItemFieldLocalShellToolCall(ItemField, discriminator="local_shell_call"): - """Local shell call. - - :ivar type: The type of the local shell call. Always ``local_shell_call``. Required. - LOCAL_SHELL_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.LOCAL_SHELL_CALL - :ivar id: The unique ID of the local shell call. Required. - :vartype id: str - :ivar call_id: The unique ID of the local shell tool call generated by the model. Required. - :vartype call_id: str - :ivar action: Required. - :vartype action: ~azure.ai.agentserver.responses.models.models.LocalShellExecAction - :ivar status: The status of the local shell call. Required. Is one of the following types: - Literal["in_progress"], Literal["completed"], Literal["incomplete"] - :vartype status: str or str or str - """ - - type: Literal[ItemFieldType.LOCAL_SHELL_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the local shell call. Always ``local_shell_call``. Required. LOCAL_SHELL_CALL.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the local shell call. Required.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the local shell tool call generated by the model. Required.""" - action: "_models.LocalShellExecAction" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - status: Literal["in_progress", "completed", "incomplete"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the local shell call. Required. Is one of the following types: - Literal[\"in_progress\"], Literal[\"completed\"], Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - call_id: str, - action: "_models.LocalShellExecAction", - status: Literal["in_progress", "completed", "incomplete"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.LOCAL_SHELL_CALL # type: ignore - - -class ItemFieldLocalShellToolCallOutput(ItemField, discriminator="local_shell_call_output"): - """Local shell call output. - - :ivar type: The type of the local shell tool call output. Always ``local_shell_call_output``. - Required. LOCAL_SHELL_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.LOCAL_SHELL_CALL_OUTPUT - :ivar id: The unique ID of the local shell tool call generated by the model. Required. - :vartype id: str - :ivar output: A JSON string of the output of the local shell tool call. Required. - :vartype output: str - :ivar status: Is one of the following types: Literal["in_progress"], Literal["completed"], - Literal["incomplete"] - :vartype status: str or str or str - """ - - type: Literal[ItemFieldType.LOCAL_SHELL_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the local shell tool call output. Always ``local_shell_call_output``. Required. - LOCAL_SHELL_CALL_OUTPUT.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the local shell tool call generated by the model. Required.""" - output: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of the output of the local shell tool call. Required.""" - status: Optional[Literal["in_progress", "completed", "incomplete"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Is one of the following types: Literal[\"in_progress\"], Literal[\"completed\"], - Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - output: str, - status: Optional[Literal["in_progress", "completed", "incomplete"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.LOCAL_SHELL_CALL_OUTPUT # type: ignore - - -class ItemFieldMcpApprovalRequest(ItemField, discriminator="mcp_approval_request"): - """MCP approval request. - - :ivar type: The type of the item. Always ``mcp_approval_request``. Required. - MCP_APPROVAL_REQUEST. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MCP_APPROVAL_REQUEST - :ivar id: The unique ID of the approval request. Required. - :vartype id: str - :ivar server_label: The label of the MCP server making the request. Required. - :vartype server_label: str - :ivar name: The name of the tool to run. Required. - :vartype name: str - :ivar arguments: A JSON string of arguments for the tool. Required. - :vartype arguments: str - """ - - type: Literal[ItemFieldType.MCP_APPROVAL_REQUEST] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``mcp_approval_request``. Required. MCP_APPROVAL_REQUEST.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the approval request. Required.""" - server_label: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The label of the MCP server making the request. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the tool to run. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of arguments for the tool. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - server_label: str, - name: str, - arguments: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.MCP_APPROVAL_REQUEST # type: ignore - - -class ItemFieldMcpApprovalResponseResource(ItemField, discriminator="mcp_approval_response"): - """MCP approval response. - - :ivar type: The type of the item. Always ``mcp_approval_response``. Required. - MCP_APPROVAL_RESPONSE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MCP_APPROVAL_RESPONSE - :ivar id: The unique ID of the approval response. Required. - :vartype id: str - :ivar approval_request_id: The ID of the approval request being answered. Required. - :vartype approval_request_id: str - :ivar approve: Whether the request was approved. Required. - :vartype approve: bool - :ivar reason: - :vartype reason: str - """ - - type: Literal[ItemFieldType.MCP_APPROVAL_RESPONSE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``mcp_approval_response``. Required. MCP_APPROVAL_RESPONSE.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the approval response. Required.""" - approval_request_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the approval request being answered. Required.""" - approve: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Whether the request was approved. Required.""" - reason: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - approval_request_id: str, - approve: bool, - reason: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.MCP_APPROVAL_RESPONSE # type: ignore - - -class ItemFieldMcpListTools(ItemField, discriminator="mcp_list_tools"): - """MCP list tools. - - :ivar type: The type of the item. Always ``mcp_list_tools``. Required. MCP_LIST_TOOLS. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MCP_LIST_TOOLS - :ivar id: The unique ID of the list. Required. - :vartype id: str - :ivar server_label: The label of the MCP server. Required. - :vartype server_label: str - :ivar tools: The tools available on the server. Required. - :vartype tools: list[~azure.ai.agentserver.responses.models.models.MCPListToolsTool] - :ivar error: - :vartype error: str - """ - - type: Literal[ItemFieldType.MCP_LIST_TOOLS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``mcp_list_tools``. Required. MCP_LIST_TOOLS.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the list. Required.""" - server_label: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The label of the MCP server. Required.""" - tools: list["_models.MCPListToolsTool"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The tools available on the server. Required.""" - error: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - server_label: str, - tools: list["_models.MCPListToolsTool"], - error: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.MCP_LIST_TOOLS # type: ignore - - -class ItemFieldMcpToolCall(ItemField, discriminator="mcp_call"): - """MCP tool call. - - :ivar type: The type of the item. Always ``mcp_call``. Required. MCP_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MCP_CALL - :ivar id: The unique ID of the tool call. Required. - :vartype id: str - :ivar server_label: The label of the MCP server running the tool. Required. - :vartype server_label: str - :ivar name: The name of the tool that was run. Required. - :vartype name: str - :ivar arguments: A JSON string of the arguments passed to the tool. Required. - :vartype arguments: str - :ivar output: - :vartype output: str - :ivar error: - :vartype error: dict[str, any] - :ivar status: The status of the tool call. One of ``in_progress``, ``completed``, - ``incomplete``, ``calling``, or ``failed``. Known values are: "in_progress", "completed", - "incomplete", "calling", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.MCPToolCallStatus - :ivar approval_request_id: - :vartype approval_request_id: str - """ - - type: Literal[ItemFieldType.MCP_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``mcp_call``. Required. MCP_CALL.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call. Required.""" - server_label: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The label of the MCP server running the tool. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the tool that was run. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of the arguments passed to the tool. Required.""" - output: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - error: Optional[dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - status: Optional[Union[str, "_models.MCPToolCallStatus"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. One of ``in_progress``, ``completed``, ``incomplete``, - ``calling``, or ``failed``. Known values are: \"in_progress\", \"completed\", \"incomplete\", - \"calling\", and \"failed\".""" - approval_request_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - server_label: str, - name: str, - arguments: str, - output: Optional[str] = None, - error: Optional[dict[str, Any]] = None, - status: Optional[Union[str, "_models.MCPToolCallStatus"]] = None, - approval_request_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.MCP_CALL # type: ignore - - -class ItemFieldMessage(ItemField, discriminator="message"): - """Message. - - :ivar type: The type of the message. Always set to ``message``. Required. MESSAGE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MESSAGE - :ivar id: The unique ID of the message. Required. - :vartype id: str - :ivar status: The status of item. One of ``in_progress``, ``completed``, or ``incomplete``. - Populated when items are returned via API. Required. Known values are: "in_progress", - "completed", and "incomplete". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.MessageStatus - :ivar role: The role of the message. One of ``unknown``, ``user``, ``assistant``, ``system``, - ``critic``, ``discriminator``, ``developer``, or ``tool``. Required. Known values are: - "unknown", "user", "assistant", "system", "critic", "discriminator", "developer", and "tool". - :vartype role: str or ~azure.ai.agentserver.responses.models.models.MessageRole - :ivar content: The content of the message. Required. - :vartype content: list[~azure.ai.agentserver.responses.models.models.MessageContent] - """ - - type: Literal[ItemFieldType.MESSAGE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the message. Always set to ``message``. Required. MESSAGE.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the message. Required.""" - status: Union[str, "_models.MessageStatus"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The status of item. One of ``in_progress``, ``completed``, or ``incomplete``. Populated when - items are returned via API. Required. Known values are: \"in_progress\", \"completed\", and - \"incomplete\".""" - role: Union[str, "_models.MessageRole"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The role of the message. One of ``unknown``, ``user``, ``assistant``, ``system``, ``critic``, - ``discriminator``, ``developer``, or ``tool``. Required. Known values are: \"unknown\", - \"user\", \"assistant\", \"system\", \"critic\", \"discriminator\", \"developer\", and - \"tool\".""" - content: list["_models.MessageContent"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The content of the message. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - status: Union[str, "_models.MessageStatus"], - role: Union[str, "_models.MessageRole"], - content: list["_models.MessageContent"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.MESSAGE # type: ignore - - -class ItemFieldReasoningItem(ItemField, discriminator="reasoning"): - """Reasoning. - - :ivar type: The type of the object. Always ``reasoning``. Required. REASONING. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.REASONING - :ivar id: The unique identifier of the reasoning content. Required. - :vartype id: str - :ivar encrypted_content: - :vartype encrypted_content: str - :ivar summary: Reasoning summary content. Required. - :vartype summary: list[~azure.ai.agentserver.responses.models.models.SummaryTextContent] - :ivar content: Reasoning text content. - :vartype content: list[~azure.ai.agentserver.responses.models.models.ReasoningTextContent] - :ivar status: The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. - Populated when items are returned via API. Is one of the following types: - Literal["in_progress"], Literal["completed"], Literal["incomplete"] - :vartype status: str or str or str - """ - - type: Literal[ItemFieldType.REASONING] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the object. Always ``reasoning``. Required. REASONING.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique identifier of the reasoning content. Required.""" - encrypted_content: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - summary: list["_models.SummaryTextContent"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Reasoning summary content. Required.""" - content: Optional[list["_models.ReasoningTextContent"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Reasoning text content.""" - status: Optional[Literal["in_progress", "completed", "incomplete"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. Populated - when items are returned via API. Is one of the following types: Literal[\"in_progress\"], - Literal[\"completed\"], Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - summary: list["_models.SummaryTextContent"], - encrypted_content: Optional[str] = None, - content: Optional[list["_models.ReasoningTextContent"]] = None, - status: Optional[Literal["in_progress", "completed", "incomplete"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.REASONING # type: ignore - - -class ItemFieldWebSearchToolCall(ItemField, discriminator="web_search_call"): - """Web search tool call. - - :ivar id: The unique ID of the web search tool call. Required. - :vartype id: str - :ivar type: The type of the web search tool call. Always ``web_search_call``. Required. - WEB_SEARCH_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.WEB_SEARCH_CALL - :ivar status: The status of the web search tool call. Required. Is one of the following types: - Literal["in_progress"], Literal["searching"], Literal["completed"], Literal["failed"] - :vartype status: str or str or str or str - :ivar action: An object describing the specific action taken in this web search call. Includes - details on how the model used the web (search, open_page, find_in_page). Required. Is one of - the following types: WebSearchActionSearch, WebSearchActionOpenPage, WebSearchActionFind - :vartype action: ~azure.ai.agentserver.responses.models.models.WebSearchActionSearch or - ~azure.ai.agentserver.responses.models.models.WebSearchActionOpenPage or - ~azure.ai.agentserver.responses.models.models.WebSearchActionFind - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the web search tool call. Required.""" - type: Literal[ItemFieldType.WEB_SEARCH_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the web search tool call. Always ``web_search_call``. Required. WEB_SEARCH_CALL.""" - status: Literal["in_progress", "searching", "completed", "failed"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the web search tool call. Required. Is one of the following types: - Literal[\"in_progress\"], Literal[\"searching\"], Literal[\"completed\"], Literal[\"failed\"]""" - action: Union["_models.WebSearchActionSearch", "_models.WebSearchActionOpenPage", "_models.WebSearchActionFind"] = ( - rest_field(visibility=["read", "create", "update", "delete", "query"]) - ) - """An object describing the specific action taken in this web search call. Includes details on how - the model used the web (search, open_page, find_in_page). Required. Is one of the following - types: WebSearchActionSearch, WebSearchActionOpenPage, WebSearchActionFind""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - status: Literal["in_progress", "searching", "completed", "failed"], - action: Union[ - "_models.WebSearchActionSearch", "_models.WebSearchActionOpenPage", "_models.WebSearchActionFind" - ], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemFieldType.WEB_SEARCH_CALL # type: ignore - - -class ItemFileSearchToolCall(Item, discriminator="file_search_call"): - """File search tool call. - - :ivar id: The unique ID of the file search tool call. Required. - :vartype id: str - :ivar type: The type of the file search tool call. Always ``file_search_call``. Required. - FILE_SEARCH_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.FILE_SEARCH_CALL - :ivar status: The status of the file search tool call. One of ``in_progress``, ``searching``, - ``incomplete`` or ``failed``,. Required. Is one of the following types: Literal["in_progress"], - Literal["searching"], Literal["completed"], Literal["incomplete"], Literal["failed"] - :vartype status: str or str or str or str or str - :ivar queries: The queries used to search for files. Required. - :vartype queries: list[str] - :ivar results: - :vartype results: list[~azure.ai.agentserver.responses.models.models.FileSearchToolCallResults] - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the file search tool call. Required.""" - type: Literal[ItemType.FILE_SEARCH_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the file search tool call. Always ``file_search_call``. Required. FILE_SEARCH_CALL.""" - status: Literal["in_progress", "searching", "completed", "incomplete", "failed"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the file search tool call. One of ``in_progress``, ``searching``, ``incomplete`` - or ``failed``,. Required. Is one of the following types: Literal[\"in_progress\"], - Literal[\"searching\"], Literal[\"completed\"], Literal[\"incomplete\"], Literal[\"failed\"]""" - queries: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The queries used to search for files. Required.""" - results: Optional[list["_models.FileSearchToolCallResults"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - status: Literal["in_progress", "searching", "completed", "incomplete", "failed"], - queries: list[str], - results: Optional[list["_models.FileSearchToolCallResults"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.FILE_SEARCH_CALL # type: ignore - - -class ItemFunctionToolCall(Item, discriminator="function_call"): - """Function tool call. - - :ivar id: The unique ID of the function tool call. - :vartype id: str - :ivar type: The type of the function tool call. Always ``function_call``. Required. - FUNCTION_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.FUNCTION_CALL - :ivar call_id: The unique ID of the function tool call generated by the model. Required. - :vartype call_id: str - :ivar name: The name of the function to run. Required. - :vartype name: str - :ivar arguments: A JSON string of the arguments to pass to the function. Required. - :vartype arguments: str - :ivar status: The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. - Populated when items are returned via API. Is one of the following types: - Literal["in_progress"], Literal["completed"], Literal["incomplete"] - :vartype status: str or str or str - """ - - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the function tool call.""" - type: Literal[ItemType.FUNCTION_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the function tool call. Always ``function_call``. Required. FUNCTION_CALL.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the function tool call generated by the model. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the function to run. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of the arguments to pass to the function. Required.""" - status: Optional[Literal["in_progress", "completed", "incomplete"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. Populated - when items are returned via API. Is one of the following types: Literal[\"in_progress\"], - Literal[\"completed\"], Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - call_id: str, - name: str, - arguments: str, - id: Optional[str] = None, # pylint: disable=redefined-builtin - status: Optional[Literal["in_progress", "completed", "incomplete"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.FUNCTION_CALL # type: ignore - - -class ItemImageGenToolCall(Item, discriminator="image_generation_call"): - """Image generation call. - - :ivar type: The type of the image generation call. Always ``image_generation_call``. Required. - IMAGE_GENERATION_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.IMAGE_GENERATION_CALL - :ivar id: The unique ID of the image generation call. Required. - :vartype id: str - :ivar status: The status of the image generation call. Required. Is one of the following types: - Literal["in_progress"], Literal["completed"], Literal["generating"], Literal["failed"] - :vartype status: str or str or str or str - :ivar result: Required. - :vartype result: str - """ - - type: Literal[ItemType.IMAGE_GENERATION_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the image generation call. Always ``image_generation_call``. Required. - IMAGE_GENERATION_CALL.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the image generation call. Required.""" - status: Literal["in_progress", "completed", "generating", "failed"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the image generation call. Required. Is one of the following types: - Literal[\"in_progress\"], Literal[\"completed\"], Literal[\"generating\"], Literal[\"failed\"]""" - result: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - status: Literal["in_progress", "completed", "generating", "failed"], - result: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.IMAGE_GENERATION_CALL # type: ignore - - -class ItemLocalShellToolCall(Item, discriminator="local_shell_call"): - """Local shell call. - - :ivar type: The type of the local shell call. Always ``local_shell_call``. Required. - LOCAL_SHELL_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.LOCAL_SHELL_CALL - :ivar id: The unique ID of the local shell call. Required. - :vartype id: str - :ivar call_id: The unique ID of the local shell tool call generated by the model. Required. - :vartype call_id: str - :ivar action: Required. - :vartype action: ~azure.ai.agentserver.responses.models.models.LocalShellExecAction - :ivar status: The status of the local shell call. Required. Is one of the following types: - Literal["in_progress"], Literal["completed"], Literal["incomplete"] - :vartype status: str or str or str - """ - - type: Literal[ItemType.LOCAL_SHELL_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the local shell call. Always ``local_shell_call``. Required. LOCAL_SHELL_CALL.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the local shell call. Required.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the local shell tool call generated by the model. Required.""" - action: "_models.LocalShellExecAction" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - status: Literal["in_progress", "completed", "incomplete"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the local shell call. Required. Is one of the following types: - Literal[\"in_progress\"], Literal[\"completed\"], Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - call_id: str, - action: "_models.LocalShellExecAction", - status: Literal["in_progress", "completed", "incomplete"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.LOCAL_SHELL_CALL # type: ignore - - -class ItemLocalShellToolCallOutput(Item, discriminator="local_shell_call_output"): - """Local shell call output. - - :ivar type: The type of the local shell tool call output. Always ``local_shell_call_output``. - Required. LOCAL_SHELL_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.LOCAL_SHELL_CALL_OUTPUT - :ivar id: The unique ID of the local shell tool call generated by the model. Required. - :vartype id: str - :ivar output: A JSON string of the output of the local shell tool call. Required. - :vartype output: str - :ivar status: Is one of the following types: Literal["in_progress"], Literal["completed"], - Literal["incomplete"] - :vartype status: str or str or str - """ - - type: Literal[ItemType.LOCAL_SHELL_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the local shell tool call output. Always ``local_shell_call_output``. Required. - LOCAL_SHELL_CALL_OUTPUT.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the local shell tool call generated by the model. Required.""" - output: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of the output of the local shell tool call. Required.""" - status: Optional[Literal["in_progress", "completed", "incomplete"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Is one of the following types: Literal[\"in_progress\"], Literal[\"completed\"], - Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - output: str, - status: Optional[Literal["in_progress", "completed", "incomplete"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.LOCAL_SHELL_CALL_OUTPUT # type: ignore - - -class ItemMcpApprovalRequest(Item, discriminator="mcp_approval_request"): - """MCP approval request. - - :ivar type: The type of the item. Always ``mcp_approval_request``. Required. - MCP_APPROVAL_REQUEST. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MCP_APPROVAL_REQUEST - :ivar id: The unique ID of the approval request. Required. - :vartype id: str - :ivar server_label: The label of the MCP server making the request. Required. - :vartype server_label: str - :ivar name: The name of the tool to run. Required. - :vartype name: str - :ivar arguments: A JSON string of arguments for the tool. Required. - :vartype arguments: str - """ - - type: Literal[ItemType.MCP_APPROVAL_REQUEST] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``mcp_approval_request``. Required. MCP_APPROVAL_REQUEST.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the approval request. Required.""" - server_label: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The label of the MCP server making the request. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the tool to run. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of arguments for the tool. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - server_label: str, - name: str, - arguments: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.MCP_APPROVAL_REQUEST # type: ignore - - -class ItemMcpListTools(Item, discriminator="mcp_list_tools"): - """MCP list tools. - - :ivar type: The type of the item. Always ``mcp_list_tools``. Required. MCP_LIST_TOOLS. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MCP_LIST_TOOLS - :ivar id: The unique ID of the list. Required. - :vartype id: str - :ivar server_label: The label of the MCP server. Required. - :vartype server_label: str - :ivar tools: The tools available on the server. Required. - :vartype tools: list[~azure.ai.agentserver.responses.models.models.MCPListToolsTool] - :ivar error: - :vartype error: str - """ - - type: Literal[ItemType.MCP_LIST_TOOLS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``mcp_list_tools``. Required. MCP_LIST_TOOLS.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the list. Required.""" - server_label: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The label of the MCP server. Required.""" - tools: list["_models.MCPListToolsTool"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The tools available on the server. Required.""" - error: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - server_label: str, - tools: list["_models.MCPListToolsTool"], - error: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.MCP_LIST_TOOLS # type: ignore - - -class ItemMcpToolCall(Item, discriminator="mcp_call"): - """MCP tool call. - - :ivar type: The type of the item. Always ``mcp_call``. Required. MCP_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MCP_CALL - :ivar id: The unique ID of the tool call. Required. - :vartype id: str - :ivar server_label: The label of the MCP server running the tool. Required. - :vartype server_label: str - :ivar name: The name of the tool that was run. Required. - :vartype name: str - :ivar arguments: A JSON string of the arguments passed to the tool. Required. - :vartype arguments: str - :ivar output: - :vartype output: str - :ivar error: - :vartype error: dict[str, any] - :ivar status: The status of the tool call. One of ``in_progress``, ``completed``, - ``incomplete``, ``calling``, or ``failed``. Known values are: "in_progress", "completed", - "incomplete", "calling", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.MCPToolCallStatus - :ivar approval_request_id: - :vartype approval_request_id: str - """ - - type: Literal[ItemType.MCP_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``mcp_call``. Required. MCP_CALL.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call. Required.""" - server_label: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The label of the MCP server running the tool. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the tool that was run. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of the arguments passed to the tool. Required.""" - output: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - error: Optional[dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - status: Optional[Union[str, "_models.MCPToolCallStatus"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. One of ``in_progress``, ``completed``, ``incomplete``, - ``calling``, or ``failed``. Known values are: \"in_progress\", \"completed\", \"incomplete\", - \"calling\", and \"failed\".""" - approval_request_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - server_label: str, - name: str, - arguments: str, - output: Optional[str] = None, - error: Optional[dict[str, Any]] = None, - status: Optional[Union[str, "_models.MCPToolCallStatus"]] = None, - approval_request_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.MCP_CALL # type: ignore - - -class ItemMessage(Item, discriminator="message"): - """Message. - - :ivar type: The type of the message. Always set to ``message``. Required. MESSAGE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MESSAGE - :ivar role: The role of the message. One of ``unknown``, ``user``, ``assistant``, ``system``, - ``critic``, ``discriminator``, ``developer``, or ``tool``. Required. Known values are: - "unknown", "user", "assistant", "system", "critic", "discriminator", "developer", and "tool". - :vartype role: str or ~azure.ai.agentserver.responses.models.models.MessageRole - :ivar content: Required. Is either a str type or a [MessageContent] type. - :vartype content: str or list[~azure.ai.agentserver.responses.models.models.MessageContent] - """ - - type: Literal[ItemType.MESSAGE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the message. Always set to ``message``. Required. MESSAGE.""" - role: Union[str, "_models.MessageRole"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The role of the message. One of ``unknown``, ``user``, ``assistant``, ``system``, ``critic``, - ``discriminator``, ``developer``, or ``tool``. Required. Known values are: \"unknown\", - \"user\", \"assistant\", \"system\", \"critic\", \"discriminator\", \"developer\", and - \"tool\".""" - content: Union[str, list["_models.MessageContent"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Required. Is either a str type or a [MessageContent] type.""" - - @overload - def __init__( - self, - *, - role: Union[str, "_models.MessageRole"], - content: Union[str, list["_models.MessageContent"]], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.MESSAGE # type: ignore - - -class ItemOutputMessage(Item, discriminator="output_message"): - """Output message. - - :ivar id: The unique ID of the output message. Required. - :vartype id: str - :ivar type: The type of the output message. Always ``message``. Required. OUTPUT_MESSAGE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.OUTPUT_MESSAGE - :ivar role: The role of the output message. Always ``assistant``. Required. Default value is - "assistant". - :vartype role: str - :ivar content: The content of the output message. Required. - :vartype content: list[~azure.ai.agentserver.responses.models.models.OutputMessageContent] - :ivar status: The status of the message input. One of ``in_progress``, ``completed``, or - ``incomplete``. Populated when input items are returned via API. Required. Is one of the - following types: Literal["in_progress"], Literal["completed"], Literal["incomplete"] - :vartype status: str or str or str - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the output message. Required.""" - type: Literal[ItemType.OUTPUT_MESSAGE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the output message. Always ``message``. Required. OUTPUT_MESSAGE.""" - role: Literal["assistant"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The role of the output message. Always ``assistant``. Required. Default value is \"assistant\".""" - content: list["_models.OutputMessageContent"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The content of the output message. Required.""" - status: Literal["in_progress", "completed", "incomplete"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the message input. One of ``in_progress``, ``completed``, or ``incomplete``. - Populated when input items are returned via API. Required. Is one of the following types: - Literal[\"in_progress\"], Literal[\"completed\"], Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - content: list["_models.OutputMessageContent"], - status: Literal["in_progress", "completed", "incomplete"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.OUTPUT_MESSAGE # type: ignore - self.role: Literal["assistant"] = "assistant" - - -class ItemReasoningItem(Item, discriminator="reasoning"): - """Reasoning. - - :ivar type: The type of the object. Always ``reasoning``. Required. REASONING. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.REASONING - :ivar id: The unique identifier of the reasoning content. Required. - :vartype id: str - :ivar encrypted_content: - :vartype encrypted_content: str - :ivar summary: Reasoning summary content. Required. - :vartype summary: list[~azure.ai.agentserver.responses.models.models.SummaryTextContent] - :ivar content: Reasoning text content. - :vartype content: list[~azure.ai.agentserver.responses.models.models.ReasoningTextContent] - :ivar status: The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. - Populated when items are returned via API. Is one of the following types: - Literal["in_progress"], Literal["completed"], Literal["incomplete"] - :vartype status: str or str or str - """ - - type: Literal[ItemType.REASONING] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the object. Always ``reasoning``. Required. REASONING.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique identifier of the reasoning content. Required.""" - encrypted_content: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - summary: list["_models.SummaryTextContent"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Reasoning summary content. Required.""" - content: Optional[list["_models.ReasoningTextContent"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Reasoning text content.""" - status: Optional[Literal["in_progress", "completed", "incomplete"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. Populated - when items are returned via API. Is one of the following types: Literal[\"in_progress\"], - Literal[\"completed\"], Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - summary: list["_models.SummaryTextContent"], - encrypted_content: Optional[str] = None, - content: Optional[list["_models.ReasoningTextContent"]] = None, - status: Optional[Literal["in_progress", "completed", "incomplete"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.REASONING # type: ignore - - -class ItemReferenceParam(Item, discriminator="item_reference"): - """Item reference. - - :ivar type: The type of item to reference. Always ``item_reference``. Required. ITEM_REFERENCE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.ITEM_REFERENCE - :ivar id: The ID of the item to reference. Required. - :vartype id: str - """ - - type: Literal[ItemType.ITEM_REFERENCE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of item to reference. Always ``item_reference``. Required. ITEM_REFERENCE.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the item to reference. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.ITEM_REFERENCE # type: ignore - - -class ItemWebSearchToolCall(Item, discriminator="web_search_call"): - """Web search tool call. - - :ivar id: The unique ID of the web search tool call. Required. - :vartype id: str - :ivar type: The type of the web search tool call. Always ``web_search_call``. Required. - WEB_SEARCH_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.WEB_SEARCH_CALL - :ivar status: The status of the web search tool call. Required. Is one of the following types: - Literal["in_progress"], Literal["searching"], Literal["completed"], Literal["failed"] - :vartype status: str or str or str or str - :ivar action: An object describing the specific action taken in this web search call. Includes - details on how the model used the web (search, open_page, find_in_page). Required. Is one of - the following types: WebSearchActionSearch, WebSearchActionOpenPage, WebSearchActionFind - :vartype action: ~azure.ai.agentserver.responses.models.models.WebSearchActionSearch or - ~azure.ai.agentserver.responses.models.models.WebSearchActionOpenPage or - ~azure.ai.agentserver.responses.models.models.WebSearchActionFind - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the web search tool call. Required.""" - type: Literal[ItemType.WEB_SEARCH_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the web search tool call. Always ``web_search_call``. Required. WEB_SEARCH_CALL.""" - status: Literal["in_progress", "searching", "completed", "failed"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the web search tool call. Required. Is one of the following types: - Literal[\"in_progress\"], Literal[\"searching\"], Literal[\"completed\"], Literal[\"failed\"]""" - action: Union["_models.WebSearchActionSearch", "_models.WebSearchActionOpenPage", "_models.WebSearchActionFind"] = ( - rest_field(visibility=["read", "create", "update", "delete", "query"]) - ) - """An object describing the specific action taken in this web search call. Includes details on how - the model used the web (search, open_page, find_in_page). Required. Is one of the following - types: WebSearchActionSearch, WebSearchActionOpenPage, WebSearchActionFind""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - status: Literal["in_progress", "searching", "completed", "failed"], - action: Union[ - "_models.WebSearchActionSearch", "_models.WebSearchActionOpenPage", "_models.WebSearchActionFind" - ], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.WEB_SEARCH_CALL # type: ignore - - -class KeyPressAction(ComputerAction, discriminator="keypress"): - """KeyPress. - - :ivar type: Specifies the event type. For a keypress action, this property is always set to - ``keypress``. Required. KEYPRESS. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.KEYPRESS - :ivar keys_property: The combination of keys the model is requesting to be pressed. This is an - array of strings, each representing a key. Required. - :vartype keys_property: list[str] - """ - - type: Literal[ComputerActionType.KEYPRESS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Specifies the event type. For a keypress action, this property is always set to ``keypress``. - Required. KEYPRESS.""" - keys_property: list[str] = rest_field( - name="keys", visibility=["read", "create", "update", "delete", "query"], original_tsp_name="keys" - ) - """The combination of keys the model is requesting to be pressed. This is an array of strings, - each representing a key. Required.""" - - @overload - def __init__( - self, - *, - keys_property: list[str], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ComputerActionType.KEYPRESS # type: ignore - - -class LocalEnvironmentResource(FunctionShellCallEnvironment, discriminator="local"): - """Local Environment. - - :ivar type: The environment type. Always ``local``. Required. LOCAL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.LOCAL - """ - - type: Literal[FunctionShellCallEnvironmentType.LOCAL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The environment type. Always ``local``. Required. LOCAL.""" - - @overload - def __init__( - self, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = FunctionShellCallEnvironmentType.LOCAL # type: ignore - - -class LocalShellExecAction(_Model): - """Local shell exec action. - - :ivar type: The type of the local shell action. Always ``exec``. Required. Default value is - "exec". - :vartype type: str - :ivar command: The command to run. Required. - :vartype command: list[str] - :ivar timeout_ms: - :vartype timeout_ms: int - :ivar working_directory: - :vartype working_directory: str - :ivar env: Environment variables to set for the command. Required. - :vartype env: dict[str, str] - :ivar user: - :vartype user: str - """ - - type: Literal["exec"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The type of the local shell action. Always ``exec``. Required. Default value is \"exec\".""" - command: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The command to run. Required.""" - timeout_ms: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - working_directory: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - env: dict[str, str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Environment variables to set for the command. Required.""" - user: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - command: list[str], - env: dict[str, str], - timeout_ms: Optional[int] = None, - working_directory: Optional[str] = None, - user: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["exec"] = "exec" - - -class LocalShellToolParam(Tool, discriminator="local_shell"): - """Local shell tool. - - :ivar type: The type of the local shell tool. Always ``local_shell``. Required. LOCAL_SHELL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.LOCAL_SHELL - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - """ - - type: Literal[ToolType.LOCAL_SHELL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the local shell tool. Always ``local_shell``. Required. LOCAL_SHELL.""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - - @overload - def __init__( - self, - *, - name: Optional[str] = None, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.LOCAL_SHELL # type: ignore - - -class LocalSkillParam(_Model): - """LocalSkillParam. - - :ivar name: The name of the skill. Required. - :vartype name: str - :ivar description: The description of the skill. Required. - :vartype description: str - :ivar path: The path to the directory containing the skill. Required. - :vartype path: str - """ - - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the skill. Required.""" - description: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The description of the skill. Required.""" - path: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The path to the directory containing the skill. Required.""" - - @overload - def __init__( - self, - *, - name: str, - description: str, - path: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class LogProb(_Model): - """Log probability. - - :ivar token: Required. - :vartype token: str - :ivar logprob: Required. - :vartype logprob: int - :ivar bytes: Required. - :vartype bytes: list[int] - :ivar top_logprobs: Required. - :vartype top_logprobs: list[~azure.ai.agentserver.responses.models.models.TopLogProb] - """ - - token: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - logprob: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - bytes: list[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - top_logprobs: list["_models.TopLogProb"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - token: str, - logprob: int, - bytes: list[int], - top_logprobs: list["_models.TopLogProb"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class MCPApprovalResponse(Item, discriminator="mcp_approval_response"): - """MCP approval response. - - :ivar type: The type of the item. Always ``mcp_approval_response``. Required. - MCP_APPROVAL_RESPONSE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MCP_APPROVAL_RESPONSE - :ivar id: - :vartype id: str - :ivar approval_request_id: The ID of the approval request being answered. Required. - :vartype approval_request_id: str - :ivar approve: Whether the request was approved. Required. - :vartype approve: bool - :ivar reason: - :vartype reason: str - """ - - type: Literal[ItemType.MCP_APPROVAL_RESPONSE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``mcp_approval_response``. Required. MCP_APPROVAL_RESPONSE.""" - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - approval_request_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the approval request being answered. Required.""" - approve: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Whether the request was approved. Required.""" - reason: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - approval_request_id: str, - approve: bool, - id: Optional[str] = None, # pylint: disable=redefined-builtin - reason: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.MCP_APPROVAL_RESPONSE # type: ignore - - -class MCPListToolsTool(_Model): - """MCP list tools tool. - - :ivar name: The name of the tool. Required. - :vartype name: str - :ivar description: - :vartype description: str - :ivar input_schema: The JSON schema describing the tool's input. Required. - :vartype input_schema: - ~azure.ai.agentserver.responses.models.models.MCPListToolsToolInputSchema - :ivar annotations: - :vartype annotations: ~azure.ai.agentserver.responses.models.models.MCPListToolsToolAnnotations - """ - - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the tool. Required.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - input_schema: "_models.MCPListToolsToolInputSchema" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The JSON schema describing the tool's input. Required.""" - annotations: Optional["_models.MCPListToolsToolAnnotations"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - - @overload - def __init__( - self, - *, - name: str, - input_schema: "_models.MCPListToolsToolInputSchema", - description: Optional[str] = None, - annotations: Optional["_models.MCPListToolsToolAnnotations"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class MCPListToolsToolAnnotations(_Model): - """MCPListToolsToolAnnotations.""" - - -class MCPListToolsToolInputSchema(_Model): - """MCPListToolsToolInputSchema.""" - - -class MCPTool(Tool, discriminator="mcp"): - """MCP tool. - - :ivar type: The type of the MCP tool. Always ``mcp``. Required. MCP. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MCP - :ivar server_label: A label for this MCP server, used to identify it in tool calls. Required. - :vartype server_label: str - :ivar server_url: The URL for the MCP server. One of ``server_url`` or ``connector_id`` must be - provided. - :vartype server_url: str - :ivar connector_id: Identifier for service connectors, like those available in ChatGPT. One of - ``server_url`` or ``connector_id`` must be provided. Learn more about service connectors `here - `_. Currently supported ``connector_id`` values are: - - * Dropbox: `connector_dropbox` - * Gmail: `connector_gmail` - * Google Calendar: `connector_googlecalendar` - * Google Drive: `connector_googledrive` - * Microsoft Teams: `connector_microsoftteams` - * Outlook Calendar: `connector_outlookcalendar` - * Outlook Email: `connector_outlookemail` - * SharePoint: `connector_sharepoint`. Is one of the following types: - Literal["connector_dropbox"], Literal["connector_gmail"], Literal["connector_googlecalendar"], - Literal["connector_googledrive"], Literal["connector_microsoftteams"], - Literal["connector_outlookcalendar"], Literal["connector_outlookemail"], - Literal["connector_sharepoint"] - :vartype connector_id: str or str or str or str or str or str or str or str - :ivar authorization: An OAuth access token that can be used with a remote MCP server, either - with a custom MCP server URL or a service connector. Your application must handle the OAuth - authorization flow and provide the token here. - :vartype authorization: str - :ivar server_description: Optional description of the MCP server, used to provide more context. - :vartype server_description: str - :ivar headers: - :vartype headers: dict[str, str] - :ivar allowed_tools: Is either a [str] type or a MCPToolFilter type. - :vartype allowed_tools: list[str] or - ~azure.ai.agentserver.responses.models.models.MCPToolFilter - :ivar require_approval: Is one of the following types: MCPToolRequireApproval, - Literal["always"], Literal["never"] - :vartype require_approval: ~azure.ai.agentserver.responses.models.models.MCPToolRequireApproval - or str or str - :ivar project_connection_id: The connection ID in the project for the MCP server. The - connection stores authentication and other connection details needed to connect to the MCP - server. - :vartype project_connection_id: str - """ - - type: Literal[ToolType.MCP] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the MCP tool. Always ``mcp``. Required. MCP.""" - server_label: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A label for this MCP server, used to identify it in tool calls. Required.""" - server_url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The URL for the MCP server. One of ``server_url`` or ``connector_id`` must be provided.""" - connector_id: Optional[ - Literal[ - "connector_dropbox", - "connector_gmail", - "connector_googlecalendar", - "connector_googledrive", - "connector_microsoftteams", - "connector_outlookcalendar", - "connector_outlookemail", - "connector_sharepoint", - ] - ] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Identifier for service connectors, like those available in ChatGPT. One of ``server_url`` or - ``connector_id`` must be provided. Learn more about service connectors `here - `_. Currently supported ``connector_id`` values are: - - * Dropbox: `connector_dropbox` - * Gmail: `connector_gmail` - * Google Calendar: `connector_googlecalendar` - * Google Drive: `connector_googledrive` - * Microsoft Teams: `connector_microsoftteams` - * Outlook Calendar: `connector_outlookcalendar` - * Outlook Email: `connector_outlookemail` - * SharePoint: `connector_sharepoint`. Is one of the following types: - Literal[\"connector_dropbox\"], Literal[\"connector_gmail\"], - Literal[\"connector_googlecalendar\"], Literal[\"connector_googledrive\"], - Literal[\"connector_microsoftteams\"], Literal[\"connector_outlookcalendar\"], - Literal[\"connector_outlookemail\"], Literal[\"connector_sharepoint\"]""" - authorization: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """An OAuth access token that can be used with a remote MCP server, either with a custom MCP - server URL or a service connector. Your application must handle the OAuth authorization flow - and provide the token here.""" - server_description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional description of the MCP server, used to provide more context.""" - headers: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - allowed_tools: Optional[Union[list[str], "_models.MCPToolFilter"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Is either a [str] type or a MCPToolFilter type.""" - require_approval: Optional[Union["_models.MCPToolRequireApproval", Literal["always"], Literal["never"]]] = ( - rest_field(visibility=["read", "create", "update", "delete", "query"]) - ) - """Is one of the following types: MCPToolRequireApproval, Literal[\"always\"], Literal[\"never\"]""" - project_connection_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The connection ID in the project for the MCP server. The connection stores authentication and - other connection details needed to connect to the MCP server.""" - - @overload - def __init__( - self, - *, - server_label: str, - server_url: Optional[str] = None, - connector_id: Optional[ - Literal[ - "connector_dropbox", - "connector_gmail", - "connector_googlecalendar", - "connector_googledrive", - "connector_microsoftteams", - "connector_outlookcalendar", - "connector_outlookemail", - "connector_sharepoint", - ] - ] = None, - authorization: Optional[str] = None, - server_description: Optional[str] = None, - headers: Optional[dict[str, str]] = None, - allowed_tools: Optional[Union[list[str], "_models.MCPToolFilter"]] = None, - require_approval: Optional[Union["_models.MCPToolRequireApproval", Literal["always"], Literal["never"]]] = None, - project_connection_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.MCP # type: ignore - - -class MCPToolFilter(_Model): - """MCP tool filter. - - :ivar tool_names: MCP allowed tools. - :vartype tool_names: list[str] - :ivar read_only: Indicates whether or not a tool modifies data or is read-only. If an MCP - server is `annotated with `readOnlyHint` - `_, - it will match this filter. - :vartype read_only: bool - """ - - tool_names: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """MCP allowed tools.""" - read_only: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Indicates whether or not a tool modifies data or is read-only. If an MCP server is `annotated - with `readOnlyHint` - `_, - it will match this filter.""" - - @overload - def __init__( - self, - *, - tool_names: Optional[list[str]] = None, - read_only: Optional[bool] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class MCPToolRequireApproval(_Model): - """MCPToolRequireApproval. - - :ivar always: - :vartype always: ~azure.ai.agentserver.responses.models.models.MCPToolFilter - :ivar never: - :vartype never: ~azure.ai.agentserver.responses.models.models.MCPToolFilter - """ - - always: Optional["_models.MCPToolFilter"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - never: Optional["_models.MCPToolFilter"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - always: Optional["_models.MCPToolFilter"] = None, - never: Optional["_models.MCPToolFilter"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class MemorySearchItem(_Model): - """A retrieved memory item from memory search. - - :ivar memory_item: Retrieved memory item. Required. - :vartype memory_item: ~azure.ai.agentserver.responses.models.models.MemoryItem - """ - - memory_item: "_models.MemoryItem" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Retrieved memory item. Required.""" - - @overload - def __init__( - self, - *, - memory_item: "_models.MemoryItem", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class MemorySearchOptions(_Model): - """Memory search options. - - :ivar max_memories: Maximum number of memory items to return. - :vartype max_memories: int - """ - - max_memories: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Maximum number of memory items to return.""" - - @overload - def __init__( - self, - *, - max_memories: Optional[int] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class MemorySearchPreviewTool(Tool, discriminator="memory_search_preview"): - """A tool for integrating memories into the agent. - - :ivar type: The type of the tool. Always ``memory_search_preview``. Required. - MEMORY_SEARCH_PREVIEW. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MEMORY_SEARCH_PREVIEW - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar memory_store_name: The name of the memory store to use. Required. - :vartype memory_store_name: str - :ivar scope: The namespace used to group and isolate memories, such as a user ID. Limits which - memories can be retrieved or updated. Use special variable ``{{$userId}}`` to scope memories to - the current signed-in user. Required. - :vartype scope: str - :ivar search_options: Options for searching the memory store. - :vartype search_options: ~azure.ai.agentserver.responses.models.models.MemorySearchOptions - :ivar update_delay: Time to wait before updating memories after inactivity (seconds). Default - 300. - :vartype update_delay: int - """ - - type: Literal[ToolType.MEMORY_SEARCH_PREVIEW] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the tool. Always ``memory_search_preview``. Required. MEMORY_SEARCH_PREVIEW.""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - memory_store_name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the memory store to use. Required.""" - scope: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The namespace used to group and isolate memories, such as a user ID. Limits which memories can - be retrieved or updated. Use special variable ``{{$userId}}`` to scope memories to the current - signed-in user. Required.""" - search_options: Optional["_models.MemorySearchOptions"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Options for searching the memory store.""" - update_delay: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Time to wait before updating memories after inactivity (seconds). Default 300.""" - - @overload - def __init__( - self, - *, - memory_store_name: str, - scope: str, - name: Optional[str] = None, - description: Optional[str] = None, - search_options: Optional["_models.MemorySearchOptions"] = None, - update_delay: Optional[int] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.MEMORY_SEARCH_PREVIEW # type: ignore - - -class MemorySearchToolCallItemParam(Item, discriminator="memory_search_call"): - """MemorySearchToolCallItemParam. - - :ivar type: Required. MEMORY_SEARCH_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MEMORY_SEARCH_CALL - :ivar results: The results returned from the memory search. - :vartype results: list[~azure.ai.agentserver.responses.models.models.MemorySearchItem] - """ - - type: Literal[ItemType.MEMORY_SEARCH_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. MEMORY_SEARCH_CALL.""" - results: Optional[list["_models.MemorySearchItem"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The results returned from the memory search.""" - - @overload - def __init__( - self, - *, - results: Optional[list["_models.MemorySearchItem"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ItemType.MEMORY_SEARCH_CALL # type: ignore - - -class MemorySearchToolCallItemResource(OutputItem, discriminator="memory_search_call"): - """MemorySearchToolCallItemResource. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. MEMORY_SEARCH_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MEMORY_SEARCH_CALL - :ivar status: The status of the memory search tool call. One of ``in_progress``, ``searching``, - ``completed``, ``incomplete`` or ``failed``,. Required. Is one of the following types: - Literal["in_progress"], Literal["searching"], Literal["completed"], Literal["incomplete"], - Literal["failed"] - :vartype status: str or str or str or str or str - :ivar results: The results returned from the memory search. - :vartype results: list[~azure.ai.agentserver.responses.models.models.MemorySearchItem] - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.MEMORY_SEARCH_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. MEMORY_SEARCH_CALL.""" - status: Literal["in_progress", "searching", "completed", "incomplete", "failed"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the memory search tool call. One of ``in_progress``, ``searching``, - ``completed``, ``incomplete`` or ``failed``,. Required. Is one of the following types: - Literal[\"in_progress\"], Literal[\"searching\"], Literal[\"completed\"], - Literal[\"incomplete\"], Literal[\"failed\"]""" - results: Optional[list["_models.MemorySearchItem"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The results returned from the memory search.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - status: Literal["in_progress", "searching", "completed", "incomplete", "failed"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - results: Optional[list["_models.MemorySearchItem"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.MEMORY_SEARCH_CALL # type: ignore - - -class MessageContentInputFileContent(MessageContent, discriminator="input_file"): - """Input file. - - :ivar type: The type of the input item. Always ``input_file``. Required. INPUT_FILE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.INPUT_FILE - :ivar file_id: - :vartype file_id: str - :ivar filename: The name of the file to be sent to the model. - :vartype filename: str - :ivar file_url: The URL of the file to be sent to the model. - :vartype file_url: str - :ivar file_data: The content of the file to be sent to the model. - :vartype file_data: str - """ - - type: Literal[MessageContentType.INPUT_FILE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the input item. Always ``input_file``. Required. INPUT_FILE.""" - file_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - filename: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the file to be sent to the model.""" - file_url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The URL of the file to be sent to the model.""" - file_data: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The content of the file to be sent to the model.""" - - @overload - def __init__( - self, - *, - file_id: Optional[str] = None, - filename: Optional[str] = None, - file_url: Optional[str] = None, - file_data: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = MessageContentType.INPUT_FILE # type: ignore - - -class MessageContentInputImageContent(MessageContent, discriminator="input_image"): - """Input image. - - :ivar type: The type of the input item. Always ``input_image``. Required. INPUT_IMAGE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.INPUT_IMAGE - :ivar image_url: - :vartype image_url: str - :ivar file_id: - :vartype file_id: str - :ivar detail: The detail level of the image to be sent to the model. One of ``high``, ``low``, - or ``auto``. Defaults to ``auto``. Required. Known values are: "low", "high", and "auto". - :vartype detail: str or ~azure.ai.agentserver.responses.models.models.ImageDetail - """ - - type: Literal[MessageContentType.INPUT_IMAGE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the input item. Always ``input_image``. Required. INPUT_IMAGE.""" - image_url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - file_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - detail: Union[str, "_models.ImageDetail"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The detail level of the image to be sent to the model. One of ``high``, ``low``, or ``auto``. - Defaults to ``auto``. Required. Known values are: \"low\", \"high\", and \"auto\".""" - - @overload - def __init__( - self, - *, - detail: Union[str, "_models.ImageDetail"], - image_url: Optional[str] = None, - file_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = MessageContentType.INPUT_IMAGE # type: ignore - - -class MessageContentInputTextContent(MessageContent, discriminator="input_text"): - """Input text. - - :ivar type: The type of the input item. Always ``input_text``. Required. INPUT_TEXT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.INPUT_TEXT - :ivar text: The text input to the model. Required. - :vartype text: str - """ - - type: Literal[MessageContentType.INPUT_TEXT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the input item. Always ``input_text``. Required. INPUT_TEXT.""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The text input to the model. Required.""" - - @overload - def __init__( - self, - *, - text: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = MessageContentType.INPUT_TEXT # type: ignore - - -class MessageContentOutputTextContent(MessageContent, discriminator="output_text"): - """Output text. - - :ivar type: The type of the output text. Always ``output_text``. Required. OUTPUT_TEXT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.OUTPUT_TEXT - :ivar text: The text output from the model. Required. - :vartype text: str - :ivar annotations: The annotations of the text output. Required. - :vartype annotations: list[~azure.ai.agentserver.responses.models.models.Annotation] - :ivar logprobs: Required. - :vartype logprobs: list[~azure.ai.agentserver.responses.models.models.LogProb] - """ - - type: Literal[MessageContentType.OUTPUT_TEXT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the output text. Always ``output_text``. Required. OUTPUT_TEXT.""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The text output from the model. Required.""" - annotations: list["_models.Annotation"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The annotations of the text output. Required.""" - logprobs: list["_models.LogProb"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - text: str, - annotations: list["_models.Annotation"], - logprobs: list["_models.LogProb"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = MessageContentType.OUTPUT_TEXT # type: ignore - - -class MessageContentReasoningTextContent(MessageContent, discriminator="reasoning_text"): - """Reasoning text. - - :ivar type: The type of the reasoning text. Always ``reasoning_text``. Required. - REASONING_TEXT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.REASONING_TEXT - :ivar text: The reasoning text from the model. Required. - :vartype text: str - """ - - type: Literal[MessageContentType.REASONING_TEXT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the reasoning text. Always ``reasoning_text``. Required. REASONING_TEXT.""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The reasoning text from the model. Required.""" - - @overload - def __init__( - self, - *, - text: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = MessageContentType.REASONING_TEXT # type: ignore - - -class MessageContentRefusalContent(MessageContent, discriminator="refusal"): - """Refusal. - - :ivar type: The type of the refusal. Always ``refusal``. Required. REFUSAL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.REFUSAL - :ivar refusal: The refusal explanation from the model. Required. - :vartype refusal: str - """ - - type: Literal[MessageContentType.REFUSAL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the refusal. Always ``refusal``. Required. REFUSAL.""" - refusal: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The refusal explanation from the model. Required.""" - - @overload - def __init__( - self, - *, - refusal: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = MessageContentType.REFUSAL # type: ignore - - -class Metadata(_Model): - """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing - additional information about the object in a structured format, and querying for objects via - API or the dashboard. Keys are strings with a maximum length of 64 characters. Values are - strings with a maximum length of 512 characters. - - """ - - -class MicrosoftFabricPreviewTool(Tool, discriminator="fabric_dataagent_preview"): - """The input definition information for a Microsoft Fabric tool as used to configure an agent. - - :ivar type: The object type, which is always 'fabric_dataagent_preview'. Required. - FABRIC_DATAAGENT_PREVIEW. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.FABRIC_DATAAGENT_PREVIEW - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar fabric_dataagent_preview: The fabric data agent tool parameters. Required. - :vartype fabric_dataagent_preview: - ~azure.ai.agentserver.responses.models.models.FabricDataAgentToolParameters - """ - - type: Literal[ToolType.FABRIC_DATAAGENT_PREVIEW] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'fabric_dataagent_preview'. Required. - FABRIC_DATAAGENT_PREVIEW.""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - fabric_dataagent_preview: "_models.FabricDataAgentToolParameters" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The fabric data agent tool parameters. Required.""" - - @overload - def __init__( - self, - *, - fabric_dataagent_preview: "_models.FabricDataAgentToolParameters", - name: Optional[str] = None, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.FABRIC_DATAAGENT_PREVIEW # type: ignore - - -class MoveParam(ComputerAction, discriminator="move"): - """Move. - - :ivar type: Specifies the event type. For a move action, this property is always set to - ``move``. Required. MOVE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MOVE - :ivar x: The x-coordinate to move to. Required. - :vartype x: int - :ivar y: The y-coordinate to move to. Required. - :vartype y: int - """ - - type: Literal[ComputerActionType.MOVE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Specifies the event type. For a move action, this property is always set to ``move``. Required. - MOVE.""" - x: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The x-coordinate to move to. Required.""" - y: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The y-coordinate to move to. Required.""" - - @overload - def __init__( - self, - *, - x: int, - y: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ComputerActionType.MOVE # type: ignore - - -class OAuthConsentRequestOutputItem(OutputItem, discriminator="oauth_consent_request"): - """Request from the service for the user to perform OAuth consent. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar id: Required. - :vartype id: str - :ivar type: Required. OAUTH_CONSENT_REQUEST. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.OAUTH_CONSENT_REQUEST - :ivar consent_link: The link the user can use to perform OAuth consent. Required. - :vartype consent_link: str - :ivar server_label: The server label for the OAuth consent request. Required. - :vartype server_label: str - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - type: Literal[OutputItemType.OAUTH_CONSENT_REQUEST] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. OAUTH_CONSENT_REQUEST.""" - consent_link: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The link the user can use to perform OAuth consent. Required.""" - server_label: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The server label for the OAuth consent request. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - consent_link: str, - server_label: str, - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.OAUTH_CONSENT_REQUEST # type: ignore - - -class OpenApiAuthDetails(_Model): - """authentication details for OpenApiFunctionDefinition. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - OpenApiAnonymousAuthDetails, OpenApiManagedAuthDetails, OpenApiProjectConnectionAuthDetails - - :ivar type: The type of authentication, must be anonymous/project_connection/managed_identity. - Required. Known values are: "anonymous", "project_connection", and "managed_identity". - :vartype type: str or ~azure.ai.agentserver.responses.models.models.OpenApiAuthType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The type of authentication, must be anonymous/project_connection/managed_identity. Required. - Known values are: \"anonymous\", \"project_connection\", and \"managed_identity\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class OpenApiAnonymousAuthDetails(OpenApiAuthDetails, discriminator="anonymous"): - """Security details for OpenApi anonymous authentication. - - :ivar type: The object type, which is always 'anonymous'. Required. ANONYMOUS. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.ANONYMOUS - """ - - type: Literal[OpenApiAuthType.ANONYMOUS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'anonymous'. Required. ANONYMOUS.""" - - @overload - def __init__( - self, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OpenApiAuthType.ANONYMOUS # type: ignore - - -class OpenApiFunctionDefinition(_Model): - """The input definition information for an openapi function. - - :ivar name: The name of the function to be called. Required. - :vartype name: str - :ivar description: A description of what the function does, used by the model to choose when - and how to call the function. - :vartype description: str - :ivar spec: The openapi function shape, described as a JSON Schema object. Required. - :vartype spec: dict[str, any] - :ivar auth: Open API authentication details. Required. - :vartype auth: ~azure.ai.agentserver.responses.models.models.OpenApiAuthDetails - :ivar default_params: List of OpenAPI spec parameters that will use user-provided defaults. - :vartype default_params: list[str] - :ivar functions: List of function definitions used by OpenApi tool. - :vartype functions: - list[~azure.ai.agentserver.responses.models.models.OpenApiFunctionDefinitionFunction] - """ - - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the function to be called. Required.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A description of what the function does, used by the model to choose when and how to call the - function.""" - spec: dict[str, Any] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The openapi function shape, described as a JSON Schema object. Required.""" - auth: "_models.OpenApiAuthDetails" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Open API authentication details. Required.""" - default_params: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """List of OpenAPI spec parameters that will use user-provided defaults.""" - functions: Optional[list["_models.OpenApiFunctionDefinitionFunction"]] = rest_field(visibility=["read"]) - """List of function definitions used by OpenApi tool.""" - - @overload - def __init__( - self, - *, - name: str, - spec: dict[str, Any], - auth: "_models.OpenApiAuthDetails", - description: Optional[str] = None, - default_params: Optional[list[str]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class OpenApiFunctionDefinitionFunction(_Model): - """OpenApiFunctionDefinitionFunction. - - :ivar name: The name of the function to be called. Required. - :vartype name: str - :ivar description: A description of what the function does, used by the model to choose when - and how to call the function. - :vartype description: str - :ivar parameters: The parameters the functions accepts, described as a JSON Schema object. - Required. - :vartype parameters: dict[str, any] - """ - - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the function to be called. Required.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A description of what the function does, used by the model to choose when and how to call the - function.""" - parameters: dict[str, Any] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The parameters the functions accepts, described as a JSON Schema object. Required.""" - - @overload - def __init__( - self, - *, - name: str, - parameters: dict[str, Any], - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class OpenApiManagedAuthDetails(OpenApiAuthDetails, discriminator="managed_identity"): - """Security details for OpenApi managed_identity authentication. - - :ivar type: The object type, which is always 'managed_identity'. Required. MANAGED_IDENTITY. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MANAGED_IDENTITY - :ivar security_scheme: Connection auth security details. Required. - :vartype security_scheme: - ~azure.ai.agentserver.responses.models.models.OpenApiManagedSecurityScheme - """ - - type: Literal[OpenApiAuthType.MANAGED_IDENTITY] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'managed_identity'. Required. MANAGED_IDENTITY.""" - security_scheme: "_models.OpenApiManagedSecurityScheme" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Connection auth security details. Required.""" - - @overload - def __init__( - self, - *, - security_scheme: "_models.OpenApiManagedSecurityScheme", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OpenApiAuthType.MANAGED_IDENTITY # type: ignore - - -class OpenApiManagedSecurityScheme(_Model): - """Security scheme for OpenApi managed_identity authentication. - - :ivar audience: Authentication scope for managed_identity auth type. Required. - :vartype audience: str - """ - - audience: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Authentication scope for managed_identity auth type. Required.""" - - @overload - def __init__( - self, - *, - audience: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class OpenApiProjectConnectionAuthDetails(OpenApiAuthDetails, discriminator="project_connection"): - """Security details for OpenApi project connection authentication. - - :ivar type: The object type, which is always 'project_connection'. Required. - PROJECT_CONNECTION. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.PROJECT_CONNECTION - :ivar security_scheme: Project connection auth security details. Required. - :vartype security_scheme: - ~azure.ai.agentserver.responses.models.models.OpenApiProjectConnectionSecurityScheme - """ - - type: Literal[OpenApiAuthType.PROJECT_CONNECTION] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'project_connection'. Required. PROJECT_CONNECTION.""" - security_scheme: "_models.OpenApiProjectConnectionSecurityScheme" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Project connection auth security details. Required.""" - - @overload - def __init__( - self, - *, - security_scheme: "_models.OpenApiProjectConnectionSecurityScheme", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OpenApiAuthType.PROJECT_CONNECTION # type: ignore - - -class OpenApiProjectConnectionSecurityScheme(_Model): - """Security scheme for OpenApi managed_identity authentication. - - :ivar project_connection_id: Project connection id for Project Connection auth type. Required. - :vartype project_connection_id: str - """ - - project_connection_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Project connection id for Project Connection auth type. Required.""" - - @overload - def __init__( - self, - *, - project_connection_id: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class OpenApiTool(Tool, discriminator="openapi"): - """The input definition information for an OpenAPI tool as used to configure an agent. - - :ivar type: The object type, which is always 'openapi'. Required. OPENAPI. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.OPENAPI - :ivar openapi: The openapi function definition. Required. - :vartype openapi: ~azure.ai.agentserver.responses.models.models.OpenApiFunctionDefinition - """ - - type: Literal[ToolType.OPENAPI] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'openapi'. Required. OPENAPI.""" - openapi: "_models.OpenApiFunctionDefinition" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The openapi function definition. Required.""" - - @overload - def __init__( - self, - *, - openapi: "_models.OpenApiFunctionDefinition", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.OPENAPI # type: ignore - - -class OpenApiToolCall(OutputItem, discriminator="openapi_call"): - """An OpenAPI tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. OPENAPI_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.OPENAPI_CALL - :ivar call_id: The unique ID of the tool call generated by the model. Required. - :vartype call_id: str - :ivar name: The name of the OpenAPI operation being called. Required. - :vartype name: str - :ivar arguments: A JSON string of the arguments to pass to the tool. Required. - :vartype arguments: str - :ivar status: The status of the tool call. Required. Known values are: "in_progress", - "completed", "incomplete", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ToolCallStatus - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.OPENAPI_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. OPENAPI_CALL.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call generated by the model. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the OpenAPI operation being called. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of the arguments to pass to the tool. Required.""" - status: Union[str, "_models.ToolCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. Required. Known values are: \"in_progress\", \"completed\", - \"incomplete\", and \"failed\".""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - name: str, - arguments: str, - status: Union[str, "_models.ToolCallStatus"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.OPENAPI_CALL # type: ignore - - -class OpenApiToolCallOutput(OutputItem, discriminator="openapi_call_output"): - """The output of an OpenAPI tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. OPENAPI_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.OPENAPI_CALL_OUTPUT - :ivar call_id: The unique ID of the tool call generated by the model. Required. - :vartype call_id: str - :ivar name: The name of the OpenAPI operation that was called. Required. - :vartype name: str - :ivar output: The output from the OpenAPI tool call. Is one of the following types: {str: Any}, - str, [Any] - :vartype output: dict[str, any] or str or list[any] - :ivar status: The status of the tool call. Required. Known values are: "in_progress", - "completed", "incomplete", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ToolCallStatus - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.OPENAPI_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. OPENAPI_CALL_OUTPUT.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call generated by the model. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the OpenAPI operation that was called. Required.""" - output: Optional["_types.ToolCallOutputContent"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The output from the OpenAPI tool call. Is one of the following types: {str: Any}, str, [Any]""" - status: Union[str, "_models.ToolCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. Required. Known values are: \"in_progress\", \"completed\", - \"incomplete\", and \"failed\".""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - name: str, - status: Union[str, "_models.ToolCallStatus"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - output: Optional["_types.ToolCallOutputContent"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.OPENAPI_CALL_OUTPUT # type: ignore - - -class OutputContent(_Model): - """OutputContent. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - OutputContentOutputTextContent, OutputContentReasoningTextContent, OutputContentRefusalContent - - :ivar type: Required. Known values are: "output_text", "refusal", and "reasoning_text". - :vartype type: str or ~azure.ai.agentserver.responses.models.models.OutputContentType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"output_text\", \"refusal\", and \"reasoning_text\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class OutputContentOutputTextContent(OutputContent, discriminator="output_text"): - """Output text. - - :ivar type: The type of the output text. Always ``output_text``. Required. OUTPUT_TEXT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.OUTPUT_TEXT - :ivar text: The text output from the model. Required. - :vartype text: str - :ivar annotations: The annotations of the text output. Required. - :vartype annotations: list[~azure.ai.agentserver.responses.models.models.Annotation] - :ivar logprobs: Required. - :vartype logprobs: list[~azure.ai.agentserver.responses.models.models.LogProb] - """ - - type: Literal[OutputContentType.OUTPUT_TEXT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the output text. Always ``output_text``. Required. OUTPUT_TEXT.""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The text output from the model. Required.""" - annotations: list["_models.Annotation"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The annotations of the text output. Required.""" - logprobs: list["_models.LogProb"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - text: str, - annotations: list["_models.Annotation"], - logprobs: list["_models.LogProb"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputContentType.OUTPUT_TEXT # type: ignore - - -class OutputContentReasoningTextContent(OutputContent, discriminator="reasoning_text"): - """Reasoning text. - - :ivar type: The type of the reasoning text. Always ``reasoning_text``. Required. - REASONING_TEXT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.REASONING_TEXT - :ivar text: The reasoning text from the model. Required. - :vartype text: str - """ - - type: Literal[OutputContentType.REASONING_TEXT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the reasoning text. Always ``reasoning_text``. Required. REASONING_TEXT.""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The reasoning text from the model. Required.""" - - @overload - def __init__( - self, - *, - text: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputContentType.REASONING_TEXT # type: ignore - - -class OutputContentRefusalContent(OutputContent, discriminator="refusal"): - """Refusal. - - :ivar type: The type of the refusal. Always ``refusal``. Required. REFUSAL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.REFUSAL - :ivar refusal: The refusal explanation from the model. Required. - :vartype refusal: str - """ - - type: Literal[OutputContentType.REFUSAL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the refusal. Always ``refusal``. Required. REFUSAL.""" - refusal: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The refusal explanation from the model. Required.""" - - @overload - def __init__( - self, - *, - refusal: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputContentType.REFUSAL # type: ignore - - -class OutputItemApplyPatchToolCall(OutputItem, discriminator="apply_patch_call"): - """Apply patch tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: The type of the item. Always ``apply_patch_call``. Required. APPLY_PATCH_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.APPLY_PATCH_CALL - :ivar id: The unique ID of the apply patch tool call. Populated when this item is returned via - API. Required. - :vartype id: str - :ivar call_id: The unique ID of the apply patch tool call generated by the model. Required. - :vartype call_id: str - :ivar status: The status of the apply patch tool call. One of ``in_progress`` or ``completed``. - Required. Known values are: "in_progress" and "completed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ApplyPatchCallStatus - :ivar operation: Apply patch operation. Required. - :vartype operation: ~azure.ai.agentserver.responses.models.models.ApplyPatchFileOperation - """ - - type: Literal[OutputItemType.APPLY_PATCH_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``apply_patch_call``. Required. APPLY_PATCH_CALL.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the apply patch tool call. Populated when this item is returned via API. - Required.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the apply patch tool call generated by the model. Required.""" - status: Union[str, "_models.ApplyPatchCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the apply patch tool call. One of ``in_progress`` or ``completed``. Required. - Known values are: \"in_progress\" and \"completed\".""" - operation: "_models.ApplyPatchFileOperation" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Apply patch operation. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - call_id: str, - status: Union[str, "_models.ApplyPatchCallStatus"], - operation: "_models.ApplyPatchFileOperation", - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.APPLY_PATCH_CALL # type: ignore - - -class OutputItemApplyPatchToolCallOutput(OutputItem, discriminator="apply_patch_call_output"): - """Apply patch tool call output. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: The type of the item. Always ``apply_patch_call_output``. Required. - APPLY_PATCH_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.APPLY_PATCH_CALL_OUTPUT - :ivar id: The unique ID of the apply patch tool call output. Populated when this item is - returned via API. Required. - :vartype id: str - :ivar call_id: The unique ID of the apply patch tool call generated by the model. Required. - :vartype call_id: str - :ivar status: The status of the apply patch tool call output. One of ``completed`` or - ``failed``. Required. Known values are: "completed" and "failed". - :vartype status: str or - ~azure.ai.agentserver.responses.models.models.ApplyPatchCallOutputStatus - :ivar output: - :vartype output: str - """ - - type: Literal[OutputItemType.APPLY_PATCH_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``apply_patch_call_output``. Required. APPLY_PATCH_CALL_OUTPUT.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the apply patch tool call output. Populated when this item is returned via - API. Required.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the apply patch tool call generated by the model. Required.""" - status: Union[str, "_models.ApplyPatchCallOutputStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the apply patch tool call output. One of ``completed`` or ``failed``. Required. - Known values are: \"completed\" and \"failed\".""" - output: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - call_id: str, - status: Union[str, "_models.ApplyPatchCallOutputStatus"], - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - output: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.APPLY_PATCH_CALL_OUTPUT # type: ignore - - -class OutputItemCodeInterpreterToolCall(OutputItem, discriminator="code_interpreter_call"): - """Code interpreter tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: The type of the code interpreter tool call. Always ``code_interpreter_call``. - Required. CODE_INTERPRETER_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CODE_INTERPRETER_CALL - :ivar id: The unique ID of the code interpreter tool call. Required. - :vartype id: str - :ivar status: The status of the code interpreter tool call. Valid values are ``in_progress``, - ``completed``, ``incomplete``, ``interpreting``, and ``failed``. Required. Is one of the - following types: Literal["in_progress"], Literal["completed"], Literal["incomplete"], - Literal["interpreting"], Literal["failed"] - :vartype status: str or str or str or str or str - :ivar container_id: The ID of the container used to run the code. Required. - :vartype container_id: str - :ivar code: Required. - :vartype code: str - :ivar outputs: Required. - :vartype outputs: list[~azure.ai.agentserver.responses.models.models.CodeInterpreterOutputLogs - or ~azure.ai.agentserver.responses.models.models.CodeInterpreterOutputImage] - """ - - type: Literal[OutputItemType.CODE_INTERPRETER_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the code interpreter tool call. Always ``code_interpreter_call``. Required. - CODE_INTERPRETER_CALL.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the code interpreter tool call. Required.""" - status: Literal["in_progress", "completed", "incomplete", "interpreting", "failed"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the code interpreter tool call. Valid values are ``in_progress``, ``completed``, - ``incomplete``, ``interpreting``, and ``failed``. Required. Is one of the following types: - Literal[\"in_progress\"], Literal[\"completed\"], Literal[\"incomplete\"], - Literal[\"interpreting\"], Literal[\"failed\"]""" - container_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the container used to run the code. Required.""" - code: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - outputs: list[Union["_models.CodeInterpreterOutputLogs", "_models.CodeInterpreterOutputImage"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - status: Literal["in_progress", "completed", "incomplete", "interpreting", "failed"], - container_id: str, - code: str, - outputs: list[Union["_models.CodeInterpreterOutputLogs", "_models.CodeInterpreterOutputImage"]], - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.CODE_INTERPRETER_CALL # type: ignore - - -class OutputItemCompactionBody(OutputItem, discriminator="compaction"): - """Compaction item. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: The type of the item. Always ``compaction``. Required. COMPACTION. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.COMPACTION - :ivar id: The unique ID of the compaction item. Required. - :vartype id: str - :ivar encrypted_content: The encrypted content that was produced by compaction. Required. - :vartype encrypted_content: str - """ - - type: Literal[OutputItemType.COMPACTION] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``compaction``. Required. COMPACTION.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the compaction item. Required.""" - encrypted_content: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The encrypted content that was produced by compaction. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - encrypted_content: str, - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.COMPACTION # type: ignore - - -class OutputItemComputerToolCall(OutputItem, discriminator="computer_call"): - """Computer tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: The type of the computer call. Always ``computer_call``. Required. COMPUTER_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.COMPUTER_CALL - :ivar id: The unique ID of the computer call. Required. - :vartype id: str - :ivar call_id: An identifier used when responding to the tool call with output. Required. - :vartype call_id: str - :ivar action: Required. - :vartype action: ~azure.ai.agentserver.responses.models.models.ComputerAction - :ivar pending_safety_checks: The pending safety checks for the computer call. Required. - :vartype pending_safety_checks: - list[~azure.ai.agentserver.responses.models.models.ComputerCallSafetyCheckParam] - :ivar status: The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. - Populated when items are returned via API. Required. Is one of the following types: - Literal["in_progress"], Literal["completed"], Literal["incomplete"] - :vartype status: str or str or str - """ - - type: Literal[OutputItemType.COMPUTER_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the computer call. Always ``computer_call``. Required. COMPUTER_CALL.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the computer call. Required.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """An identifier used when responding to the tool call with output. Required.""" - action: "_models.ComputerAction" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - pending_safety_checks: list["_models.ComputerCallSafetyCheckParam"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The pending safety checks for the computer call. Required.""" - status: Literal["in_progress", "completed", "incomplete"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. Populated - when items are returned via API. Required. Is one of the following types: - Literal[\"in_progress\"], Literal[\"completed\"], Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - call_id: str, - action: "_models.ComputerAction", - pending_safety_checks: list["_models.ComputerCallSafetyCheckParam"], - status: Literal["in_progress", "completed", "incomplete"], - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.COMPUTER_CALL # type: ignore - - -class OutputItemComputerToolCallOutputResource(OutputItem, discriminator="computer_call_output"): - """OutputItemComputerToolCallOutputResource. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: The type of the computer tool call output. Always ``computer_call_output``. - Required. COMPUTER_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.COMPUTER_CALL_OUTPUT - :ivar id: The ID of the computer tool call output. - :vartype id: str - :ivar call_id: The ID of the computer tool call that produced the output. Required. - :vartype call_id: str - :ivar acknowledged_safety_checks: The safety checks reported by the API that have been - acknowledged by the developer. - :vartype acknowledged_safety_checks: - list[~azure.ai.agentserver.responses.models.models.ComputerCallSafetyCheckParam] - :ivar output: Required. - :vartype output: ~azure.ai.agentserver.responses.models.models.ComputerScreenshotImage - :ivar status: The status of the message input. One of ``in_progress``, ``completed``, or - ``incomplete``. Populated when input items are returned via API. Is one of the following types: - Literal["in_progress"], Literal["completed"], Literal["incomplete"] - :vartype status: str or str or str - """ - - type: Literal[OutputItemType.COMPUTER_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the computer tool call output. Always ``computer_call_output``. Required. - COMPUTER_CALL_OUTPUT.""" - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the computer tool call output.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the computer tool call that produced the output. Required.""" - acknowledged_safety_checks: Optional[list["_models.ComputerCallSafetyCheckParam"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The safety checks reported by the API that have been acknowledged by the developer.""" - output: "_models.ComputerScreenshotImage" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - status: Optional[Literal["in_progress", "completed", "incomplete"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the message input. One of ``in_progress``, ``completed``, or ``incomplete``. - Populated when input items are returned via API. Is one of the following types: - Literal[\"in_progress\"], Literal[\"completed\"], Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - call_id: str, - output: "_models.ComputerScreenshotImage", - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - id: Optional[str] = None, # pylint: disable=redefined-builtin - acknowledged_safety_checks: Optional[list["_models.ComputerCallSafetyCheckParam"]] = None, - status: Optional[Literal["in_progress", "completed", "incomplete"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.COMPUTER_CALL_OUTPUT # type: ignore - - -class OutputItemCustomToolCall(OutputItem, discriminator="custom_tool_call"): - """Custom tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: The type of the custom tool call. Always ``custom_tool_call``. Required. - CUSTOM_TOOL_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CUSTOM_TOOL_CALL - :ivar id: The unique ID of the custom tool call in the OpenAI platform. - :vartype id: str - :ivar call_id: An identifier used to map this custom tool call to a tool call output. Required. - :vartype call_id: str - :ivar name: The name of the custom tool being called. Required. - :vartype name: str - :ivar input: The input for the custom tool call generated by the model. Required. - :vartype input: str - """ - - type: Literal[OutputItemType.CUSTOM_TOOL_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the custom tool call. Always ``custom_tool_call``. Required. CUSTOM_TOOL_CALL.""" - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the custom tool call in the OpenAI platform.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """An identifier used to map this custom tool call to a tool call output. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the custom tool being called. Required.""" - input: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The input for the custom tool call generated by the model. Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - name: str, - input: str, - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - id: Optional[str] = None, # pylint: disable=redefined-builtin - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.CUSTOM_TOOL_CALL # type: ignore - - -class OutputItemCustomToolCallOutput(OutputItem, discriminator="custom_tool_call_output"): - """Custom tool call output. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: The type of the custom tool call output. Always ``custom_tool_call_output``. - Required. CUSTOM_TOOL_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CUSTOM_TOOL_CALL_OUTPUT - :ivar id: The unique ID of the custom tool call output in the OpenAI platform. - :vartype id: str - :ivar call_id: The call ID, used to map this custom tool call output to a custom tool call. - Required. - :vartype call_id: str - :ivar output: The output from the custom tool call generated by your code. Can be a string or - an list of output content. Required. Is either a str type or a - [FunctionAndCustomToolCallOutput] type. - :vartype output: str or - list[~azure.ai.agentserver.responses.models.models.FunctionAndCustomToolCallOutput] - """ - - type: Literal[OutputItemType.CUSTOM_TOOL_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the custom tool call output. Always ``custom_tool_call_output``. Required. - CUSTOM_TOOL_CALL_OUTPUT.""" - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the custom tool call output in the OpenAI platform.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The call ID, used to map this custom tool call output to a custom tool call. Required.""" - output: Union[str, list["_models.FunctionAndCustomToolCallOutput"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The output from the custom tool call generated by your code. Can be a string or an list of - output content. Required. Is either a str type or a [FunctionAndCustomToolCallOutput] type.""" - - @overload - def __init__( - self, - *, - call_id: str, - output: Union[str, list["_models.FunctionAndCustomToolCallOutput"]], - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - id: Optional[str] = None, # pylint: disable=redefined-builtin - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.CUSTOM_TOOL_CALL_OUTPUT # type: ignore - - -class OutputItemFileSearchToolCall(OutputItem, discriminator="file_search_call"): - """File search tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar id: The unique ID of the file search tool call. Required. - :vartype id: str - :ivar type: The type of the file search tool call. Always ``file_search_call``. Required. - FILE_SEARCH_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.FILE_SEARCH_CALL - :ivar status: The status of the file search tool call. One of ``in_progress``, ``searching``, - ``incomplete`` or ``failed``,. Required. Is one of the following types: Literal["in_progress"], - Literal["searching"], Literal["completed"], Literal["incomplete"], Literal["failed"] - :vartype status: str or str or str or str or str - :ivar queries: The queries used to search for files. Required. - :vartype queries: list[str] - :ivar results: - :vartype results: list[~azure.ai.agentserver.responses.models.models.FileSearchToolCallResults] - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the file search tool call. Required.""" - type: Literal[OutputItemType.FILE_SEARCH_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the file search tool call. Always ``file_search_call``. Required. FILE_SEARCH_CALL.""" - status: Literal["in_progress", "searching", "completed", "incomplete", "failed"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the file search tool call. One of ``in_progress``, ``searching``, ``incomplete`` - or ``failed``,. Required. Is one of the following types: Literal[\"in_progress\"], - Literal[\"searching\"], Literal[\"completed\"], Literal[\"incomplete\"], Literal[\"failed\"]""" - queries: list[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The queries used to search for files. Required.""" - results: Optional[list["_models.FileSearchToolCallResults"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - status: Literal["in_progress", "searching", "completed", "incomplete", "failed"], - queries: list[str], - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - results: Optional[list["_models.FileSearchToolCallResults"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.FILE_SEARCH_CALL # type: ignore - - -class OutputItemFunctionShellCall(OutputItem, discriminator="shell_call"): - """Shell tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: The type of the item. Always ``shell_call``. Required. SHELL_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.SHELL_CALL - :ivar id: The unique ID of the shell tool call. Populated when this item is returned via API. - Required. - :vartype id: str - :ivar call_id: The unique ID of the shell tool call generated by the model. Required. - :vartype call_id: str - :ivar action: The shell commands and limits that describe how to run the tool call. Required. - :vartype action: ~azure.ai.agentserver.responses.models.models.FunctionShellAction - :ivar status: The status of the shell call. One of ``in_progress``, ``completed``, or - ``incomplete``. Required. Known values are: "in_progress", "completed", and "incomplete". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.LocalShellCallStatus - :ivar environment: Required. - :vartype environment: - ~azure.ai.agentserver.responses.models.models.FunctionShellCallEnvironment - """ - - type: Literal[OutputItemType.SHELL_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``shell_call``. Required. SHELL_CALL.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the shell tool call. Populated when this item is returned via API. Required.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the shell tool call generated by the model. Required.""" - action: "_models.FunctionShellAction" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The shell commands and limits that describe how to run the tool call. Required.""" - status: Union[str, "_models.LocalShellCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the shell call. One of ``in_progress``, ``completed``, or ``incomplete``. - Required. Known values are: \"in_progress\", \"completed\", and \"incomplete\".""" - environment: "_models.FunctionShellCallEnvironment" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - call_id: str, - action: "_models.FunctionShellAction", - status: Union[str, "_models.LocalShellCallStatus"], - environment: "_models.FunctionShellCallEnvironment", - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.SHELL_CALL # type: ignore - - -class OutputItemFunctionShellCallOutput(OutputItem, discriminator="shell_call_output"): - """Shell call output. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: The type of the shell call output. Always ``shell_call_output``. Required. - SHELL_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.SHELL_CALL_OUTPUT - :ivar id: The unique ID of the shell call output. Populated when this item is returned via API. - Required. - :vartype id: str - :ivar call_id: The unique ID of the shell tool call generated by the model. Required. - :vartype call_id: str - :ivar status: The status of the shell call output. One of ``in_progress``, ``completed``, or - ``incomplete``. Required. Known values are: "in_progress", "completed", and "incomplete". - :vartype status: str or - ~azure.ai.agentserver.responses.models.models.LocalShellCallOutputStatusEnum - :ivar output: An array of shell call output contents. Required. - :vartype output: - list[~azure.ai.agentserver.responses.models.models.FunctionShellCallOutputContent] - :ivar max_output_length: Required. - :vartype max_output_length: int - """ - - type: Literal[OutputItemType.SHELL_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the shell call output. Always ``shell_call_output``. Required. SHELL_CALL_OUTPUT.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the shell call output. Populated when this item is returned via API. Required.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the shell tool call generated by the model. Required.""" - status: Union[str, "_models.LocalShellCallOutputStatusEnum"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the shell call output. One of ``in_progress``, ``completed``, or ``incomplete``. - Required. Known values are: \"in_progress\", \"completed\", and \"incomplete\".""" - output: list["_models.FunctionShellCallOutputContent"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """An array of shell call output contents. Required.""" - max_output_length: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - call_id: str, - status: Union[str, "_models.LocalShellCallOutputStatusEnum"], - output: list["_models.FunctionShellCallOutputContent"], - max_output_length: int, - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.SHELL_CALL_OUTPUT # type: ignore - - -class OutputItemFunctionToolCall(OutputItem, discriminator="function_call"): - """Function tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar id: The unique ID of the function tool call. - :vartype id: str - :ivar type: The type of the function tool call. Always ``function_call``. Required. - FUNCTION_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.FUNCTION_CALL - :ivar call_id: The unique ID of the function tool call generated by the model. Required. - :vartype call_id: str - :ivar name: The name of the function to run. Required. - :vartype name: str - :ivar arguments: A JSON string of the arguments to pass to the function. Required. - :vartype arguments: str - :ivar status: The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. - Populated when items are returned via API. Is one of the following types: - Literal["in_progress"], Literal["completed"], Literal["incomplete"] - :vartype status: str or str or str - """ - - id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the function tool call.""" - type: Literal[OutputItemType.FUNCTION_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the function tool call. Always ``function_call``. Required. FUNCTION_CALL.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the function tool call generated by the model. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the function to run. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of the arguments to pass to the function. Required.""" - status: Optional[Literal["in_progress", "completed", "incomplete"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. Populated - when items are returned via API. Is one of the following types: Literal[\"in_progress\"], - Literal[\"completed\"], Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - call_id: str, - name: str, - arguments: str, - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - id: Optional[str] = None, # pylint: disable=redefined-builtin - status: Optional[Literal["in_progress", "completed", "incomplete"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.FUNCTION_CALL # type: ignore - - -class OutputItemImageGenToolCall(OutputItem, discriminator="image_generation_call"): - """Image generation call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: The type of the image generation call. Always ``image_generation_call``. Required. - IMAGE_GENERATION_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.IMAGE_GENERATION_CALL - :ivar id: The unique ID of the image generation call. Required. - :vartype id: str - :ivar status: The status of the image generation call. Required. Is one of the following types: - Literal["in_progress"], Literal["completed"], Literal["generating"], Literal["failed"] - :vartype status: str or str or str or str - :ivar result: Required. - :vartype result: str - """ - - type: Literal[OutputItemType.IMAGE_GENERATION_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the image generation call. Always ``image_generation_call``. Required. - IMAGE_GENERATION_CALL.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the image generation call. Required.""" - status: Literal["in_progress", "completed", "generating", "failed"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the image generation call. Required. Is one of the following types: - Literal[\"in_progress\"], Literal[\"completed\"], Literal[\"generating\"], Literal[\"failed\"]""" - result: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - status: Literal["in_progress", "completed", "generating", "failed"], - result: str, - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.IMAGE_GENERATION_CALL # type: ignore - - -class OutputItemLocalShellToolCall(OutputItem, discriminator="local_shell_call"): - """Local shell call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: The type of the local shell call. Always ``local_shell_call``. Required. - LOCAL_SHELL_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.LOCAL_SHELL_CALL - :ivar id: The unique ID of the local shell call. Required. - :vartype id: str - :ivar call_id: The unique ID of the local shell tool call generated by the model. Required. - :vartype call_id: str - :ivar action: Required. - :vartype action: ~azure.ai.agentserver.responses.models.models.LocalShellExecAction - :ivar status: The status of the local shell call. Required. Is one of the following types: - Literal["in_progress"], Literal["completed"], Literal["incomplete"] - :vartype status: str or str or str - """ - - type: Literal[OutputItemType.LOCAL_SHELL_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the local shell call. Always ``local_shell_call``. Required. LOCAL_SHELL_CALL.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the local shell call. Required.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the local shell tool call generated by the model. Required.""" - action: "_models.LocalShellExecAction" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - status: Literal["in_progress", "completed", "incomplete"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the local shell call. Required. Is one of the following types: - Literal[\"in_progress\"], Literal[\"completed\"], Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - call_id: str, - action: "_models.LocalShellExecAction", - status: Literal["in_progress", "completed", "incomplete"], - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.LOCAL_SHELL_CALL # type: ignore - - -class OutputItemLocalShellToolCallOutput(OutputItem, discriminator="local_shell_call_output"): - """Local shell call output. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: The type of the local shell tool call output. Always ``local_shell_call_output``. - Required. LOCAL_SHELL_CALL_OUTPUT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.LOCAL_SHELL_CALL_OUTPUT - :ivar id: The unique ID of the local shell tool call generated by the model. Required. - :vartype id: str - :ivar output: A JSON string of the output of the local shell tool call. Required. - :vartype output: str - :ivar status: Is one of the following types: Literal["in_progress"], Literal["completed"], - Literal["incomplete"] - :vartype status: str or str or str - """ - - type: Literal[OutputItemType.LOCAL_SHELL_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the local shell tool call output. Always ``local_shell_call_output``. Required. - LOCAL_SHELL_CALL_OUTPUT.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the local shell tool call generated by the model. Required.""" - output: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of the output of the local shell tool call. Required.""" - status: Optional[Literal["in_progress", "completed", "incomplete"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Is one of the following types: Literal[\"in_progress\"], Literal[\"completed\"], - Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - output: str, - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - status: Optional[Literal["in_progress", "completed", "incomplete"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.LOCAL_SHELL_CALL_OUTPUT # type: ignore - - -class OutputItemMcpApprovalRequest(OutputItem, discriminator="mcp_approval_request"): - """MCP approval request. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: The type of the item. Always ``mcp_approval_request``. Required. - MCP_APPROVAL_REQUEST. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MCP_APPROVAL_REQUEST - :ivar id: The unique ID of the approval request. Required. - :vartype id: str - :ivar server_label: The label of the MCP server making the request. Required. - :vartype server_label: str - :ivar name: The name of the tool to run. Required. - :vartype name: str - :ivar arguments: A JSON string of arguments for the tool. Required. - :vartype arguments: str - """ - - type: Literal[OutputItemType.MCP_APPROVAL_REQUEST] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``mcp_approval_request``. Required. MCP_APPROVAL_REQUEST.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the approval request. Required.""" - server_label: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The label of the MCP server making the request. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the tool to run. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of arguments for the tool. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - server_label: str, - name: str, - arguments: str, - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.MCP_APPROVAL_REQUEST # type: ignore - - -class OutputItemMcpApprovalResponseResource(OutputItem, discriminator="mcp_approval_response"): - """MCP approval response. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: The type of the item. Always ``mcp_approval_response``. Required. - MCP_APPROVAL_RESPONSE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MCP_APPROVAL_RESPONSE - :ivar id: The unique ID of the approval response. Required. - :vartype id: str - :ivar approval_request_id: The ID of the approval request being answered. Required. - :vartype approval_request_id: str - :ivar approve: Whether the request was approved. Required. - :vartype approve: bool - :ivar reason: - :vartype reason: str - """ - - type: Literal[OutputItemType.MCP_APPROVAL_RESPONSE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``mcp_approval_response``. Required. MCP_APPROVAL_RESPONSE.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the approval response. Required.""" - approval_request_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the approval request being answered. Required.""" - approve: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Whether the request was approved. Required.""" - reason: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - approval_request_id: str, - approve: bool, - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - reason: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.MCP_APPROVAL_RESPONSE # type: ignore - - -class OutputItemMcpListTools(OutputItem, discriminator="mcp_list_tools"): - """MCP list tools. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: The type of the item. Always ``mcp_list_tools``. Required. MCP_LIST_TOOLS. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MCP_LIST_TOOLS - :ivar id: The unique ID of the list. Required. - :vartype id: str - :ivar server_label: The label of the MCP server. Required. - :vartype server_label: str - :ivar tools: The tools available on the server. Required. - :vartype tools: list[~azure.ai.agentserver.responses.models.models.MCPListToolsTool] - :ivar error: - :vartype error: str - """ - - type: Literal[OutputItemType.MCP_LIST_TOOLS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``mcp_list_tools``. Required. MCP_LIST_TOOLS.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the list. Required.""" - server_label: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The label of the MCP server. Required.""" - tools: list["_models.MCPListToolsTool"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The tools available on the server. Required.""" - error: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - server_label: str, - tools: list["_models.MCPListToolsTool"], - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - error: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.MCP_LIST_TOOLS # type: ignore - - -class OutputItemMcpToolCall(OutputItem, discriminator="mcp_call"): - """MCP tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: The type of the item. Always ``mcp_call``. Required. MCP_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MCP_CALL - :ivar id: The unique ID of the tool call. Required. - :vartype id: str - :ivar server_label: The label of the MCP server running the tool. Required. - :vartype server_label: str - :ivar name: The name of the tool that was run. Required. - :vartype name: str - :ivar arguments: A JSON string of the arguments passed to the tool. Required. - :vartype arguments: str - :ivar output: - :vartype output: str - :ivar error: - :vartype error: dict[str, any] - :ivar status: The status of the tool call. One of ``in_progress``, ``completed``, - ``incomplete``, ``calling``, or ``failed``. Known values are: "in_progress", "completed", - "incomplete", "calling", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.MCPToolCallStatus - :ivar approval_request_id: - :vartype approval_request_id: str - """ - - type: Literal[OutputItemType.MCP_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the item. Always ``mcp_call``. Required. MCP_CALL.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call. Required.""" - server_label: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The label of the MCP server running the tool. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the tool that was run. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of the arguments passed to the tool. Required.""" - output: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - error: Optional[dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - status: Optional[Union[str, "_models.MCPToolCallStatus"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. One of ``in_progress``, ``completed``, ``incomplete``, - ``calling``, or ``failed``. Known values are: \"in_progress\", \"completed\", \"incomplete\", - \"calling\", and \"failed\".""" - approval_request_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - server_label: str, - name: str, - arguments: str, - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - output: Optional[str] = None, - error: Optional[dict[str, Any]] = None, - status: Optional[Union[str, "_models.MCPToolCallStatus"]] = None, - approval_request_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.MCP_CALL # type: ignore - - -class OutputItemMessage(OutputItem, discriminator="message"): - """Message. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: The type of the message. Always set to ``message``. Required. MESSAGE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MESSAGE - :ivar id: The unique ID of the message. Required. - :vartype id: str - :ivar status: The status of item. One of ``in_progress``, ``completed``, or ``incomplete``. - Populated when items are returned via API. Required. Known values are: "in_progress", - "completed", and "incomplete". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.MessageStatus - :ivar role: The role of the message. One of ``unknown``, ``user``, ``assistant``, ``system``, - ``critic``, ``discriminator``, ``developer``, or ``tool``. Required. Known values are: - "unknown", "user", "assistant", "system", "critic", "discriminator", "developer", and "tool". - :vartype role: str or ~azure.ai.agentserver.responses.models.models.MessageRole - :ivar content: The content of the message. Required. - :vartype content: list[~azure.ai.agentserver.responses.models.models.MessageContent] - """ - - type: Literal[OutputItemType.MESSAGE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the message. Always set to ``message``. Required. MESSAGE.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the message. Required.""" - status: Union[str, "_models.MessageStatus"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The status of item. One of ``in_progress``, ``completed``, or ``incomplete``. Populated when - items are returned via API. Required. Known values are: \"in_progress\", \"completed\", and - \"incomplete\".""" - role: Union[str, "_models.MessageRole"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The role of the message. One of ``unknown``, ``user``, ``assistant``, ``system``, ``critic``, - ``discriminator``, ``developer``, or ``tool``. Required. Known values are: \"unknown\", - \"user\", \"assistant\", \"system\", \"critic\", \"discriminator\", \"developer\", and - \"tool\".""" - content: list["_models.MessageContent"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The content of the message. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - status: Union[str, "_models.MessageStatus"], - role: Union[str, "_models.MessageRole"], - content: list["_models.MessageContent"], - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.MESSAGE # type: ignore - - -class OutputItemOutputMessage(OutputItem, discriminator="output_message"): - """Output message. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar id: The unique ID of the output message. Required. - :vartype id: str - :ivar type: The type of the output message. Always ``message``. Required. OUTPUT_MESSAGE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.OUTPUT_MESSAGE - :ivar role: The role of the output message. Always ``assistant``. Required. Default value is - "assistant". - :vartype role: str - :ivar content: The content of the output message. Required. - :vartype content: list[~azure.ai.agentserver.responses.models.models.OutputMessageContent] - :ivar status: The status of the message input. One of ``in_progress``, ``completed``, or - ``incomplete``. Populated when input items are returned via API. Required. Is one of the - following types: Literal["in_progress"], Literal["completed"], Literal["incomplete"] - :vartype status: str or str or str - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the output message. Required.""" - type: Literal[OutputItemType.OUTPUT_MESSAGE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the output message. Always ``message``. Required. OUTPUT_MESSAGE.""" - role: Literal["assistant"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The role of the output message. Always ``assistant``. Required. Default value is \"assistant\".""" - content: list["_models.OutputMessageContent"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The content of the output message. Required.""" - status: Literal["in_progress", "completed", "incomplete"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the message input. One of ``in_progress``, ``completed``, or ``incomplete``. - Populated when input items are returned via API. Required. Is one of the following types: - Literal[\"in_progress\"], Literal[\"completed\"], Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - content: list["_models.OutputMessageContent"], - status: Literal["in_progress", "completed", "incomplete"], - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.OUTPUT_MESSAGE # type: ignore - self.role: Literal["assistant"] = "assistant" - - -class OutputItemReasoningItem(OutputItem, discriminator="reasoning"): - """Reasoning. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: The type of the object. Always ``reasoning``. Required. REASONING. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.REASONING - :ivar id: The unique identifier of the reasoning content. Required. - :vartype id: str - :ivar encrypted_content: - :vartype encrypted_content: str - :ivar summary: Reasoning summary content. Required. - :vartype summary: list[~azure.ai.agentserver.responses.models.models.SummaryTextContent] - :ivar content: Reasoning text content. - :vartype content: list[~azure.ai.agentserver.responses.models.models.ReasoningTextContent] - :ivar status: The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. - Populated when items are returned via API. Is one of the following types: - Literal["in_progress"], Literal["completed"], Literal["incomplete"] - :vartype status: str or str or str - """ - - type: Literal[OutputItemType.REASONING] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the object. Always ``reasoning``. Required. REASONING.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique identifier of the reasoning content. Required.""" - encrypted_content: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - summary: list["_models.SummaryTextContent"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Reasoning summary content. Required.""" - content: Optional[list["_models.ReasoningTextContent"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Reasoning text content.""" - status: Optional[Literal["in_progress", "completed", "incomplete"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the item. One of ``in_progress``, ``completed``, or ``incomplete``. Populated - when items are returned via API. Is one of the following types: Literal[\"in_progress\"], - Literal[\"completed\"], Literal[\"incomplete\"]""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - summary: list["_models.SummaryTextContent"], - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - encrypted_content: Optional[str] = None, - content: Optional[list["_models.ReasoningTextContent"]] = None, - status: Optional[Literal["in_progress", "completed", "incomplete"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.REASONING # type: ignore - - -class OutputItemWebSearchToolCall(OutputItem, discriminator="web_search_call"): - """Web search tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar id: The unique ID of the web search tool call. Required. - :vartype id: str - :ivar type: The type of the web search tool call. Always ``web_search_call``. Required. - WEB_SEARCH_CALL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.WEB_SEARCH_CALL - :ivar status: The status of the web search tool call. Required. Is one of the following types: - Literal["in_progress"], Literal["searching"], Literal["completed"], Literal["failed"] - :vartype status: str or str or str or str - :ivar action: An object describing the specific action taken in this web search call. Includes - details on how the model used the web (search, open_page, find_in_page). Required. Is one of - the following types: WebSearchActionSearch, WebSearchActionOpenPage, WebSearchActionFind - :vartype action: ~azure.ai.agentserver.responses.models.models.WebSearchActionSearch or - ~azure.ai.agentserver.responses.models.models.WebSearchActionOpenPage or - ~azure.ai.agentserver.responses.models.models.WebSearchActionFind - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the web search tool call. Required.""" - type: Literal[OutputItemType.WEB_SEARCH_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the web search tool call. Always ``web_search_call``. Required. WEB_SEARCH_CALL.""" - status: Literal["in_progress", "searching", "completed", "failed"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the web search tool call. Required. Is one of the following types: - Literal[\"in_progress\"], Literal[\"searching\"], Literal[\"completed\"], Literal[\"failed\"]""" - action: Union["_models.WebSearchActionSearch", "_models.WebSearchActionOpenPage", "_models.WebSearchActionFind"] = ( - rest_field(visibility=["read", "create", "update", "delete", "query"]) - ) - """An object describing the specific action taken in this web search call. Includes details on how - the model used the web (search, open_page, find_in_page). Required. Is one of the following - types: WebSearchActionSearch, WebSearchActionOpenPage, WebSearchActionFind""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - status: Literal["in_progress", "searching", "completed", "failed"], - action: Union[ - "_models.WebSearchActionSearch", "_models.WebSearchActionOpenPage", "_models.WebSearchActionFind" - ], - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.WEB_SEARCH_CALL # type: ignore - - -class OutputMessageContent(_Model): - """OutputMessageContent. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - OutputMessageContentOutputTextContent, OutputMessageContentRefusalContent - - :ivar type: Required. Known values are: "output_text" and "refusal". - :vartype type: str or ~azure.ai.agentserver.responses.models.models.OutputMessageContentType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"output_text\" and \"refusal\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class OutputMessageContentOutputTextContent(OutputMessageContent, discriminator="output_text"): - """Output text. - - :ivar type: The type of the output text. Always ``output_text``. Required. OUTPUT_TEXT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.OUTPUT_TEXT - :ivar text: The text output from the model. Required. - :vartype text: str - :ivar annotations: The annotations of the text output. Required. - :vartype annotations: list[~azure.ai.agentserver.responses.models.models.Annotation] - :ivar logprobs: Required. - :vartype logprobs: list[~azure.ai.agentserver.responses.models.models.LogProb] - """ - - type: Literal[OutputMessageContentType.OUTPUT_TEXT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the output text. Always ``output_text``. Required. OUTPUT_TEXT.""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The text output from the model. Required.""" - annotations: list["_models.Annotation"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The annotations of the text output. Required.""" - logprobs: list["_models.LogProb"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - text: str, - annotations: list["_models.Annotation"], - logprobs: list["_models.LogProb"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputMessageContentType.OUTPUT_TEXT # type: ignore - - -class OutputMessageContentRefusalContent(OutputMessageContent, discriminator="refusal"): - """Refusal. - - :ivar type: The type of the refusal. Always ``refusal``. Required. REFUSAL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.REFUSAL - :ivar refusal: The refusal explanation from the model. Required. - :vartype refusal: str - """ - - type: Literal[OutputMessageContentType.REFUSAL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the refusal. Always ``refusal``. Required. REFUSAL.""" - refusal: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The refusal explanation from the model. Required.""" - - @overload - def __init__( - self, - *, - refusal: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputMessageContentType.REFUSAL # type: ignore - - -class Prompt(_Model): - """Reference to a prompt template and its variables. `Learn more - `_. - - :ivar id: The unique identifier of the prompt template to use. Required. - :vartype id: str - :ivar version: - :vartype version: str - :ivar variables: - :vartype variables: ~azure.ai.agentserver.responses.models.models.ResponsePromptVariables - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique identifier of the prompt template to use. Required.""" - version: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - variables: Optional["_models.ResponsePromptVariables"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - version: Optional[str] = None, - variables: Optional["_models.ResponsePromptVariables"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class RankingOptions(_Model): - """RankingOptions. - - :ivar ranker: The ranker to use for the file search. Known values are: "auto" and - "default-2024-11-15". - :vartype ranker: str or ~azure.ai.agentserver.responses.models.models.RankerVersionType - :ivar score_threshold: The score threshold for the file search, a number between 0 and 1. - Numbers closer to 1 will attempt to return only the most relevant results, but may return fewer - results. - :vartype score_threshold: int - :ivar hybrid_search: Weights that control how reciprocal rank fusion balances semantic - embedding matches versus sparse keyword matches when hybrid search is enabled. - :vartype hybrid_search: ~azure.ai.agentserver.responses.models.models.HybridSearchOptions - """ - - ranker: Optional[Union[str, "_models.RankerVersionType"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The ranker to use for the file search. Known values are: \"auto\" and \"default-2024-11-15\".""" - score_threshold: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The score threshold for the file search, a number between 0 and 1. Numbers closer to 1 will - attempt to return only the most relevant results, but may return fewer results.""" - hybrid_search: Optional["_models.HybridSearchOptions"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Weights that control how reciprocal rank fusion balances semantic embedding matches versus - sparse keyword matches when hybrid search is enabled.""" - - @overload - def __init__( - self, - *, - ranker: Optional[Union[str, "_models.RankerVersionType"]] = None, - score_threshold: Optional[int] = None, - hybrid_search: Optional["_models.HybridSearchOptions"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class Reasoning(_Model): - """Reasoning. - - :ivar effort: Is one of the following types: Literal["none"], Literal["minimal"], - Literal["low"], Literal["medium"], Literal["high"], Literal["xhigh"] - :vartype effort: str or str or str or str or str or str - :ivar summary: Is one of the following types: Literal["auto"], Literal["concise"], - Literal["detailed"] - :vartype summary: str or str or str - :ivar generate_summary: Is one of the following types: Literal["auto"], Literal["concise"], - Literal["detailed"] - :vartype generate_summary: str or str or str - """ - - effort: Optional[Literal["none", "minimal", "low", "medium", "high", "xhigh"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Is one of the following types: Literal[\"none\"], Literal[\"minimal\"], Literal[\"low\"], - Literal[\"medium\"], Literal[\"high\"], Literal[\"xhigh\"]""" - summary: Optional[Literal["auto", "concise", "detailed"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Is one of the following types: Literal[\"auto\"], Literal[\"concise\"], Literal[\"detailed\"]""" - generate_summary: Optional[Literal["auto", "concise", "detailed"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Is one of the following types: Literal[\"auto\"], Literal[\"concise\"], Literal[\"detailed\"]""" - - @overload - def __init__( - self, - *, - effort: Optional[Literal["none", "minimal", "low", "medium", "high", "xhigh"]] = None, - summary: Optional[Literal["auto", "concise", "detailed"]] = None, - generate_summary: Optional[Literal["auto", "concise", "detailed"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ReasoningTextContent(_Model): - """Reasoning text. - - :ivar type: The type of the reasoning text. Always ``reasoning_text``. Required. Default value - is "reasoning_text". - :vartype type: str - :ivar text: The reasoning text from the model. Required. - :vartype text: str - """ - - type: Literal["reasoning_text"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The type of the reasoning text. Always ``reasoning_text``. Required. Default value is - \"reasoning_text\".""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The reasoning text from the model. Required.""" - - @overload - def __init__( - self, - *, - text: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["reasoning_text"] = "reasoning_text" - - -class ResponseStreamEvent(_Model): - """ResponseStreamEvent. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ResponseErrorEvent, ResponseAudioDeltaEvent, ResponseAudioDoneEvent, - ResponseAudioTranscriptDeltaEvent, ResponseAudioTranscriptDoneEvent, - ResponseCodeInterpreterCallCompletedEvent, ResponseCodeInterpreterCallInProgressEvent, - ResponseCodeInterpreterCallInterpretingEvent, ResponseCodeInterpreterCallCodeDeltaEvent, - ResponseCodeInterpreterCallCodeDoneEvent, ResponseCompletedEvent, - ResponseContentPartAddedEvent, ResponseContentPartDoneEvent, ResponseCreatedEvent, - ResponseCustomToolCallInputDeltaEvent, ResponseCustomToolCallInputDoneEvent, - ResponseFailedEvent, ResponseFileSearchCallCompletedEvent, - ResponseFileSearchCallInProgressEvent, ResponseFileSearchCallSearchingEvent, - ResponseFunctionCallArgumentsDeltaEvent, ResponseFunctionCallArgumentsDoneEvent, - ResponseImageGenCallCompletedEvent, ResponseImageGenCallGeneratingEvent, - ResponseImageGenCallInProgressEvent, ResponseImageGenCallPartialImageEvent, - ResponseInProgressEvent, ResponseIncompleteEvent, ResponseMCPCallCompletedEvent, - ResponseMCPCallFailedEvent, ResponseMCPCallInProgressEvent, ResponseMCPCallArgumentsDeltaEvent, - ResponseMCPCallArgumentsDoneEvent, ResponseMCPListToolsCompletedEvent, - ResponseMCPListToolsFailedEvent, ResponseMCPListToolsInProgressEvent, - ResponseOutputItemAddedEvent, ResponseOutputItemDoneEvent, - ResponseOutputTextAnnotationAddedEvent, ResponseTextDeltaEvent, ResponseTextDoneEvent, - ResponseQueuedEvent, ResponseReasoningSummaryPartAddedEvent, - ResponseReasoningSummaryPartDoneEvent, ResponseReasoningSummaryTextDeltaEvent, - ResponseReasoningSummaryTextDoneEvent, ResponseReasoningTextDeltaEvent, - ResponseReasoningTextDoneEvent, ResponseRefusalDeltaEvent, ResponseRefusalDoneEvent, - ResponseWebSearchCallCompletedEvent, ResponseWebSearchCallInProgressEvent, - ResponseWebSearchCallSearchingEvent - - :ivar type: Required. Known values are: "response.audio.delta", "response.audio.done", - "response.audio.transcript.delta", "response.audio.transcript.done", - "response.code_interpreter_call_code.delta", "response.code_interpreter_call_code.done", - "response.code_interpreter_call.completed", "response.code_interpreter_call.in_progress", - "response.code_interpreter_call.interpreting", "response.completed", - "response.content_part.added", "response.content_part.done", "response.created", "error", - "response.file_search_call.completed", "response.file_search_call.in_progress", - "response.file_search_call.searching", "response.function_call_arguments.delta", - "response.function_call_arguments.done", "response.in_progress", "response.failed", - "response.incomplete", "response.output_item.added", "response.output_item.done", - "response.reasoning_summary_part.added", "response.reasoning_summary_part.done", - "response.reasoning_summary_text.delta", "response.reasoning_summary_text.done", - "response.reasoning_text.delta", "response.reasoning_text.done", "response.refusal.delta", - "response.refusal.done", "response.output_text.delta", "response.output_text.done", - "response.web_search_call.completed", "response.web_search_call.in_progress", - "response.web_search_call.searching", "response.image_generation_call.completed", - "response.image_generation_call.generating", "response.image_generation_call.in_progress", - "response.image_generation_call.partial_image", "response.mcp_call_arguments.delta", - "response.mcp_call_arguments.done", "response.mcp_call.completed", "response.mcp_call.failed", - "response.mcp_call.in_progress", "response.mcp_list_tools.completed", - "response.mcp_list_tools.failed", "response.mcp_list_tools.in_progress", - "response.output_text.annotation.added", "response.queued", - "response.custom_tool_call_input.delta", and "response.custom_tool_call_input.done". - :vartype type: str or ~azure.ai.agentserver.responses.models.models.ResponseStreamEventType - :ivar sequence_number: Required. - :vartype sequence_number: int - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"response.audio.delta\", \"response.audio.done\", - \"response.audio.transcript.delta\", \"response.audio.transcript.done\", - \"response.code_interpreter_call_code.delta\", \"response.code_interpreter_call_code.done\", - \"response.code_interpreter_call.completed\", \"response.code_interpreter_call.in_progress\", - \"response.code_interpreter_call.interpreting\", \"response.completed\", - \"response.content_part.added\", \"response.content_part.done\", \"response.created\", - \"error\", \"response.file_search_call.completed\", \"response.file_search_call.in_progress\", - \"response.file_search_call.searching\", \"response.function_call_arguments.delta\", - \"response.function_call_arguments.done\", \"response.in_progress\", \"response.failed\", - \"response.incomplete\", \"response.output_item.added\", \"response.output_item.done\", - \"response.reasoning_summary_part.added\", \"response.reasoning_summary_part.done\", - \"response.reasoning_summary_text.delta\", \"response.reasoning_summary_text.done\", - \"response.reasoning_text.delta\", \"response.reasoning_text.done\", - \"response.refusal.delta\", \"response.refusal.done\", \"response.output_text.delta\", - \"response.output_text.done\", \"response.web_search_call.completed\", - \"response.web_search_call.in_progress\", \"response.web_search_call.searching\", - \"response.image_generation_call.completed\", \"response.image_generation_call.generating\", - \"response.image_generation_call.in_progress\", - \"response.image_generation_call.partial_image\", \"response.mcp_call_arguments.delta\", - \"response.mcp_call_arguments.done\", \"response.mcp_call.completed\", - \"response.mcp_call.failed\", \"response.mcp_call.in_progress\", - \"response.mcp_list_tools.completed\", \"response.mcp_list_tools.failed\", - \"response.mcp_list_tools.in_progress\", \"response.output_text.annotation.added\", - \"response.queued\", \"response.custom_tool_call_input.delta\", and - \"response.custom_tool_call_input.done\".""" - sequence_number: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - type: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ResponseAudioDeltaEvent(ResponseStreamEvent, discriminator="response.audio.delta"): - """Emitted when there is a partial audio response. - - :ivar type: The type of the event. Always ``response.audio.delta``. Required. - RESPONSE_AUDIO_DELTA. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.RESPONSE_AUDIO_DELTA - :ivar sequence_number: A sequence number for this chunk of the stream response. Required. - :vartype sequence_number: int - :ivar delta: A chunk of Base64 encoded response audio bytes. Required. - :vartype delta: bytes - """ - - type: Literal[ResponseStreamEventType.RESPONSE_AUDIO_DELTA] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.audio.delta``. Required. RESPONSE_AUDIO_DELTA.""" - delta: bytes = rest_field(visibility=["read", "create", "update", "delete", "query"], format="base64") - """A chunk of Base64 encoded response audio bytes. Required.""" - - @overload - def __init__( - self, - *, - sequence_number: int, - delta: bytes, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_AUDIO_DELTA # type: ignore - - -class ResponseAudioDoneEvent(ResponseStreamEvent, discriminator="response.audio.done"): - """Emitted when the audio response is complete. - - :ivar type: The type of the event. Always ``response.audio.done``. Required. - RESPONSE_AUDIO_DONE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.RESPONSE_AUDIO_DONE - :ivar sequence_number: The sequence number of the delta. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_AUDIO_DONE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.audio.done``. Required. RESPONSE_AUDIO_DONE.""" - - @overload - def __init__( - self, - *, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_AUDIO_DONE # type: ignore - - -class ResponseAudioTranscriptDeltaEvent(ResponseStreamEvent, discriminator="response.audio.transcript.delta"): - """Emitted when there is a partial transcript of audio. - - :ivar type: The type of the event. Always ``response.audio.transcript.delta``. Required. - RESPONSE_AUDIO_TRANSCRIPT_DELTA. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_AUDIO_TRANSCRIPT_DELTA - :ivar delta: The partial transcript of the audio response. Required. - :vartype delta: str - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_AUDIO_TRANSCRIPT_DELTA] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.audio.transcript.delta``. Required. - RESPONSE_AUDIO_TRANSCRIPT_DELTA.""" - delta: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The partial transcript of the audio response. Required.""" - - @overload - def __init__( - self, - *, - delta: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_AUDIO_TRANSCRIPT_DELTA # type: ignore - - -class ResponseAudioTranscriptDoneEvent(ResponseStreamEvent, discriminator="response.audio.transcript.done"): - """Emitted when the full audio transcript is completed. - - :ivar type: The type of the event. Always ``response.audio.transcript.done``. Required. - RESPONSE_AUDIO_TRANSCRIPT_DONE. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_AUDIO_TRANSCRIPT_DONE - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_AUDIO_TRANSCRIPT_DONE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.audio.transcript.done``. Required. - RESPONSE_AUDIO_TRANSCRIPT_DONE.""" - - @overload - def __init__( - self, - *, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_AUDIO_TRANSCRIPT_DONE # type: ignore - - -class ResponseCodeInterpreterCallCodeDeltaEvent( - ResponseStreamEvent, discriminator="response.code_interpreter_call_code.delta" -): # pylint: disable=name-too-long - """Emitted when a partial code snippet is streamed by the code interpreter. - - :ivar type: The type of the event. Always ``response.code_interpreter_call_code.delta``. - Required. RESPONSE_CODE_INTERPRETER_CALL_CODE_DELTA. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_CODE_INTERPRETER_CALL_CODE_DELTA - :ivar output_index: The index of the output item in the response for which the code is being - streamed. Required. - :vartype output_index: int - :ivar item_id: The unique identifier of the code interpreter tool call item. Required. - :vartype item_id: str - :ivar delta: The partial code snippet being streamed by the code interpreter. Required. - :vartype delta: str - :ivar sequence_number: The sequence number of this event, used to order streaming events. - Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_CODE_DELTA] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.code_interpreter_call_code.delta``. Required. - RESPONSE_CODE_INTERPRETER_CALL_CODE_DELTA.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item in the response for which the code is being streamed. Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique identifier of the code interpreter tool call item. Required.""" - delta: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The partial code snippet being streamed by the code interpreter. Required.""" - - @overload - def __init__( - self, - *, - output_index: int, - item_id: str, - delta: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_CODE_DELTA # type: ignore - - -class ResponseCodeInterpreterCallCodeDoneEvent( - ResponseStreamEvent, discriminator="response.code_interpreter_call_code.done" -): - """Emitted when the code snippet is finalized by the code interpreter. - - :ivar type: The type of the event. Always ``response.code_interpreter_call_code.done``. - Required. RESPONSE_CODE_INTERPRETER_CALL_CODE_DONE. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_CODE_INTERPRETER_CALL_CODE_DONE - :ivar output_index: The index of the output item in the response for which the code is - finalized. Required. - :vartype output_index: int - :ivar item_id: The unique identifier of the code interpreter tool call item. Required. - :vartype item_id: str - :ivar code: The final code snippet output by the code interpreter. Required. - :vartype code: str - :ivar sequence_number: The sequence number of this event, used to order streaming events. - Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_CODE_DONE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.code_interpreter_call_code.done``. Required. - RESPONSE_CODE_INTERPRETER_CALL_CODE_DONE.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item in the response for which the code is finalized. Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique identifier of the code interpreter tool call item. Required.""" - code: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The final code snippet output by the code interpreter. Required.""" - - @overload - def __init__( - self, - *, - output_index: int, - item_id: str, - code: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_CODE_DONE # type: ignore - - -class ResponseCodeInterpreterCallCompletedEvent( - ResponseStreamEvent, discriminator="response.code_interpreter_call.completed" -): # pylint: disable=name-too-long - """Emitted when the code interpreter call is completed. - - :ivar type: The type of the event. Always ``response.code_interpreter_call.completed``. - Required. RESPONSE_CODE_INTERPRETER_CALL_COMPLETED. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_CODE_INTERPRETER_CALL_COMPLETED - :ivar output_index: The index of the output item in the response for which the code interpreter - call is completed. Required. - :vartype output_index: int - :ivar item_id: The unique identifier of the code interpreter tool call item. Required. - :vartype item_id: str - :ivar sequence_number: The sequence number of this event, used to order streaming events. - Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_COMPLETED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.code_interpreter_call.completed``. Required. - RESPONSE_CODE_INTERPRETER_CALL_COMPLETED.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item in the response for which the code interpreter call is completed. - Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique identifier of the code interpreter tool call item. Required.""" - - @overload - def __init__( - self, - *, - output_index: int, - item_id: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_COMPLETED # type: ignore - - -class ResponseCodeInterpreterCallInProgressEvent( - ResponseStreamEvent, discriminator="response.code_interpreter_call.in_progress" -): # pylint: disable=name-too-long - """Emitted when a code interpreter call is in progress. - - :ivar type: The type of the event. Always ``response.code_interpreter_call.in_progress``. - Required. RESPONSE_CODE_INTERPRETER_CALL_IN_PROGRESS. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_CODE_INTERPRETER_CALL_IN_PROGRESS - :ivar output_index: The index of the output item in the response for which the code interpreter - call is in progress. Required. - :vartype output_index: int - :ivar item_id: The unique identifier of the code interpreter tool call item. Required. - :vartype item_id: str - :ivar sequence_number: The sequence number of this event, used to order streaming events. - Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_IN_PROGRESS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.code_interpreter_call.in_progress``. Required. - RESPONSE_CODE_INTERPRETER_CALL_IN_PROGRESS.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item in the response for which the code interpreter call is in - progress. Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique identifier of the code interpreter tool call item. Required.""" - - @overload - def __init__( - self, - *, - output_index: int, - item_id: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_IN_PROGRESS # type: ignore - - -class ResponseCodeInterpreterCallInterpretingEvent( - ResponseStreamEvent, discriminator="response.code_interpreter_call.interpreting" -): # pylint: disable=name-too-long - """Emitted when the code interpreter is actively interpreting the code snippet. - - :ivar type: The type of the event. Always ``response.code_interpreter_call.interpreting``. - Required. RESPONSE_CODE_INTERPRETER_CALL_INTERPRETING. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_CODE_INTERPRETER_CALL_INTERPRETING - :ivar output_index: The index of the output item in the response for which the code interpreter - is interpreting code. Required. - :vartype output_index: int - :ivar item_id: The unique identifier of the code interpreter tool call item. Required. - :vartype item_id: str - :ivar sequence_number: The sequence number of this event, used to order streaming events. - Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_INTERPRETING] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.code_interpreter_call.interpreting``. Required. - RESPONSE_CODE_INTERPRETER_CALL_INTERPRETING.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item in the response for which the code interpreter is interpreting - code. Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique identifier of the code interpreter tool call item. Required.""" - - @overload - def __init__( - self, - *, - output_index: int, - item_id: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_INTERPRETING # type: ignore - - -class ResponseCompletedEvent(ResponseStreamEvent, discriminator="response.completed"): - """Emitted when the model response is complete. - - :ivar type: The type of the event. Always ``response.completed``. Required. RESPONSE_COMPLETED. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.RESPONSE_COMPLETED - :ivar response: Properties of the completed response. Required. - :vartype response: ~azure.ai.agentserver.responses.models.models.ResponseObject - :ivar sequence_number: The sequence number for this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_COMPLETED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.completed``. Required. RESPONSE_COMPLETED.""" - response: "_models.ResponseObject" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Properties of the completed response. Required.""" - - @overload - def __init__( - self, - *, - response: "_models.ResponseObject", - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_COMPLETED # type: ignore - - -class ResponseContentPartAddedEvent(ResponseStreamEvent, discriminator="response.content_part.added"): - """Emitted when a new content part is added. - - :ivar type: The type of the event. Always ``response.content_part.added``. Required. - RESPONSE_CONTENT_PART_ADDED. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.RESPONSE_CONTENT_PART_ADDED - :ivar item_id: The ID of the output item that the content part was added to. Required. - :vartype item_id: str - :ivar output_index: The index of the output item that the content part was added to. Required. - :vartype output_index: int - :ivar content_index: The index of the content part that was added. Required. - :vartype content_index: int - :ivar part: The content part that was added. Required. - :vartype part: ~azure.ai.agentserver.responses.models.models.OutputContent - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_CONTENT_PART_ADDED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.content_part.added``. Required. - RESPONSE_CONTENT_PART_ADDED.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the output item that the content part was added to. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that the content part was added to. Required.""" - content_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the content part that was added. Required.""" - part: "_models.OutputContent" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The content part that was added. Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - output_index: int, - content_index: int, - part: "_models.OutputContent", - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_CONTENT_PART_ADDED # type: ignore - - -class ResponseContentPartDoneEvent(ResponseStreamEvent, discriminator="response.content_part.done"): - """Emitted when a content part is done. - - :ivar type: The type of the event. Always ``response.content_part.done``. Required. - RESPONSE_CONTENT_PART_DONE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.RESPONSE_CONTENT_PART_DONE - :ivar item_id: The ID of the output item that the content part was added to. Required. - :vartype item_id: str - :ivar output_index: The index of the output item that the content part was added to. Required. - :vartype output_index: int - :ivar content_index: The index of the content part that is done. Required. - :vartype content_index: int - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - :ivar part: The content part that is done. Required. - :vartype part: ~azure.ai.agentserver.responses.models.models.OutputContent - """ - - type: Literal[ResponseStreamEventType.RESPONSE_CONTENT_PART_DONE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.content_part.done``. Required. - RESPONSE_CONTENT_PART_DONE.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the output item that the content part was added to. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that the content part was added to. Required.""" - content_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the content part that is done. Required.""" - part: "_models.OutputContent" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The content part that is done. Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - output_index: int, - content_index: int, - sequence_number: int, - part: "_models.OutputContent", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_CONTENT_PART_DONE # type: ignore - - -class ResponseCreatedEvent(ResponseStreamEvent, discriminator="response.created"): - """An event that is emitted when a response is created. - - :ivar type: The type of the event. Always ``response.created``. Required. RESPONSE_CREATED. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.RESPONSE_CREATED - :ivar response: The response that was created. Required. - :vartype response: ~azure.ai.agentserver.responses.models.models.ResponseObject - :ivar sequence_number: The sequence number for this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_CREATED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.created``. Required. RESPONSE_CREATED.""" - response: "_models.ResponseObject" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The response that was created. Required.""" - - @overload - def __init__( - self, - *, - response: "_models.ResponseObject", - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_CREATED # type: ignore - - -class ResponseCustomToolCallInputDeltaEvent(ResponseStreamEvent, discriminator="response.custom_tool_call_input.delta"): - """ResponseCustomToolCallInputDelta. - - :ivar type: The event type identifier. Required. RESPONSE_CUSTOM_TOOL_CALL_INPUT_DELTA. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_CUSTOM_TOOL_CALL_INPUT_DELTA - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - :ivar output_index: The index of the output this delta applies to. Required. - :vartype output_index: int - :ivar item_id: Unique identifier for the API item associated with this event. Required. - :vartype item_id: str - :ivar delta: The incremental input data (delta) for the custom tool call. Required. - :vartype delta: str - """ - - type: Literal[ResponseStreamEventType.RESPONSE_CUSTOM_TOOL_CALL_INPUT_DELTA] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The event type identifier. Required. RESPONSE_CUSTOM_TOOL_CALL_INPUT_DELTA.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output this delta applies to. Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Unique identifier for the API item associated with this event. Required.""" - delta: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The incremental input data (delta) for the custom tool call. Required.""" - - @overload - def __init__( - self, - *, - sequence_number: int, - output_index: int, - item_id: str, - delta: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_CUSTOM_TOOL_CALL_INPUT_DELTA # type: ignore - - -class ResponseCustomToolCallInputDoneEvent(ResponseStreamEvent, discriminator="response.custom_tool_call_input.done"): - """ResponseCustomToolCallInputDone. - - :ivar type: The event type identifier. Required. RESPONSE_CUSTOM_TOOL_CALL_INPUT_DONE. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_CUSTOM_TOOL_CALL_INPUT_DONE - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - :ivar output_index: The index of the output this event applies to. Required. - :vartype output_index: int - :ivar item_id: Unique identifier for the API item associated with this event. Required. - :vartype item_id: str - :ivar input: The complete input data for the custom tool call. Required. - :vartype input: str - """ - - type: Literal[ResponseStreamEventType.RESPONSE_CUSTOM_TOOL_CALL_INPUT_DONE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The event type identifier. Required. RESPONSE_CUSTOM_TOOL_CALL_INPUT_DONE.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output this event applies to. Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Unique identifier for the API item associated with this event. Required.""" - input: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The complete input data for the custom tool call. Required.""" - - @overload - def __init__( - self, - *, - sequence_number: int, - output_index: int, - item_id: str, - input: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_CUSTOM_TOOL_CALL_INPUT_DONE # type: ignore - - -class ResponseErrorEvent(ResponseStreamEvent, discriminator="error"): - """Emitted when an error occurs. - - :ivar type: The type of the event. Always ``error``. Required. ERROR. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.ERROR - :ivar code: Required. - :vartype code: str - :ivar message: The error message. Required. - :vartype message: str - :ivar param: Required. - :vartype param: str - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.ERROR] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``error``. Required. ERROR.""" - code: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - message: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The error message. Required.""" - param: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - code: str, - message: str, - param: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.ERROR # type: ignore - - -class ResponseErrorInfo(_Model): - """An error object returned when the model fails to generate a Response. - - :ivar code: Required. Known values are: "server_error", "rate_limit_exceeded", - "invalid_prompt", "vector_store_timeout", "invalid_image", "invalid_image_format", - "invalid_base64_image", "invalid_image_url", "image_too_large", "image_too_small", - "image_parse_error", "image_content_policy_violation", "invalid_image_mode", - "image_file_too_large", "unsupported_image_media_type", "empty_image_file", - "failed_to_download_image", and "image_file_not_found". - :vartype code: str or ~azure.ai.agentserver.responses.models.models.ResponseErrorCode - :ivar message: A human-readable description of the error. Required. - :vartype message: str - """ - - code: Union[str, "_models.ResponseErrorCode"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Required. Known values are: \"server_error\", \"rate_limit_exceeded\", \"invalid_prompt\", - \"vector_store_timeout\", \"invalid_image\", \"invalid_image_format\", - \"invalid_base64_image\", \"invalid_image_url\", \"image_too_large\", \"image_too_small\", - \"image_parse_error\", \"image_content_policy_violation\", \"invalid_image_mode\", - \"image_file_too_large\", \"unsupported_image_media_type\", \"empty_image_file\", - \"failed_to_download_image\", and \"image_file_not_found\".""" - message: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A human-readable description of the error. Required.""" - - @overload - def __init__( - self, - *, - code: Union[str, "_models.ResponseErrorCode"], - message: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ResponseFailedEvent(ResponseStreamEvent, discriminator="response.failed"): - """An event that is emitted when a response fails. - - :ivar type: The type of the event. Always ``response.failed``. Required. RESPONSE_FAILED. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.RESPONSE_FAILED - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - :ivar response: The response that failed. Required. - :vartype response: ~azure.ai.agentserver.responses.models.models.ResponseObject - """ - - type: Literal[ResponseStreamEventType.RESPONSE_FAILED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.failed``. Required. RESPONSE_FAILED.""" - response: "_models.ResponseObject" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The response that failed. Required.""" - - @overload - def __init__( - self, - *, - sequence_number: int, - response: "_models.ResponseObject", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_FAILED # type: ignore - - -class ResponseFileSearchCallCompletedEvent(ResponseStreamEvent, discriminator="response.file_search_call.completed"): - """Emitted when a file search call is completed (results found). - - :ivar type: The type of the event. Always ``response.file_search_call.completed``. Required. - RESPONSE_FILE_SEARCH_CALL_COMPLETED. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_FILE_SEARCH_CALL_COMPLETED - :ivar output_index: The index of the output item that the file search call is initiated. - Required. - :vartype output_index: int - :ivar item_id: The ID of the output item that the file search call is initiated. Required. - :vartype item_id: str - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_FILE_SEARCH_CALL_COMPLETED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.file_search_call.completed``. Required. - RESPONSE_FILE_SEARCH_CALL_COMPLETED.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that the file search call is initiated. Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the output item that the file search call is initiated. Required.""" - - @overload - def __init__( - self, - *, - output_index: int, - item_id: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_FILE_SEARCH_CALL_COMPLETED # type: ignore - - -class ResponseFileSearchCallInProgressEvent(ResponseStreamEvent, discriminator="response.file_search_call.in_progress"): - """Emitted when a file search call is initiated. - - :ivar type: The type of the event. Always ``response.file_search_call.in_progress``. Required. - RESPONSE_FILE_SEARCH_CALL_IN_PROGRESS. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_FILE_SEARCH_CALL_IN_PROGRESS - :ivar output_index: The index of the output item that the file search call is initiated. - Required. - :vartype output_index: int - :ivar item_id: The ID of the output item that the file search call is initiated. Required. - :vartype item_id: str - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_FILE_SEARCH_CALL_IN_PROGRESS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.file_search_call.in_progress``. Required. - RESPONSE_FILE_SEARCH_CALL_IN_PROGRESS.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that the file search call is initiated. Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the output item that the file search call is initiated. Required.""" - - @overload - def __init__( - self, - *, - output_index: int, - item_id: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_FILE_SEARCH_CALL_IN_PROGRESS # type: ignore - - -class ResponseFileSearchCallSearchingEvent(ResponseStreamEvent, discriminator="response.file_search_call.searching"): - """Emitted when a file search is currently searching. - - :ivar type: The type of the event. Always ``response.file_search_call.searching``. Required. - RESPONSE_FILE_SEARCH_CALL_SEARCHING. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_FILE_SEARCH_CALL_SEARCHING - :ivar output_index: The index of the output item that the file search call is searching. - Required. - :vartype output_index: int - :ivar item_id: The ID of the output item that the file search call is initiated. Required. - :vartype item_id: str - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_FILE_SEARCH_CALL_SEARCHING] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.file_search_call.searching``. Required. - RESPONSE_FILE_SEARCH_CALL_SEARCHING.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that the file search call is searching. Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the output item that the file search call is initiated. Required.""" - - @overload - def __init__( - self, - *, - output_index: int, - item_id: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_FILE_SEARCH_CALL_SEARCHING # type: ignore - - -class ResponseFormatJsonSchemaSchema(_Model): - """JSON schema.""" - - -class ResponseFunctionCallArgumentsDeltaEvent( - ResponseStreamEvent, discriminator="response.function_call_arguments.delta" -): - """Emitted when there is a partial function-call arguments delta. - - :ivar type: The type of the event. Always ``response.function_call_arguments.delta``. Required. - RESPONSE_FUNCTION_CALL_ARGUMENTS_DELTA. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_FUNCTION_CALL_ARGUMENTS_DELTA - :ivar item_id: The ID of the output item that the function-call arguments delta is added to. - Required. - :vartype item_id: str - :ivar output_index: The index of the output item that the function-call arguments delta is - added to. Required. - :vartype output_index: int - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - :ivar delta: The function-call arguments delta that is added. Required. - :vartype delta: str - """ - - type: Literal[ResponseStreamEventType.RESPONSE_FUNCTION_CALL_ARGUMENTS_DELTA] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.function_call_arguments.delta``. Required. - RESPONSE_FUNCTION_CALL_ARGUMENTS_DELTA.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the output item that the function-call arguments delta is added to. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that the function-call arguments delta is added to. Required.""" - delta: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The function-call arguments delta that is added. Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - output_index: int, - sequence_number: int, - delta: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_FUNCTION_CALL_ARGUMENTS_DELTA # type: ignore - - -class ResponseFunctionCallArgumentsDoneEvent( - ResponseStreamEvent, discriminator="response.function_call_arguments.done" -): - """Emitted when function-call arguments are finalized. - - :ivar type: Required. RESPONSE_FUNCTION_CALL_ARGUMENTS_DONE. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_FUNCTION_CALL_ARGUMENTS_DONE - :ivar item_id: The ID of the item. Required. - :vartype item_id: str - :ivar name: The name of the function that was called. Required. - :vartype name: str - :ivar output_index: The index of the output item. Required. - :vartype output_index: int - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - :ivar arguments: The function-call arguments. Required. - :vartype arguments: str - """ - - type: Literal[ResponseStreamEventType.RESPONSE_FUNCTION_CALL_ARGUMENTS_DONE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. RESPONSE_FUNCTION_CALL_ARGUMENTS_DONE.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the item. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the function that was called. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The function-call arguments. Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - name: str, - output_index: int, - sequence_number: int, - arguments: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_FUNCTION_CALL_ARGUMENTS_DONE # type: ignore - - -class ResponseImageGenCallCompletedEvent(ResponseStreamEvent, discriminator="response.image_generation_call.completed"): - """ResponseImageGenCallCompletedEvent. - - :ivar type: The type of the event. Always 'response.image_generation_call.completed'. Required. - RESPONSE_IMAGE_GENERATION_CALL_COMPLETED. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_IMAGE_GENERATION_CALL_COMPLETED - :ivar output_index: The index of the output item in the response's output array. Required. - :vartype output_index: int - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - :ivar item_id: The unique identifier of the image generation item being processed. Required. - :vartype item_id: str - """ - - type: Literal[ResponseStreamEventType.RESPONSE_IMAGE_GENERATION_CALL_COMPLETED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always 'response.image_generation_call.completed'. Required. - RESPONSE_IMAGE_GENERATION_CALL_COMPLETED.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item in the response's output array. Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique identifier of the image generation item being processed. Required.""" - - @overload - def __init__( - self, - *, - output_index: int, - sequence_number: int, - item_id: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_IMAGE_GENERATION_CALL_COMPLETED # type: ignore - - -class ResponseImageGenCallGeneratingEvent( - ResponseStreamEvent, discriminator="response.image_generation_call.generating" -): - """ResponseImageGenCallGeneratingEvent. - - :ivar type: The type of the event. Always 'response.image_generation_call.generating'. - Required. RESPONSE_IMAGE_GENERATION_CALL_GENERATING. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_IMAGE_GENERATION_CALL_GENERATING - :ivar output_index: The index of the output item in the response's output array. Required. - :vartype output_index: int - :ivar item_id: The unique identifier of the image generation item being processed. Required. - :vartype item_id: str - :ivar sequence_number: The sequence number of the image generation item being processed. - Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_IMAGE_GENERATION_CALL_GENERATING] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always 'response.image_generation_call.generating'. Required. - RESPONSE_IMAGE_GENERATION_CALL_GENERATING.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item in the response's output array. Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique identifier of the image generation item being processed. Required.""" - - @overload - def __init__( - self, - *, - output_index: int, - item_id: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_IMAGE_GENERATION_CALL_GENERATING # type: ignore - - -class ResponseImageGenCallInProgressEvent( - ResponseStreamEvent, discriminator="response.image_generation_call.in_progress" -): - """ResponseImageGenCallInProgressEvent. - - :ivar type: The type of the event. Always 'response.image_generation_call.in_progress'. - Required. RESPONSE_IMAGE_GENERATION_CALL_IN_PROGRESS. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_IMAGE_GENERATION_CALL_IN_PROGRESS - :ivar output_index: The index of the output item in the response's output array. Required. - :vartype output_index: int - :ivar item_id: The unique identifier of the image generation item being processed. Required. - :vartype item_id: str - :ivar sequence_number: The sequence number of the image generation item being processed. - Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_IMAGE_GENERATION_CALL_IN_PROGRESS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always 'response.image_generation_call.in_progress'. Required. - RESPONSE_IMAGE_GENERATION_CALL_IN_PROGRESS.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item in the response's output array. Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique identifier of the image generation item being processed. Required.""" - - @overload - def __init__( - self, - *, - output_index: int, - item_id: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_IMAGE_GENERATION_CALL_IN_PROGRESS # type: ignore - - -class ResponseImageGenCallPartialImageEvent( - ResponseStreamEvent, discriminator="response.image_generation_call.partial_image" -): - """ResponseImageGenCallPartialImageEvent. - - :ivar type: The type of the event. Always 'response.image_generation_call.partial_image'. - Required. RESPONSE_IMAGE_GENERATION_CALL_PARTIAL_IMAGE. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_IMAGE_GENERATION_CALL_PARTIAL_IMAGE - :ivar output_index: The index of the output item in the response's output array. Required. - :vartype output_index: int - :ivar item_id: The unique identifier of the image generation item being processed. Required. - :vartype item_id: str - :ivar sequence_number: The sequence number of the image generation item being processed. - Required. - :vartype sequence_number: int - :ivar partial_image_index: 0-based index for the partial image (backend is 1-based, but this is - 0-based for the user). Required. - :vartype partial_image_index: int - :ivar partial_image_b64: Base64-encoded partial image data, suitable for rendering as an image. - Required. - :vartype partial_image_b64: str - """ - - type: Literal[ResponseStreamEventType.RESPONSE_IMAGE_GENERATION_CALL_PARTIAL_IMAGE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always 'response.image_generation_call.partial_image'. Required. - RESPONSE_IMAGE_GENERATION_CALL_PARTIAL_IMAGE.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item in the response's output array. Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique identifier of the image generation item being processed. Required.""" - partial_image_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """0-based index for the partial image (backend is 1-based, but this is 0-based for the user). - Required.""" - partial_image_b64: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Base64-encoded partial image data, suitable for rendering as an image. Required.""" - - @overload - def __init__( - self, - *, - output_index: int, - item_id: str, - sequence_number: int, - partial_image_index: int, - partial_image_b64: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_IMAGE_GENERATION_CALL_PARTIAL_IMAGE # type: ignore - - -class ResponseIncompleteDetails(_Model): - """ResponseIncompleteDetails. - - :ivar reason: Is either a Literal["max_output_tokens"] type or a Literal["content_filter"] - type. - :vartype reason: str or str - """ - - reason: Optional[Literal["max_output_tokens", "content_filter"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Is either a Literal[\"max_output_tokens\"] type or a Literal[\"content_filter\"] type.""" - - @overload - def __init__( - self, - *, - reason: Optional[Literal["max_output_tokens", "content_filter"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ResponseIncompleteEvent(ResponseStreamEvent, discriminator="response.incomplete"): - """An event that is emitted when a response finishes as incomplete. - - :ivar type: The type of the event. Always ``response.incomplete``. Required. - RESPONSE_INCOMPLETE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.RESPONSE_INCOMPLETE - :ivar response: The response that was incomplete. Required. - :vartype response: ~azure.ai.agentserver.responses.models.models.ResponseObject - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_INCOMPLETE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.incomplete``. Required. RESPONSE_INCOMPLETE.""" - response: "_models.ResponseObject" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The response that was incomplete. Required.""" - - @overload - def __init__( - self, - *, - response: "_models.ResponseObject", - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_INCOMPLETE # type: ignore - - -class ResponseInProgressEvent(ResponseStreamEvent, discriminator="response.in_progress"): - """Emitted when the response is in progress. - - :ivar type: The type of the event. Always ``response.in_progress``. Required. - RESPONSE_IN_PROGRESS. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.RESPONSE_IN_PROGRESS - :ivar response: The response that is in progress. Required. - :vartype response: ~azure.ai.agentserver.responses.models.models.ResponseObject - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_IN_PROGRESS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.in_progress``. Required. RESPONSE_IN_PROGRESS.""" - response: "_models.ResponseObject" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The response that is in progress. Required.""" - - @overload - def __init__( - self, - *, - response: "_models.ResponseObject", - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_IN_PROGRESS # type: ignore - - -class ResponseLogProb(_Model): - """A logprob is the logarithmic probability that the model assigns to producing a particular token - at a given position in the sequence. Less-negative (higher) logprob values indicate greater - model confidence in that token choice. - - :ivar token: A possible text token. Required. - :vartype token: str - :ivar logprob: The log probability of this token. Required. - :vartype logprob: int - :ivar top_logprobs: The log probability of the top 20 most likely tokens. - :vartype top_logprobs: - list[~azure.ai.agentserver.responses.models.models.ResponseLogProbTopLogprobs] - """ - - token: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A possible text token. Required.""" - logprob: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The log probability of this token. Required.""" - top_logprobs: Optional[list["_models.ResponseLogProbTopLogprobs"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The log probability of the top 20 most likely tokens.""" - - @overload - def __init__( - self, - *, - token: str, - logprob: int, - top_logprobs: Optional[list["_models.ResponseLogProbTopLogprobs"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ResponseLogProbTopLogprobs(_Model): - """ResponseLogProbTopLogprobs. - - :ivar token: - :vartype token: str - :ivar logprob: - :vartype logprob: int - """ - - token: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - logprob: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - token: Optional[str] = None, - logprob: Optional[int] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ResponseMCPCallArgumentsDeltaEvent(ResponseStreamEvent, discriminator="response.mcp_call_arguments.delta"): - """ResponseMCPCallArgumentsDeltaEvent. - - :ivar type: The type of the event. Always 'response.mcp_call_arguments.delta'. Required. - RESPONSE_MCP_CALL_ARGUMENTS_DELTA. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_MCP_CALL_ARGUMENTS_DELTA - :ivar output_index: The index of the output item in the response's output array. Required. - :vartype output_index: int - :ivar item_id: The unique identifier of the MCP tool call item being processed. Required. - :vartype item_id: str - :ivar delta: A JSON string containing the partial update to the arguments for the MCP tool - call. Required. - :vartype delta: str - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_MCP_CALL_ARGUMENTS_DELTA] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always 'response.mcp_call_arguments.delta'. Required. - RESPONSE_MCP_CALL_ARGUMENTS_DELTA.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item in the response's output array. Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique identifier of the MCP tool call item being processed. Required.""" - delta: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string containing the partial update to the arguments for the MCP tool call. Required.""" - - @overload - def __init__( - self, - *, - output_index: int, - item_id: str, - delta: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_MCP_CALL_ARGUMENTS_DELTA # type: ignore - - -class ResponseMCPCallArgumentsDoneEvent(ResponseStreamEvent, discriminator="response.mcp_call_arguments.done"): - """ResponseMCPCallArgumentsDoneEvent. - - :ivar type: The type of the event. Always 'response.mcp_call_arguments.done'. Required. - RESPONSE_MCP_CALL_ARGUMENTS_DONE. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_MCP_CALL_ARGUMENTS_DONE - :ivar output_index: The index of the output item in the response's output array. Required. - :vartype output_index: int - :ivar item_id: The unique identifier of the MCP tool call item being processed. Required. - :vartype item_id: str - :ivar arguments: A JSON string containing the finalized arguments for the MCP tool call. - Required. - :vartype arguments: str - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_MCP_CALL_ARGUMENTS_DONE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always 'response.mcp_call_arguments.done'. Required. - RESPONSE_MCP_CALL_ARGUMENTS_DONE.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item in the response's output array. Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique identifier of the MCP tool call item being processed. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string containing the finalized arguments for the MCP tool call. Required.""" - - @overload - def __init__( - self, - *, - output_index: int, - item_id: str, - arguments: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_MCP_CALL_ARGUMENTS_DONE # type: ignore - - -class ResponseMCPCallCompletedEvent(ResponseStreamEvent, discriminator="response.mcp_call.completed"): - """ResponseMCPCallCompletedEvent. - - :ivar type: The type of the event. Always 'response.mcp_call.completed'. Required. - RESPONSE_MCP_CALL_COMPLETED. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.RESPONSE_MCP_CALL_COMPLETED - :ivar item_id: The ID of the MCP tool call item that completed. Required. - :vartype item_id: str - :ivar output_index: The index of the output item that completed. Required. - :vartype output_index: int - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_MCP_CALL_COMPLETED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always 'response.mcp_call.completed'. Required. - RESPONSE_MCP_CALL_COMPLETED.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the MCP tool call item that completed. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that completed. Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - output_index: int, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_MCP_CALL_COMPLETED # type: ignore - - -class ResponseMCPCallFailedEvent(ResponseStreamEvent, discriminator="response.mcp_call.failed"): - """ResponseMCPCallFailedEvent. - - :ivar type: The type of the event. Always 'response.mcp_call.failed'. Required. - RESPONSE_MCP_CALL_FAILED. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.RESPONSE_MCP_CALL_FAILED - :ivar item_id: The ID of the MCP tool call item that failed. Required. - :vartype item_id: str - :ivar output_index: The index of the output item that failed. Required. - :vartype output_index: int - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_MCP_CALL_FAILED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always 'response.mcp_call.failed'. Required. RESPONSE_MCP_CALL_FAILED.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the MCP tool call item that failed. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that failed. Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - output_index: int, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_MCP_CALL_FAILED # type: ignore - - -class ResponseMCPCallInProgressEvent(ResponseStreamEvent, discriminator="response.mcp_call.in_progress"): - """ResponseMCPCallInProgressEvent. - - :ivar type: The type of the event. Always 'response.mcp_call.in_progress'. Required. - RESPONSE_MCP_CALL_IN_PROGRESS. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_MCP_CALL_IN_PROGRESS - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - :ivar output_index: The index of the output item in the response's output array. Required. - :vartype output_index: int - :ivar item_id: The unique identifier of the MCP tool call item being processed. Required. - :vartype item_id: str - """ - - type: Literal[ResponseStreamEventType.RESPONSE_MCP_CALL_IN_PROGRESS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always 'response.mcp_call.in_progress'. Required. - RESPONSE_MCP_CALL_IN_PROGRESS.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item in the response's output array. Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique identifier of the MCP tool call item being processed. Required.""" - - @overload - def __init__( - self, - *, - sequence_number: int, - output_index: int, - item_id: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_MCP_CALL_IN_PROGRESS # type: ignore - - -class ResponseMCPListToolsCompletedEvent(ResponseStreamEvent, discriminator="response.mcp_list_tools.completed"): - """ResponseMCPListToolsCompletedEvent. - - :ivar type: The type of the event. Always 'response.mcp_list_tools.completed'. Required. - RESPONSE_MCP_LIST_TOOLS_COMPLETED. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_MCP_LIST_TOOLS_COMPLETED - :ivar item_id: The ID of the MCP tool call item that produced this output. Required. - :vartype item_id: str - :ivar output_index: The index of the output item that was processed. Required. - :vartype output_index: int - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_MCP_LIST_TOOLS_COMPLETED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always 'response.mcp_list_tools.completed'. Required. - RESPONSE_MCP_LIST_TOOLS_COMPLETED.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the MCP tool call item that produced this output. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that was processed. Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - output_index: int, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_MCP_LIST_TOOLS_COMPLETED # type: ignore - - -class ResponseMCPListToolsFailedEvent(ResponseStreamEvent, discriminator="response.mcp_list_tools.failed"): - """ResponseMCPListToolsFailedEvent. - - :ivar type: The type of the event. Always 'response.mcp_list_tools.failed'. Required. - RESPONSE_MCP_LIST_TOOLS_FAILED. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_MCP_LIST_TOOLS_FAILED - :ivar item_id: The ID of the MCP tool call item that failed. Required. - :vartype item_id: str - :ivar output_index: The index of the output item that failed. Required. - :vartype output_index: int - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_MCP_LIST_TOOLS_FAILED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always 'response.mcp_list_tools.failed'. Required. - RESPONSE_MCP_LIST_TOOLS_FAILED.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the MCP tool call item that failed. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that failed. Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - output_index: int, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_MCP_LIST_TOOLS_FAILED # type: ignore - - -class ResponseMCPListToolsInProgressEvent(ResponseStreamEvent, discriminator="response.mcp_list_tools.in_progress"): - """ResponseMCPListToolsInProgressEvent. - - :ivar type: The type of the event. Always 'response.mcp_list_tools.in_progress'. Required. - RESPONSE_MCP_LIST_TOOLS_IN_PROGRESS. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_MCP_LIST_TOOLS_IN_PROGRESS - :ivar item_id: The ID of the MCP tool call item that is being processed. Required. - :vartype item_id: str - :ivar output_index: The index of the output item that is being processed. Required. - :vartype output_index: int - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_MCP_LIST_TOOLS_IN_PROGRESS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always 'response.mcp_list_tools.in_progress'. Required. - RESPONSE_MCP_LIST_TOOLS_IN_PROGRESS.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the MCP tool call item that is being processed. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that is being processed. Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - output_index: int, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_MCP_LIST_TOOLS_IN_PROGRESS # type: ignore - - -class ResponseObject(_Model): - """The response object. - - :ivar metadata: - :vartype metadata: ~azure.ai.agentserver.responses.models.models.Metadata - :ivar top_logprobs: - :vartype top_logprobs: int - :ivar temperature: - :vartype temperature: int - :ivar top_p: - :vartype top_p: int - :ivar user: This field is being replaced by ``safety_identifier`` and ``prompt_cache_key``. Use - ``prompt_cache_key`` instead to maintain caching optimizations. A stable identifier for your - end-users. Used to boost cache hit rates by better bucketing similar requests and to help - OpenAI detect and prevent abuse. `Learn more - `_. - :vartype user: str - :ivar safety_identifier: A stable identifier used to help detect users of your application that - may be violating OpenAI's usage policies. The IDs should be a string that uniquely identifies - each user. We recommend hashing their username or email address, in order to avoid sending us - any identifying information. `Learn more - `_. - :vartype safety_identifier: str - :ivar prompt_cache_key: Used by OpenAI to cache responses for similar requests to optimize your - cache hit rates. Replaces the ``user`` field. `Learn more `_. - :vartype prompt_cache_key: str - :ivar service_tier: Is one of the following types: Literal["auto"], Literal["default"], - Literal["flex"], Literal["scale"], Literal["priority"] - :vartype service_tier: str or str or str or str or str - :ivar prompt_cache_retention: Is either a Literal["in-memory"] type or a Literal["24h"] type. - :vartype prompt_cache_retention: str or str - :ivar previous_response_id: - :vartype previous_response_id: str - :ivar model: The model deployment to use for the creation of this response. - :vartype model: str - :ivar reasoning: - :vartype reasoning: ~azure.ai.agentserver.responses.models.models.Reasoning - :ivar background: - :vartype background: bool - :ivar max_output_tokens: - :vartype max_output_tokens: int - :ivar max_tool_calls: - :vartype max_tool_calls: int - :ivar text: - :vartype text: ~azure.ai.agentserver.responses.models.models.ResponseTextParam - :ivar tools: - :vartype tools: list[~azure.ai.agentserver.responses.models.models.Tool] - :ivar tool_choice: Is either a Union[str, "_models.ToolChoiceOptions"] type or a - ToolChoiceParam type. - :vartype tool_choice: str or ~azure.ai.agentserver.responses.models.models.ToolChoiceOptions or - ~azure.ai.agentserver.responses.models.models.ToolChoiceParam - :ivar prompt: - :vartype prompt: ~azure.ai.agentserver.responses.models.models.Prompt - :ivar truncation: Is either a Literal["auto"] type or a Literal["disabled"] type. - :vartype truncation: str or str - :ivar id: Unique identifier for this Response. Required. - :vartype id: str - :ivar object: The object type of this resource - always set to ``response``. Required. Default - value is "response". - :vartype object: str - :ivar status: The status of the response generation. One of ``completed``, ``failed``, - ``in_progress``, ``cancelled``, ``queued``, or ``incomplete``. Is one of the following types: - Literal["completed"], Literal["failed"], Literal["in_progress"], Literal["cancelled"], - Literal["queued"], Literal["incomplete"] - :vartype status: str or str or str or str or str or str - :ivar created_at: Unix timestamp (in seconds) of when this Response was created. Required. - :vartype created_at: ~datetime.datetime - :ivar completed_at: - :vartype completed_at: ~datetime.datetime - :ivar error: Required. - :vartype error: ~azure.ai.agentserver.responses.models.models.ResponseErrorInfo - :ivar incomplete_details: Required. - :vartype incomplete_details: - ~azure.ai.agentserver.responses.models.models.ResponseIncompleteDetails - :ivar output: An array of content items generated by the model. - - * The length and order of items in the `output` array is dependent - on the model's response. - * Rather than accessing the first item in the `output` array and - assuming it's an `assistant` message with the content generated by - the model, you might consider using the `output_text` property where - supported in SDKs. Required. - :vartype output: list[~azure.ai.agentserver.responses.models.models.OutputItem] - :ivar instructions: Required. Is either a str type or a [Item] type. - :vartype instructions: str or list[~azure.ai.agentserver.responses.models.models.Item] - :ivar output_text: - :vartype output_text: str - :ivar usage: - :vartype usage: ~azure.ai.agentserver.responses.models.models.ResponseUsage - :ivar parallel_tool_calls: Whether to allow the model to run tool calls in parallel. Required. - :vartype parallel_tool_calls: bool - :ivar conversation: - :vartype conversation: ~azure.ai.agentserver.responses.models.models.ConversationReference - :ivar agent_reference: The agent used for this response. Required. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - """ - - metadata: Optional["_models.Metadata"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - top_logprobs: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - temperature: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - top_p: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - user: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """This field is being replaced by ``safety_identifier`` and ``prompt_cache_key``. Use - ``prompt_cache_key`` instead to maintain caching optimizations. A stable identifier for your - end-users. Used to boost cache hit rates by better bucketing similar requests and to help - OpenAI detect and prevent abuse. `Learn more - `_.""" - safety_identifier: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A stable identifier used to help detect users of your application that may be violating - OpenAI's usage policies. The IDs should be a string that uniquely identifies each user. We - recommend hashing their username or email address, in order to avoid sending us any identifying - information. `Learn more `_.""" - prompt_cache_key: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. - Replaces the ``user`` field. `Learn more `_.""" - service_tier: Optional[Literal["auto", "default", "flex", "scale", "priority"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Is one of the following types: Literal[\"auto\"], Literal[\"default\"], Literal[\"flex\"], - Literal[\"scale\"], Literal[\"priority\"]""" - prompt_cache_retention: Optional[Literal["in-memory", "24h"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Is either a Literal[\"in-memory\"] type or a Literal[\"24h\"] type.""" - previous_response_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - model: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The model deployment to use for the creation of this response.""" - reasoning: Optional["_models.Reasoning"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - background: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - max_output_tokens: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - max_tool_calls: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - text: Optional["_models.ResponseTextParam"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - tools: Optional[list["_models.Tool"]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - tool_choice: Optional[Union[str, "_models.ToolChoiceOptions", "_models.ToolChoiceParam"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Is either a Union[str, \"_models.ToolChoiceOptions\"] type or a ToolChoiceParam type.""" - prompt: Optional["_models.Prompt"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - truncation: Optional[Literal["auto", "disabled"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Is either a Literal[\"auto\"] type or a Literal[\"disabled\"] type.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Unique identifier for this Response. Required.""" - object: Literal["response"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type of this resource - always set to ``response``. Required. Default value is - \"response\".""" - status: Optional[Literal["completed", "failed", "in_progress", "cancelled", "queued", "incomplete"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the response generation. One of ``completed``, ``failed``, ``in_progress``, - ``cancelled``, ``queued``, or ``incomplete``. Is one of the following types: - Literal[\"completed\"], Literal[\"failed\"], Literal[\"in_progress\"], Literal[\"cancelled\"], - Literal[\"queued\"], Literal[\"incomplete\"]""" - created_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """Unix timestamp (in seconds) of when this Response was created. Required.""" - completed_at: Optional[datetime.datetime] = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - error: "_models.ResponseErrorInfo" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - incomplete_details: "_models.ResponseIncompleteDetails" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Required.""" - output: list["_models.OutputItem"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """An array of content items generated by the model. - - * The length and order of items in the `output` array is dependent - on the model's response. - * Rather than accessing the first item in the `output` array and - assuming it's an `assistant` message with the content generated by - the model, you might consider using the `output_text` property where - supported in SDKs. Required.""" - instructions: Union[str, list["_models.Item"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Required. Is either a str type or a [Item] type.""" - output_text: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - usage: Optional["_models.ResponseUsage"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - parallel_tool_calls: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Whether to allow the model to run tool calls in parallel. Required.""" - conversation: Optional["_models.ConversationReference"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - agent_reference: "_models.AgentReference" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The agent used for this response. Required.""" - - @overload - def __init__( # pylint: disable=too-many-locals - self, - *, - id: str, # pylint: disable=redefined-builtin - created_at: datetime.datetime, - error: "_models.ResponseErrorInfo", - incomplete_details: "_models.ResponseIncompleteDetails", - output: list["_models.OutputItem"], - instructions: Union[str, list["_models.Item"]], - parallel_tool_calls: bool, - agent_reference: "_models.AgentReference", - metadata: Optional["_models.Metadata"] = None, - top_logprobs: Optional[int] = None, - temperature: Optional[int] = None, - top_p: Optional[int] = None, - user: Optional[str] = None, - safety_identifier: Optional[str] = None, - prompt_cache_key: Optional[str] = None, - service_tier: Optional[Literal["auto", "default", "flex", "scale", "priority"]] = None, - prompt_cache_retention: Optional[Literal["in-memory", "24h"]] = None, - previous_response_id: Optional[str] = None, - model: Optional[str] = None, - reasoning: Optional["_models.Reasoning"] = None, - background: Optional[bool] = None, - max_output_tokens: Optional[int] = None, - max_tool_calls: Optional[int] = None, - text: Optional["_models.ResponseTextParam"] = None, - tools: Optional[list["_models.Tool"]] = None, - tool_choice: Optional[Union[str, "_models.ToolChoiceOptions", "_models.ToolChoiceParam"]] = None, - prompt: Optional["_models.Prompt"] = None, - truncation: Optional[Literal["auto", "disabled"]] = None, - status: Optional[Literal["completed", "failed", "in_progress", "cancelled", "queued", "incomplete"]] = None, - completed_at: Optional[datetime.datetime] = None, - output_text: Optional[str] = None, - usage: Optional["_models.ResponseUsage"] = None, - conversation: Optional["_models.ConversationReference"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.object: Literal["response"] = "response" - - -class ResponseOutputItemAddedEvent(ResponseStreamEvent, discriminator="response.output_item.added"): - """Emitted when a new output item is added. - - :ivar type: The type of the event. Always ``response.output_item.added``. Required. - RESPONSE_OUTPUT_ITEM_ADDED. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.RESPONSE_OUTPUT_ITEM_ADDED - :ivar output_index: The index of the output item that was added. Required. - :vartype output_index: int - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - :ivar item: The output item that was added. Required. - :vartype item: ~azure.ai.agentserver.responses.models.models.OutputItem - """ - - type: Literal[ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_ADDED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.output_item.added``. Required. - RESPONSE_OUTPUT_ITEM_ADDED.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that was added. Required.""" - item: "_models.OutputItem" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The output item that was added. Required.""" - - @overload - def __init__( - self, - *, - output_index: int, - sequence_number: int, - item: "_models.OutputItem", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_ADDED # type: ignore - - -class ResponseOutputItemDoneEvent(ResponseStreamEvent, discriminator="response.output_item.done"): - """Emitted when an output item is marked done. - - :ivar type: The type of the event. Always ``response.output_item.done``. Required. - RESPONSE_OUTPUT_ITEM_DONE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.RESPONSE_OUTPUT_ITEM_DONE - :ivar output_index: The index of the output item that was marked done. Required. - :vartype output_index: int - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - :ivar item: The output item that was marked done. Required. - :vartype item: ~azure.ai.agentserver.responses.models.models.OutputItem - """ - - type: Literal[ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_DONE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.output_item.done``. Required. - RESPONSE_OUTPUT_ITEM_DONE.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that was marked done. Required.""" - item: "_models.OutputItem" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The output item that was marked done. Required.""" - - @overload - def __init__( - self, - *, - output_index: int, - sequence_number: int, - item: "_models.OutputItem", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_DONE # type: ignore - - -class ResponseOutputTextAnnotationAddedEvent( - ResponseStreamEvent, discriminator="response.output_text.annotation.added" -): - """ResponseOutputTextAnnotationAddedEvent. - - :ivar type: The type of the event. Always 'response.output_text.annotation.added'. Required. - RESPONSE_OUTPUT_TEXT_ANNOTATION_ADDED. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_OUTPUT_TEXT_ANNOTATION_ADDED - :ivar item_id: The unique identifier of the item to which the annotation is being added. - Required. - :vartype item_id: str - :ivar output_index: The index of the output item in the response's output array. Required. - :vartype output_index: int - :ivar content_index: The index of the content part within the output item. Required. - :vartype content_index: int - :ivar annotation_index: The index of the annotation within the content part. Required. - :vartype annotation_index: int - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - :ivar annotation: The annotation object being added. (See annotation schema for details.). - Required. - :vartype annotation: ~azure.ai.agentserver.responses.models.models.Annotation - """ - - type: Literal[ResponseStreamEventType.RESPONSE_OUTPUT_TEXT_ANNOTATION_ADDED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always 'response.output_text.annotation.added'. Required. - RESPONSE_OUTPUT_TEXT_ANNOTATION_ADDED.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique identifier of the item to which the annotation is being added. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item in the response's output array. Required.""" - content_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the content part within the output item. Required.""" - annotation_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the annotation within the content part. Required.""" - annotation: "_models.Annotation" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The annotation object being added. (See annotation schema for details.). Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - output_index: int, - content_index: int, - annotation_index: int, - sequence_number: int, - annotation: "_models.Annotation", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_OUTPUT_TEXT_ANNOTATION_ADDED # type: ignore - - -class ResponsePromptVariables(_Model): - """Prompt Variables.""" - - -class ResponseQueuedEvent(ResponseStreamEvent, discriminator="response.queued"): - """ResponseQueuedEvent. - - :ivar type: The type of the event. Always 'response.queued'. Required. RESPONSE_QUEUED. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.RESPONSE_QUEUED - :ivar response: The full response object that is queued. Required. - :vartype response: ~azure.ai.agentserver.responses.models.models.ResponseObject - :ivar sequence_number: The sequence number for this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_QUEUED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always 'response.queued'. Required. RESPONSE_QUEUED.""" - response: "_models.ResponseObject" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The full response object that is queued. Required.""" - - @overload - def __init__( - self, - *, - response: "_models.ResponseObject", - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_QUEUED # type: ignore - - -class ResponseReasoningSummaryPartAddedEvent( - ResponseStreamEvent, discriminator="response.reasoning_summary_part.added" -): - """Emitted when a new reasoning summary part is added. - - :ivar type: The type of the event. Always ``response.reasoning_summary_part.added``. Required. - RESPONSE_REASONING_SUMMARY_PART_ADDED. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_REASONING_SUMMARY_PART_ADDED - :ivar item_id: The ID of the item this summary part is associated with. Required. - :vartype item_id: str - :ivar output_index: The index of the output item this summary part is associated with. - Required. - :vartype output_index: int - :ivar summary_index: The index of the summary part within the reasoning summary. Required. - :vartype summary_index: int - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - :ivar part: The summary part that was added. Required. - :vartype part: - ~azure.ai.agentserver.responses.models.models.ResponseReasoningSummaryPartAddedEventPart - """ - - type: Literal[ResponseStreamEventType.RESPONSE_REASONING_SUMMARY_PART_ADDED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.reasoning_summary_part.added``. Required. - RESPONSE_REASONING_SUMMARY_PART_ADDED.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the item this summary part is associated with. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item this summary part is associated with. Required.""" - summary_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the summary part within the reasoning summary. Required.""" - part: "_models.ResponseReasoningSummaryPartAddedEventPart" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The summary part that was added. Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - output_index: int, - summary_index: int, - sequence_number: int, - part: "_models.ResponseReasoningSummaryPartAddedEventPart", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_REASONING_SUMMARY_PART_ADDED # type: ignore - - -class ResponseReasoningSummaryPartAddedEventPart(_Model): # pylint: disable=name-too-long - """ResponseReasoningSummaryPartAddedEventPart. - - :ivar type: Required. Default value is "summary_text". - :vartype type: str - :ivar text: Required. - :vartype text: str - """ - - type: Literal["summary_text"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required. Default value is \"summary_text\".""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - text: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["summary_text"] = "summary_text" - - -class ResponseReasoningSummaryPartDoneEvent(ResponseStreamEvent, discriminator="response.reasoning_summary_part.done"): - """Emitted when a reasoning summary part is completed. - - :ivar type: The type of the event. Always ``response.reasoning_summary_part.done``. Required. - RESPONSE_REASONING_SUMMARY_PART_DONE. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_REASONING_SUMMARY_PART_DONE - :ivar item_id: The ID of the item this summary part is associated with. Required. - :vartype item_id: str - :ivar output_index: The index of the output item this summary part is associated with. - Required. - :vartype output_index: int - :ivar summary_index: The index of the summary part within the reasoning summary. Required. - :vartype summary_index: int - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - :ivar part: The completed summary part. Required. - :vartype part: - ~azure.ai.agentserver.responses.models.models.ResponseReasoningSummaryPartDoneEventPart - """ - - type: Literal[ResponseStreamEventType.RESPONSE_REASONING_SUMMARY_PART_DONE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.reasoning_summary_part.done``. Required. - RESPONSE_REASONING_SUMMARY_PART_DONE.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the item this summary part is associated with. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item this summary part is associated with. Required.""" - summary_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the summary part within the reasoning summary. Required.""" - part: "_models.ResponseReasoningSummaryPartDoneEventPart" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The completed summary part. Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - output_index: int, - summary_index: int, - sequence_number: int, - part: "_models.ResponseReasoningSummaryPartDoneEventPart", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_REASONING_SUMMARY_PART_DONE # type: ignore - - -class ResponseReasoningSummaryPartDoneEventPart(_Model): # pylint: disable=name-too-long - """ResponseReasoningSummaryPartDoneEventPart. - - :ivar type: Required. Default value is "summary_text". - :vartype type: str - :ivar text: Required. - :vartype text: str - """ - - type: Literal["summary_text"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required. Default value is \"summary_text\".""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - text: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["summary_text"] = "summary_text" - - -class ResponseReasoningSummaryTextDeltaEvent( - ResponseStreamEvent, discriminator="response.reasoning_summary_text.delta" -): - """Emitted when a delta is added to a reasoning summary text. - - :ivar type: The type of the event. Always ``response.reasoning_summary_text.delta``. Required. - RESPONSE_REASONING_SUMMARY_TEXT_DELTA. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_REASONING_SUMMARY_TEXT_DELTA - :ivar item_id: The ID of the item this summary text delta is associated with. Required. - :vartype item_id: str - :ivar output_index: The index of the output item this summary text delta is associated with. - Required. - :vartype output_index: int - :ivar summary_index: The index of the summary part within the reasoning summary. Required. - :vartype summary_index: int - :ivar delta: The text delta that was added to the summary. Required. - :vartype delta: str - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_REASONING_SUMMARY_TEXT_DELTA] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.reasoning_summary_text.delta``. Required. - RESPONSE_REASONING_SUMMARY_TEXT_DELTA.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the item this summary text delta is associated with. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item this summary text delta is associated with. Required.""" - summary_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the summary part within the reasoning summary. Required.""" - delta: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The text delta that was added to the summary. Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - output_index: int, - summary_index: int, - delta: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_REASONING_SUMMARY_TEXT_DELTA # type: ignore - - -class ResponseReasoningSummaryTextDoneEvent(ResponseStreamEvent, discriminator="response.reasoning_summary_text.done"): - """Emitted when a reasoning summary text is completed. - - :ivar type: The type of the event. Always ``response.reasoning_summary_text.done``. Required. - RESPONSE_REASONING_SUMMARY_TEXT_DONE. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_REASONING_SUMMARY_TEXT_DONE - :ivar item_id: The ID of the item this summary text is associated with. Required. - :vartype item_id: str - :ivar output_index: The index of the output item this summary text is associated with. - Required. - :vartype output_index: int - :ivar summary_index: The index of the summary part within the reasoning summary. Required. - :vartype summary_index: int - :ivar text: The full text of the completed reasoning summary. Required. - :vartype text: str - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_REASONING_SUMMARY_TEXT_DONE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.reasoning_summary_text.done``. Required. - RESPONSE_REASONING_SUMMARY_TEXT_DONE.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the item this summary text is associated with. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item this summary text is associated with. Required.""" - summary_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the summary part within the reasoning summary. Required.""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The full text of the completed reasoning summary. Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - output_index: int, - summary_index: int, - text: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_REASONING_SUMMARY_TEXT_DONE # type: ignore - - -class ResponseReasoningTextDeltaEvent(ResponseStreamEvent, discriminator="response.reasoning_text.delta"): - """Emitted when a delta is added to a reasoning text. - - :ivar type: The type of the event. Always ``response.reasoning_text.delta``. Required. - RESPONSE_REASONING_TEXT_DELTA. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_REASONING_TEXT_DELTA - :ivar item_id: The ID of the item this reasoning text delta is associated with. Required. - :vartype item_id: str - :ivar output_index: The index of the output item this reasoning text delta is associated with. - Required. - :vartype output_index: int - :ivar content_index: The index of the reasoning content part this delta is associated with. - Required. - :vartype content_index: int - :ivar delta: The text delta that was added to the reasoning content. Required. - :vartype delta: str - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_REASONING_TEXT_DELTA] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.reasoning_text.delta``. Required. - RESPONSE_REASONING_TEXT_DELTA.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the item this reasoning text delta is associated with. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item this reasoning text delta is associated with. Required.""" - content_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the reasoning content part this delta is associated with. Required.""" - delta: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The text delta that was added to the reasoning content. Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - output_index: int, - content_index: int, - delta: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_REASONING_TEXT_DELTA # type: ignore - - -class ResponseReasoningTextDoneEvent(ResponseStreamEvent, discriminator="response.reasoning_text.done"): - """Emitted when a reasoning text is completed. - - :ivar type: The type of the event. Always ``response.reasoning_text.done``. Required. - RESPONSE_REASONING_TEXT_DONE. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_REASONING_TEXT_DONE - :ivar item_id: The ID of the item this reasoning text is associated with. Required. - :vartype item_id: str - :ivar output_index: The index of the output item this reasoning text is associated with. - Required. - :vartype output_index: int - :ivar content_index: The index of the reasoning content part. Required. - :vartype content_index: int - :ivar text: The full text of the completed reasoning content. Required. - :vartype text: str - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_REASONING_TEXT_DONE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.reasoning_text.done``. Required. - RESPONSE_REASONING_TEXT_DONE.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the item this reasoning text is associated with. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item this reasoning text is associated with. Required.""" - content_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the reasoning content part. Required.""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The full text of the completed reasoning content. Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - output_index: int, - content_index: int, - text: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_REASONING_TEXT_DONE # type: ignore - - -class ResponseRefusalDeltaEvent(ResponseStreamEvent, discriminator="response.refusal.delta"): - """Emitted when there is a partial refusal text. - - :ivar type: The type of the event. Always ``response.refusal.delta``. Required. - RESPONSE_REFUSAL_DELTA. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.RESPONSE_REFUSAL_DELTA - :ivar item_id: The ID of the output item that the refusal text is added to. Required. - :vartype item_id: str - :ivar output_index: The index of the output item that the refusal text is added to. Required. - :vartype output_index: int - :ivar content_index: The index of the content part that the refusal text is added to. Required. - :vartype content_index: int - :ivar delta: The refusal text that is added. Required. - :vartype delta: str - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_REFUSAL_DELTA] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.refusal.delta``. Required. RESPONSE_REFUSAL_DELTA.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the output item that the refusal text is added to. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that the refusal text is added to. Required.""" - content_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the content part that the refusal text is added to. Required.""" - delta: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The refusal text that is added. Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - output_index: int, - content_index: int, - delta: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_REFUSAL_DELTA # type: ignore - - -class ResponseRefusalDoneEvent(ResponseStreamEvent, discriminator="response.refusal.done"): - """Emitted when refusal text is finalized. - - :ivar type: The type of the event. Always ``response.refusal.done``. Required. - RESPONSE_REFUSAL_DONE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.RESPONSE_REFUSAL_DONE - :ivar item_id: The ID of the output item that the refusal text is finalized. Required. - :vartype item_id: str - :ivar output_index: The index of the output item that the refusal text is finalized. Required. - :vartype output_index: int - :ivar content_index: The index of the content part that the refusal text is finalized. - Required. - :vartype content_index: int - :ivar refusal: The refusal text that is finalized. Required. - :vartype refusal: str - :ivar sequence_number: The sequence number of this event. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_REFUSAL_DONE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.refusal.done``. Required. RESPONSE_REFUSAL_DONE.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the output item that the refusal text is finalized. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that the refusal text is finalized. Required.""" - content_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the content part that the refusal text is finalized. Required.""" - refusal: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The refusal text that is finalized. Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - output_index: int, - content_index: int, - refusal: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_REFUSAL_DONE # type: ignore - - -class ResponseStreamOptions(_Model): - """Options for streaming responses. Only set this when you set ``stream: true``. - - :ivar include_obfuscation: When true, stream obfuscation will be enabled. Stream obfuscation - adds random characters to an ``obfuscation`` field on streaming delta events to normalize - payload sizes as a mitigation to certain side-channel attacks. These obfuscation fields are - included by default, but add a small amount of overhead to the data stream. You can set - ``include_obfuscation`` to false to optimize for bandwidth if you trust the network links - between your application and the OpenAI API. - :vartype include_obfuscation: bool - """ - - include_obfuscation: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """When true, stream obfuscation will be enabled. Stream obfuscation adds random characters to an - ``obfuscation`` field on streaming delta events to normalize payload sizes as a mitigation to - certain side-channel attacks. These obfuscation fields are included by default, but add a small - amount of overhead to the data stream. You can set ``include_obfuscation`` to false to optimize - for bandwidth if you trust the network links between your application and the OpenAI API.""" - - @overload - def __init__( - self, - *, - include_obfuscation: Optional[bool] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ResponseTextDeltaEvent(ResponseStreamEvent, discriminator="response.output_text.delta"): - """Emitted when there is an additional text delta. - - :ivar type: The type of the event. Always ``response.output_text.delta``. Required. - RESPONSE_OUTPUT_TEXT_DELTA. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.RESPONSE_OUTPUT_TEXT_DELTA - :ivar item_id: The ID of the output item that the text delta was added to. Required. - :vartype item_id: str - :ivar output_index: The index of the output item that the text delta was added to. Required. - :vartype output_index: int - :ivar content_index: The index of the content part that the text delta was added to. Required. - :vartype content_index: int - :ivar delta: The text delta that was added. Required. - :vartype delta: str - :ivar sequence_number: The sequence number for this event. Required. - :vartype sequence_number: int - :ivar logprobs: The log probabilities of the tokens in the delta. Required. - :vartype logprobs: list[~azure.ai.agentserver.responses.models.models.ResponseLogProb] - """ - - type: Literal[ResponseStreamEventType.RESPONSE_OUTPUT_TEXT_DELTA] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.output_text.delta``. Required. - RESPONSE_OUTPUT_TEXT_DELTA.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the output item that the text delta was added to. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that the text delta was added to. Required.""" - content_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the content part that the text delta was added to. Required.""" - delta: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The text delta that was added. Required.""" - logprobs: list["_models.ResponseLogProb"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The log probabilities of the tokens in the delta. Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - output_index: int, - content_index: int, - delta: str, - sequence_number: int, - logprobs: list["_models.ResponseLogProb"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_OUTPUT_TEXT_DELTA # type: ignore - - -class ResponseTextDoneEvent(ResponseStreamEvent, discriminator="response.output_text.done"): - """Emitted when text content is finalized. - - :ivar type: The type of the event. Always ``response.output_text.done``. Required. - RESPONSE_OUTPUT_TEXT_DONE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.RESPONSE_OUTPUT_TEXT_DONE - :ivar item_id: The ID of the output item that the text content is finalized. Required. - :vartype item_id: str - :ivar output_index: The index of the output item that the text content is finalized. Required. - :vartype output_index: int - :ivar content_index: The index of the content part that the text content is finalized. - Required. - :vartype content_index: int - :ivar text: The text content that is finalized. Required. - :vartype text: str - :ivar sequence_number: The sequence number for this event. Required. - :vartype sequence_number: int - :ivar logprobs: The log probabilities of the tokens in the delta. Required. - :vartype logprobs: list[~azure.ai.agentserver.responses.models.models.ResponseLogProb] - """ - - type: Literal[ResponseStreamEventType.RESPONSE_OUTPUT_TEXT_DONE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.output_text.done``. Required. - RESPONSE_OUTPUT_TEXT_DONE.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the output item that the text content is finalized. Required.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that the text content is finalized. Required.""" - content_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the content part that the text content is finalized. Required.""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The text content that is finalized. Required.""" - logprobs: list["_models.ResponseLogProb"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The log probabilities of the tokens in the delta. Required.""" - - @overload - def __init__( - self, - *, - item_id: str, - output_index: int, - content_index: int, - text: str, - sequence_number: int, - logprobs: list["_models.ResponseLogProb"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_OUTPUT_TEXT_DONE # type: ignore - - -class ResponseTextParam(_Model): - """Configuration options for a text response from the model. Can be plain - text or structured JSON data. Learn more: - - * [Text inputs and outputs](/docs/guides/text) - * [Structured Outputs](/docs/guides/structured-outputs). - - :ivar format: - :vartype format: ~azure.ai.agentserver.responses.models.models.TextResponseFormatConfiguration - :ivar verbosity: Is one of the following types: Literal["low"], Literal["medium"], - Literal["high"] - :vartype verbosity: str or str or str - """ - - format: Optional["_models.TextResponseFormatConfiguration"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - verbosity: Optional[Literal["low", "medium", "high"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Is one of the following types: Literal[\"low\"], Literal[\"medium\"], Literal[\"high\"]""" - - @overload - def __init__( - self, - *, - format: Optional["_models.TextResponseFormatConfiguration"] = None, - verbosity: Optional[Literal["low", "medium", "high"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ResponseUsage(_Model): - """Represents token usage details including input tokens, output tokens, a breakdown of output - tokens, and the total tokens used. - - :ivar input_tokens: The number of input tokens. Required. - :vartype input_tokens: int - :ivar input_tokens_details: A detailed breakdown of the input tokens. Required. - :vartype input_tokens_details: - ~azure.ai.agentserver.responses.models.models.ResponseUsageInputTokensDetails - :ivar output_tokens: The number of output tokens. Required. - :vartype output_tokens: int - :ivar output_tokens_details: A detailed breakdown of the output tokens. Required. - :vartype output_tokens_details: - ~azure.ai.agentserver.responses.models.models.ResponseUsageOutputTokensDetails - :ivar total_tokens: The total number of tokens used. Required. - :vartype total_tokens: int - """ - - input_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The number of input tokens. Required.""" - input_tokens_details: "_models.ResponseUsageInputTokensDetails" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """A detailed breakdown of the input tokens. Required.""" - output_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The number of output tokens. Required.""" - output_tokens_details: "_models.ResponseUsageOutputTokensDetails" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """A detailed breakdown of the output tokens. Required.""" - total_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The total number of tokens used. Required.""" - - @overload - def __init__( - self, - *, - input_tokens: int, - input_tokens_details: "_models.ResponseUsageInputTokensDetails", - output_tokens: int, - output_tokens_details: "_models.ResponseUsageOutputTokensDetails", - total_tokens: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ResponseUsageInputTokensDetails(_Model): - """ResponseUsageInputTokensDetails. - - :ivar cached_tokens: Required. - :vartype cached_tokens: int - """ - - cached_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - cached_tokens: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ResponseUsageOutputTokensDetails(_Model): - """ResponseUsageOutputTokensDetails. - - :ivar reasoning_tokens: Required. - :vartype reasoning_tokens: int - """ - - reasoning_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - reasoning_tokens: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ResponseWebSearchCallCompletedEvent(ResponseStreamEvent, discriminator="response.web_search_call.completed"): - """Emitted when a web search call is completed. - - :ivar type: The type of the event. Always ``response.web_search_call.completed``. Required. - RESPONSE_WEB_SEARCH_CALL_COMPLETED. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_WEB_SEARCH_CALL_COMPLETED - :ivar output_index: The index of the output item that the web search call is associated with. - Required. - :vartype output_index: int - :ivar item_id: Unique ID for the output item associated with the web search call. Required. - :vartype item_id: str - :ivar sequence_number: The sequence number of the web search call being processed. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_WEB_SEARCH_CALL_COMPLETED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.web_search_call.completed``. Required. - RESPONSE_WEB_SEARCH_CALL_COMPLETED.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that the web search call is associated with. Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Unique ID for the output item associated with the web search call. Required.""" - - @overload - def __init__( - self, - *, - output_index: int, - item_id: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_WEB_SEARCH_CALL_COMPLETED # type: ignore - - -class ResponseWebSearchCallInProgressEvent(ResponseStreamEvent, discriminator="response.web_search_call.in_progress"): - """Emitted when a web search call is initiated. - - :ivar type: The type of the event. Always ``response.web_search_call.in_progress``. Required. - RESPONSE_WEB_SEARCH_CALL_IN_PROGRESS. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_WEB_SEARCH_CALL_IN_PROGRESS - :ivar output_index: The index of the output item that the web search call is associated with. - Required. - :vartype output_index: int - :ivar item_id: Unique ID for the output item associated with the web search call. Required. - :vartype item_id: str - :ivar sequence_number: The sequence number of the web search call being processed. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_WEB_SEARCH_CALL_IN_PROGRESS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.web_search_call.in_progress``. Required. - RESPONSE_WEB_SEARCH_CALL_IN_PROGRESS.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that the web search call is associated with. Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Unique ID for the output item associated with the web search call. Required.""" - - @overload - def __init__( - self, - *, - output_index: int, - item_id: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_WEB_SEARCH_CALL_IN_PROGRESS # type: ignore - - -class ResponseWebSearchCallSearchingEvent(ResponseStreamEvent, discriminator="response.web_search_call.searching"): - """Emitted when a web search call is executing. - - :ivar type: The type of the event. Always ``response.web_search_call.searching``. Required. - RESPONSE_WEB_SEARCH_CALL_SEARCHING. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.RESPONSE_WEB_SEARCH_CALL_SEARCHING - :ivar output_index: The index of the output item that the web search call is associated with. - Required. - :vartype output_index: int - :ivar item_id: Unique ID for the output item associated with the web search call. Required. - :vartype item_id: str - :ivar sequence_number: The sequence number of the web search call being processed. Required. - :vartype sequence_number: int - """ - - type: Literal[ResponseStreamEventType.RESPONSE_WEB_SEARCH_CALL_SEARCHING] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the event. Always ``response.web_search_call.searching``. Required. - RESPONSE_WEB_SEARCH_CALL_SEARCHING.""" - output_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output item that the web search call is associated with. Required.""" - item_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Unique ID for the output item associated with the web search call. Required.""" - - @overload - def __init__( - self, - *, - output_index: int, - item_id: str, - sequence_number: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ResponseStreamEventType.RESPONSE_WEB_SEARCH_CALL_SEARCHING # type: ignore - - -class ScreenshotParam(ComputerAction, discriminator="screenshot"): - """Screenshot. - - :ivar type: Specifies the event type. For a screenshot action, this property is always set to - ``screenshot``. Required. SCREENSHOT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.SCREENSHOT - """ - - type: Literal[ComputerActionType.SCREENSHOT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Specifies the event type. For a screenshot action, this property is always set to - ``screenshot``. Required. SCREENSHOT.""" - - @overload - def __init__( - self, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ComputerActionType.SCREENSHOT # type: ignore - - -class ScrollParam(ComputerAction, discriminator="scroll"): - """Scroll. - - :ivar type: Specifies the event type. For a scroll action, this property is always set to - ``scroll``. Required. SCROLL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.SCROLL - :ivar x: The x-coordinate where the scroll occurred. Required. - :vartype x: int - :ivar y: The y-coordinate where the scroll occurred. Required. - :vartype y: int - :ivar scroll_x: The horizontal scroll distance. Required. - :vartype scroll_x: int - :ivar scroll_y: The vertical scroll distance. Required. - :vartype scroll_y: int - """ - - type: Literal[ComputerActionType.SCROLL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Specifies the event type. For a scroll action, this property is always set to ``scroll``. - Required. SCROLL.""" - x: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The x-coordinate where the scroll occurred. Required.""" - y: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The y-coordinate where the scroll occurred. Required.""" - scroll_x: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The horizontal scroll distance. Required.""" - scroll_y: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The vertical scroll distance. Required.""" - - @overload - def __init__( - self, - *, - x: int, - y: int, - scroll_x: int, - scroll_y: int, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ComputerActionType.SCROLL # type: ignore - - -class SharepointGroundingToolCall(OutputItem, discriminator="sharepoint_grounding_preview_call"): - """A SharePoint grounding tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. SHAREPOINT_GROUNDING_PREVIEW_CALL. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.SHAREPOINT_GROUNDING_PREVIEW_CALL - :ivar call_id: The unique ID of the tool call generated by the model. Required. - :vartype call_id: str - :ivar arguments: A JSON string of the arguments to pass to the tool. Required. - :vartype arguments: str - :ivar status: The status of the tool call. Required. Known values are: "in_progress", - "completed", "incomplete", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ToolCallStatus - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.SHAREPOINT_GROUNDING_PREVIEW_CALL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. SHAREPOINT_GROUNDING_PREVIEW_CALL.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call generated by the model. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A JSON string of the arguments to pass to the tool. Required.""" - status: Union[str, "_models.ToolCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. Required. Known values are: \"in_progress\", \"completed\", - \"incomplete\", and \"failed\".""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - arguments: str, - status: Union[str, "_models.ToolCallStatus"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.SHAREPOINT_GROUNDING_PREVIEW_CALL # type: ignore - - -class SharepointGroundingToolCallOutput(OutputItem, discriminator="sharepoint_grounding_preview_call_output"): - """The output of a SharePoint grounding tool call. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. SHAREPOINT_GROUNDING_PREVIEW_CALL_OUTPUT. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.SHAREPOINT_GROUNDING_PREVIEW_CALL_OUTPUT - :ivar call_id: The unique ID of the tool call generated by the model. Required. - :vartype call_id: str - :ivar output: The output from the SharePoint grounding tool call. Is one of the following - types: {str: Any}, str, [Any] - :vartype output: dict[str, any] or str or list[any] - :ivar status: The status of the tool call. Required. Known values are: "in_progress", - "completed", "incomplete", and "failed". - :vartype status: str or ~azure.ai.agentserver.responses.models.models.ToolCallStatus - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.SHAREPOINT_GROUNDING_PREVIEW_CALL_OUTPUT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. SHAREPOINT_GROUNDING_PREVIEW_CALL_OUTPUT.""" - call_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the tool call generated by the model. Required.""" - output: Optional["_types.ToolCallOutputContent"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The output from the SharePoint grounding tool call. Is one of the following types: {str: Any}, - str, [Any]""" - status: Union[str, "_models.ToolCallStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the tool call. Required. Known values are: \"in_progress\", \"completed\", - \"incomplete\", and \"failed\".""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - call_id: str, - status: Union[str, "_models.ToolCallStatus"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - output: Optional["_types.ToolCallOutputContent"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.SHAREPOINT_GROUNDING_PREVIEW_CALL_OUTPUT # type: ignore - - -class SharepointGroundingToolParameters(_Model): - """The sharepoint grounding tool parameters. - - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar project_connections: The project connections attached to this tool. There can be a - maximum of 1 connection resource attached to the tool. - :vartype project_connections: - list[~azure.ai.agentserver.responses.models.models.ToolProjectConnection] - """ - - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - project_connections: Optional[list["_models.ToolProjectConnection"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The project connections attached to this tool. There can be a maximum of 1 connection resource - attached to the tool.""" - - @overload - def __init__( - self, - *, - name: Optional[str] = None, - description: Optional[str] = None, - project_connections: Optional[list["_models.ToolProjectConnection"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class SharepointPreviewTool(Tool, discriminator="sharepoint_grounding_preview"): - """The input definition information for a sharepoint tool as used to configure an agent. - - :ivar type: The object type, which is always 'sharepoint_grounding_preview'. Required. - SHAREPOINT_GROUNDING_PREVIEW. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.SHAREPOINT_GROUNDING_PREVIEW - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar sharepoint_grounding_preview: The sharepoint grounding tool parameters. Required. - :vartype sharepoint_grounding_preview: - ~azure.ai.agentserver.responses.models.models.SharepointGroundingToolParameters - """ - - type: Literal[ToolType.SHAREPOINT_GROUNDING_PREVIEW] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'sharepoint_grounding_preview'. Required. - SHAREPOINT_GROUNDING_PREVIEW.""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - sharepoint_grounding_preview: "_models.SharepointGroundingToolParameters" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The sharepoint grounding tool parameters. Required.""" - - @overload - def __init__( - self, - *, - sharepoint_grounding_preview: "_models.SharepointGroundingToolParameters", - name: Optional[str] = None, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.SHAREPOINT_GROUNDING_PREVIEW # type: ignore - - -class SkillReferenceParam(ContainerSkill, discriminator="skill_reference"): - """SkillReferenceParam. - - :ivar type: References a skill created with the /v1/skills endpoint. Required. SKILL_REFERENCE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.SKILL_REFERENCE - :ivar skill_id: The ID of the referenced skill. Required. - :vartype skill_id: str - :ivar version: Optional skill version. Use a positive integer or 'latest'. Omit for default. - :vartype version: str - """ - - type: Literal[ContainerSkillType.SKILL_REFERENCE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """References a skill created with the /v1/skills endpoint. Required. SKILL_REFERENCE.""" - skill_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the referenced skill. Required.""" - version: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional skill version. Use a positive integer or 'latest'. Omit for default.""" - - @overload - def __init__( - self, - *, - skill_id: str, - version: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ContainerSkillType.SKILL_REFERENCE # type: ignore - - -class ToolChoiceParam(_Model): - """How the model should select which tool (or tools) to use when generating a response. See the - ``tools`` parameter to see how to specify which tools the model can call. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ToolChoiceAllowed, SpecificApplyPatchParam, ToolChoiceCodeInterpreter, - ToolChoiceComputerUsePreview, ToolChoiceCustom, ToolChoiceFileSearch, ToolChoiceFunction, - ToolChoiceImageGeneration, ToolChoiceMCP, SpecificFunctionShellParam, - ToolChoiceWebSearchPreview, ToolChoiceWebSearchPreview20250311 - - :ivar type: Required. Known values are: "allowed_tools", "function", "mcp", "custom", - "apply_patch", "shell", "file_search", "web_search_preview", "computer_use_preview", - "web_search_preview_2025_03_11", "image_generation", and "code_interpreter". - :vartype type: str or ~azure.ai.agentserver.responses.models.models.ToolChoiceParamType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"allowed_tools\", \"function\", \"mcp\", \"custom\", - \"apply_patch\", \"shell\", \"file_search\", \"web_search_preview\", \"computer_use_preview\", - \"web_search_preview_2025_03_11\", \"image_generation\", and \"code_interpreter\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class SpecificApplyPatchParam(ToolChoiceParam, discriminator="apply_patch"): - """Specific apply patch tool choice. - - :ivar type: The tool to call. Always ``apply_patch``. Required. APPLY_PATCH. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.APPLY_PATCH - """ - - type: Literal[ToolChoiceParamType.APPLY_PATCH] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The tool to call. Always ``apply_patch``. Required. APPLY_PATCH.""" - - @overload - def __init__( - self, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolChoiceParamType.APPLY_PATCH # type: ignore - - -class SpecificFunctionShellParam(ToolChoiceParam, discriminator="shell"): - """Specific shell tool choice. - - :ivar type: The tool to call. Always ``shell``. Required. SHELL. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.SHELL - """ - - type: Literal[ToolChoiceParamType.SHELL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The tool to call. Always ``shell``. Required. SHELL.""" - - @overload - def __init__( - self, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolChoiceParamType.SHELL # type: ignore - - -class StructuredOutputDefinition(_Model): - """A structured output that can be produced by the agent. - - :ivar name: The name of the structured output. Required. - :vartype name: str - :ivar description: A description of the output to emit. Used by the model to determine when to - emit the output. Required. - :vartype description: str - :ivar schema: The JSON schema for the structured output. Required. - :vartype schema: dict[str, any] - :ivar strict: Whether to enforce strict validation. Default ``true``. Required. - :vartype strict: bool - """ - - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the structured output. Required.""" - description: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A description of the output to emit. Used by the model to determine when to emit the output. - Required.""" - schema: dict[str, Any] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The JSON schema for the structured output. Required.""" - strict: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Whether to enforce strict validation. Default ``true``. Required.""" - - @overload - def __init__( - self, - *, - name: str, - description: str, - schema: dict[str, Any], - strict: bool, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class StructuredOutputsOutputItem(OutputItem, discriminator="structured_outputs"): - """StructuredOutputsOutputItem. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. STRUCTURED_OUTPUTS. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.STRUCTURED_OUTPUTS - :ivar output: The structured output captured during the response. Required. - :vartype output: any - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.STRUCTURED_OUTPUTS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. STRUCTURED_OUTPUTS.""" - output: Any = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The structured output captured during the response. Required.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - output: Any, - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.STRUCTURED_OUTPUTS # type: ignore - - -class SummaryTextContent(MessageContent, discriminator="summary_text"): - """Summary text. - - :ivar type: The type of the object. Always ``summary_text``. Required. SUMMARY_TEXT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.SUMMARY_TEXT - :ivar text: A summary of the reasoning output from the model so far. Required. - :vartype text: str - """ - - type: Literal[MessageContentType.SUMMARY_TEXT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the object. Always ``summary_text``. Required. SUMMARY_TEXT.""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A summary of the reasoning output from the model so far. Required.""" - - @overload - def __init__( - self, - *, - text: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = MessageContentType.SUMMARY_TEXT # type: ignore - - -class TextContent(MessageContent, discriminator="text"): - """Text Content. - - :ivar type: Required. TEXT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.TEXT - :ivar text: Required. - :vartype text: str - """ - - type: Literal[MessageContentType.TEXT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. TEXT.""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - text: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = MessageContentType.TEXT # type: ignore - - -class TextResponseFormatConfiguration(_Model): - """An object specifying the format that the model must output. Configuring ``{ "type": - "json_schema" }`` enables Structured Outputs, which ensures the model will match your supplied - JSON schema. Learn more in the `Structured Outputs guide `_. - The default format is ``{ "type": "text" }`` with no additional options. *Not recommended for - gpt-4o and newer models:** Setting to ``{ "type": "json_object" }`` enables the older JSON - mode, which ensures the message the model generates is valid JSON. Using ``json_schema`` is - preferred for models that support it. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - TextResponseFormatConfigurationResponseFormatJsonObject, TextResponseFormatJsonSchema, - TextResponseFormatConfigurationResponseFormatText - - :ivar type: Required. Known values are: "text", "json_schema", and "json_object". - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.TextResponseFormatConfigurationType - """ - - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"text\", \"json_schema\", and \"json_object\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class TextResponseFormatConfigurationResponseFormatJsonObject( - TextResponseFormatConfiguration, discriminator="json_object" -): # pylint: disable=name-too-long - """JSON object. - - :ivar type: The type of response format being defined. Always ``json_object``. Required. - JSON_OBJECT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.JSON_OBJECT - """ - - type: Literal[TextResponseFormatConfigurationType.JSON_OBJECT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of response format being defined. Always ``json_object``. Required. JSON_OBJECT.""" - - @overload - def __init__( - self, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = TextResponseFormatConfigurationType.JSON_OBJECT # type: ignore - - -class TextResponseFormatConfigurationResponseFormatText( - TextResponseFormatConfiguration, discriminator="text" -): # pylint: disable=name-too-long - """Text. - - :ivar type: The type of response format being defined. Always ``text``. Required. TEXT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.TEXT - """ - - type: Literal[TextResponseFormatConfigurationType.TEXT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of response format being defined. Always ``text``. Required. TEXT.""" - - @overload - def __init__( - self, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = TextResponseFormatConfigurationType.TEXT # type: ignore - - -class TextResponseFormatJsonSchema(TextResponseFormatConfiguration, discriminator="json_schema"): - """JSON schema. - - :ivar type: The type of response format being defined. Always ``json_schema``. Required. - JSON_SCHEMA. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.JSON_SCHEMA - :ivar description: A description of what the response format is for, used by the model to - determine how to respond in the format. - :vartype description: str - :ivar name: The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and - dashes, with a maximum length of 64. Required. - :vartype name: str - :ivar schema: Required. - :vartype schema: ~azure.ai.agentserver.responses.models.models.ResponseFormatJsonSchemaSchema - :ivar strict: - :vartype strict: bool - """ - - type: Literal[TextResponseFormatConfigurationType.JSON_SCHEMA] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of response format being defined. Always ``json_schema``. Required. JSON_SCHEMA.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A description of what the response format is for, used by the model to determine how to respond - in the format.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with - a maximum length of 64. Required.""" - schema: "_models.ResponseFormatJsonSchemaSchema" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Required.""" - strict: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - name: str, - schema: "_models.ResponseFormatJsonSchemaSchema", - description: Optional[str] = None, - strict: Optional[bool] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = TextResponseFormatConfigurationType.JSON_SCHEMA # type: ignore - - -class ToolChoiceAllowed(ToolChoiceParam, discriminator="allowed_tools"): - """Allowed tools. - - :ivar type: Allowed tool configuration type. Always ``allowed_tools``. Required. ALLOWED_TOOLS. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.ALLOWED_TOOLS - :ivar mode: Constrains the tools available to the model to a pre-defined set. ``auto`` allows - the model to pick from among the allowed tools and generate a message. ``required`` requires - the model to call one or more of the allowed tools. Required. Is either a Literal["auto"] type - or a Literal["required"] type. - :vartype mode: str or str - :ivar tools: A list of tool definitions that the model should be allowed to call. For the - Responses API, the list of tool definitions might look like: - - .. code-block:: json - - [ - { "type": "function", "name": "get_weather" }, - { "type": "mcp", "server_label": "deepwiki" }, - { "type": "image_generation" } - ]. Required. - :vartype tools: list[dict[str, any]] - """ - - type: Literal[ToolChoiceParamType.ALLOWED_TOOLS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Allowed tool configuration type. Always ``allowed_tools``. Required. ALLOWED_TOOLS.""" - mode: Literal["auto", "required"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Constrains the tools available to the model to a pre-defined set. ``auto`` allows the model to - pick from among the allowed tools and generate a message. ``required`` requires the model to - call one or more of the allowed tools. Required. Is either a Literal[\"auto\"] type or a - Literal[\"required\"] type.""" - tools: list[dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A list of tool definitions that the model should be allowed to call. For the Responses API, the - list of tool definitions might look like: - - .. code-block:: json - - [ - { \"type\": \"function\", \"name\": \"get_weather\" }, - { \"type\": \"mcp\", \"server_label\": \"deepwiki\" }, - { \"type\": \"image_generation\" } - ]. Required.""" - - @overload - def __init__( - self, - *, - mode: Literal["auto", "required"], - tools: list[dict[str, Any]], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolChoiceParamType.ALLOWED_TOOLS # type: ignore - - -class ToolChoiceCodeInterpreter(ToolChoiceParam, discriminator="code_interpreter"): - """Indicates that the model should use a built-in tool to generate a response. `Learn more about - built-in tools `_. - - :ivar type: Required. CODE_INTERPRETER. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CODE_INTERPRETER - """ - - type: Literal[ToolChoiceParamType.CODE_INTERPRETER] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. CODE_INTERPRETER.""" - - @overload - def __init__( - self, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolChoiceParamType.CODE_INTERPRETER # type: ignore - - -class ToolChoiceComputerUsePreview(ToolChoiceParam, discriminator="computer_use_preview"): - """Indicates that the model should use a built-in tool to generate a response. `Learn more about - built-in tools `_. - - :ivar type: Required. COMPUTER_USE_PREVIEW. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.COMPUTER_USE_PREVIEW - """ - - type: Literal[ToolChoiceParamType.COMPUTER_USE_PREVIEW] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. COMPUTER_USE_PREVIEW.""" - - @overload - def __init__( - self, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolChoiceParamType.COMPUTER_USE_PREVIEW # type: ignore - - -class ToolChoiceCustom(ToolChoiceParam, discriminator="custom"): - """Custom tool. - - :ivar type: For custom tool calling, the type is always ``custom``. Required. CUSTOM. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.CUSTOM - :ivar name: The name of the custom tool to call. Required. - :vartype name: str - """ - - type: Literal[ToolChoiceParamType.CUSTOM] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """For custom tool calling, the type is always ``custom``. Required. CUSTOM.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the custom tool to call. Required.""" - - @overload - def __init__( - self, - *, - name: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolChoiceParamType.CUSTOM # type: ignore - - -class ToolChoiceFileSearch(ToolChoiceParam, discriminator="file_search"): - """Indicates that the model should use a built-in tool to generate a response. `Learn more about - built-in tools `_. - - :ivar type: Required. FILE_SEARCH. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.FILE_SEARCH - """ - - type: Literal[ToolChoiceParamType.FILE_SEARCH] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. FILE_SEARCH.""" - - @overload - def __init__( - self, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolChoiceParamType.FILE_SEARCH # type: ignore - - -class ToolChoiceFunction(ToolChoiceParam, discriminator="function"): - """Function tool. - - :ivar type: For function calling, the type is always ``function``. Required. FUNCTION. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.FUNCTION - :ivar name: The name of the function to call. Required. - :vartype name: str - """ - - type: Literal[ToolChoiceParamType.FUNCTION] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """For function calling, the type is always ``function``. Required. FUNCTION.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the function to call. Required.""" - - @overload - def __init__( - self, - *, - name: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolChoiceParamType.FUNCTION # type: ignore - - -class ToolChoiceImageGeneration(ToolChoiceParam, discriminator="image_generation"): - """Indicates that the model should use a built-in tool to generate a response. `Learn more about - built-in tools `_. - - :ivar type: Required. IMAGE_GENERATION. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.IMAGE_GENERATION - """ - - type: Literal[ToolChoiceParamType.IMAGE_GENERATION] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. IMAGE_GENERATION.""" - - @overload - def __init__( - self, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolChoiceParamType.IMAGE_GENERATION # type: ignore - - -class ToolChoiceMCP(ToolChoiceParam, discriminator="mcp"): - """MCP tool. - - :ivar type: For MCP tools, the type is always ``mcp``. Required. MCP. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.MCP - :ivar server_label: The label of the MCP server to use. Required. - :vartype server_label: str - :ivar name: - :vartype name: str - """ - - type: Literal[ToolChoiceParamType.MCP] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """For MCP tools, the type is always ``mcp``. Required. MCP.""" - server_label: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The label of the MCP server to use. Required.""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - server_label: str, - name: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolChoiceParamType.MCP # type: ignore - - -class ToolChoiceWebSearchPreview(ToolChoiceParam, discriminator="web_search_preview"): - """Indicates that the model should use a built-in tool to generate a response. `Learn more about - built-in tools `_. - - :ivar type: Required. WEB_SEARCH_PREVIEW. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.WEB_SEARCH_PREVIEW - """ - - type: Literal[ToolChoiceParamType.WEB_SEARCH_PREVIEW] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. WEB_SEARCH_PREVIEW.""" - - @overload - def __init__( - self, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolChoiceParamType.WEB_SEARCH_PREVIEW # type: ignore - - -class ToolChoiceWebSearchPreview20250311(ToolChoiceParam, discriminator="web_search_preview_2025_03_11"): - """Indicates that the model should use a built-in tool to generate a response. `Learn more about - built-in tools `_. - - :ivar type: Required. WEB_SEARCH_PREVIEW2025_03_11. - :vartype type: str or - ~azure.ai.agentserver.responses.models.models.WEB_SEARCH_PREVIEW2025_03_11 - """ - - type: Literal[ToolChoiceParamType.WEB_SEARCH_PREVIEW2025_03_11] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. WEB_SEARCH_PREVIEW2025_03_11.""" - - @overload - def __init__( - self, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolChoiceParamType.WEB_SEARCH_PREVIEW2025_03_11 # type: ignore - - -class ToolProjectConnection(_Model): - """A project connection resource. - - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar project_connection_id: A project connection in a ToolProjectConnectionList attached to - this tool. Required. - :vartype project_connection_id: str - """ - - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - project_connection_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A project connection in a ToolProjectConnectionList attached to this tool. Required.""" - - @overload - def __init__( - self, - *, - project_connection_id: str, - name: Optional[str] = None, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class TopLogProb(_Model): - """Top log probability. - - :ivar token: Required. - :vartype token: str - :ivar logprob: Required. - :vartype logprob: int - :ivar bytes: Required. - :vartype bytes: list[int] - """ - - token: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - logprob: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - bytes: list[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - token: str, - logprob: int, - bytes: list[int], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class TypeParam(ComputerAction, discriminator="type"): - """Type. - - :ivar type: Specifies the event type. For a type action, this property is always set to - ``type``. Required. TYPE. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.TYPE - :ivar text: The text to type. Required. - :vartype text: str - """ - - type: Literal[ComputerActionType.TYPE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Specifies the event type. For a type action, this property is always set to ``type``. Required. - TYPE.""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The text to type. Required.""" - - @overload - def __init__( - self, - *, - text: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ComputerActionType.TYPE # type: ignore - - -class UrlCitationBody(Annotation, discriminator="url_citation"): - """URL citation. - - :ivar type: The type of the URL citation. Always ``url_citation``. Required. URL_CITATION. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.URL_CITATION - :ivar url: The URL of the web resource. Required. - :vartype url: str - :ivar start_index: The index of the first character of the URL citation in the message. - Required. - :vartype start_index: int - :ivar end_index: The index of the last character of the URL citation in the message. Required. - :vartype end_index: int - :ivar title: The title of the web resource. Required. - :vartype title: str - """ - - type: Literal[AnnotationType.URL_CITATION] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the URL citation. Always ``url_citation``. Required. URL_CITATION.""" - url: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The URL of the web resource. Required.""" - start_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the first character of the URL citation in the message. Required.""" - end_index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the last character of the URL citation in the message. Required.""" - title: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The title of the web resource. Required.""" - - @overload - def __init__( - self, - *, - url: str, - start_index: int, - end_index: int, - title: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = AnnotationType.URL_CITATION # type: ignore - - -class UserProfileMemoryItem(MemoryItem, discriminator="user_profile"): - """A memory item specifically containing user profile information extracted from conversations, - such as preferences, interests, and personal details. - - :ivar memory_id: The unique ID of the memory item. Required. - :vartype memory_id: str - :ivar updated_at: The last update time of the memory item. Required. - :vartype updated_at: ~datetime.datetime - :ivar scope: The namespace that logically groups and isolates memories, such as a user ID. - Required. - :vartype scope: str - :ivar content: The content of the memory. Required. - :vartype content: str - :ivar kind: The kind of the memory item. Required. User profile information extracted from - conversations. - :vartype kind: str or ~azure.ai.agentserver.responses.models.models.USER_PROFILE - """ - - kind: Literal[MemoryItemKind.USER_PROFILE] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The kind of the memory item. Required. User profile information extracted from conversations.""" - - @overload - def __init__( - self, - *, - memory_id: str, - updated_at: datetime.datetime, - scope: str, - content: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.kind = MemoryItemKind.USER_PROFILE # type: ignore - - -class VectorStoreFileAttributes(_Model): - """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing - additional information about the object in a structured format, and querying for objects via - API or the dashboard. Keys are strings with a maximum length of 64 characters. Values are - strings with a maximum length of 512 characters, booleans, or numbers. - - """ - - -class WaitParam(ComputerAction, discriminator="wait"): - """Wait. - - :ivar type: Specifies the event type. For a wait action, this property is always set to - ``wait``. Required. WAIT. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.WAIT - """ - - type: Literal[ComputerActionType.WAIT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Specifies the event type. For a wait action, this property is always set to ``wait``. Required. - WAIT.""" - - @overload - def __init__( - self, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ComputerActionType.WAIT # type: ignore - - -class WebSearchActionFind(_Model): - """Find action. - - :ivar type: The action type. Required. Default value is "find_in_page". - :vartype type: str - :ivar url: The URL of the page searched for the pattern. Required. - :vartype url: str - :ivar pattern: The pattern or text to search for within the page. Required. - :vartype pattern: str - """ - - type: Literal["find_in_page"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The action type. Required. Default value is \"find_in_page\".""" - url: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The URL of the page searched for the pattern. Required.""" - pattern: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The pattern or text to search for within the page. Required.""" - - @overload - def __init__( - self, - *, - url: str, - pattern: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["find_in_page"] = "find_in_page" - - -class WebSearchActionOpenPage(_Model): - """Open page action. - - :ivar type: The action type. Required. Default value is "open_page". - :vartype type: str - :ivar url: The URL opened by the model. - :vartype url: str - """ - - type: Literal["open_page"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The action type. Required. Default value is \"open_page\".""" - url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The URL opened by the model.""" - - @overload - def __init__( - self, - *, - url: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["open_page"] = "open_page" - - -class WebSearchActionSearch(_Model): - """Search action. - - :ivar type: The action type. Required. Default value is "search". - :vartype type: str - :ivar query: [DEPRECATED] The search query. Required. - :vartype query: str - :ivar queries: Search queries. - :vartype queries: list[str] - :ivar sources: Web search sources. - :vartype sources: - list[~azure.ai.agentserver.responses.models.models.WebSearchActionSearchSources] - """ - - type: Literal["search"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The action type. Required. Default value is \"search\".""" - query: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """[DEPRECATED] The search query. Required.""" - queries: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Search queries.""" - sources: Optional[list["_models.WebSearchActionSearchSources"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Web search sources.""" - - @overload - def __init__( - self, - *, - query: str, - queries: Optional[list[str]] = None, - sources: Optional[list["_models.WebSearchActionSearchSources"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["search"] = "search" - - -class WebSearchActionSearchSources(_Model): - """WebSearchActionSearchSources. - - :ivar type: Required. Default value is "url". - :vartype type: str - :ivar url: Required. - :vartype url: str - """ - - type: Literal["url"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required. Default value is \"url\".""" - url: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - url: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["url"] = "url" - - -class WebSearchApproximateLocation(_Model): - """Web search approximate location. - - :ivar type: The type of location approximation. Always ``approximate``. Required. Default value - is "approximate". - :vartype type: str - :ivar country: - :vartype country: str - :ivar region: - :vartype region: str - :ivar city: - :vartype city: str - :ivar timezone: - :vartype timezone: str - """ - - type: Literal["approximate"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The type of location approximation. Always ``approximate``. Required. Default value is - \"approximate\".""" - country: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - region: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - city: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - timezone: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - country: Optional[str] = None, - region: Optional[str] = None, - city: Optional[str] = None, - timezone: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["approximate"] = "approximate" - - -class WebSearchConfiguration(_Model): - """A web search configuration for bing custom search. - - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar project_connection_id: Project connection id for grounding with bing custom search. - Required. - :vartype project_connection_id: str - :ivar instance_name: Name of the custom configuration instance given to config. Required. - :vartype instance_name: str - """ - - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - project_connection_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Project connection id for grounding with bing custom search. Required.""" - instance_name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Name of the custom configuration instance given to config. Required.""" - - @overload - def __init__( - self, - *, - project_connection_id: str, - instance_name: str, - name: Optional[str] = None, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class WebSearchPreviewTool(Tool, discriminator="web_search_preview"): - """Web search preview. - - :ivar type: The type of the web search tool. One of ``web_search_preview`` or - ``web_search_preview_2025_03_11``. Required. WEB_SEARCH_PREVIEW. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.WEB_SEARCH_PREVIEW - :ivar user_location: - :vartype user_location: ~azure.ai.agentserver.responses.models.models.ApproximateLocation - :ivar search_context_size: High level guidance for the amount of context window space to use - for the search. One of ``low``, ``medium``, or ``high``. ``medium`` is the default. Known - values are: "low", "medium", and "high". - :vartype search_context_size: str or - ~azure.ai.agentserver.responses.models.models.SearchContextSize - """ - - type: Literal[ToolType.WEB_SEARCH_PREVIEW] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the web search tool. One of ``web_search_preview`` or - ``web_search_preview_2025_03_11``. Required. WEB_SEARCH_PREVIEW.""" - user_location: Optional["_models.ApproximateLocation"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - search_context_size: Optional[Union[str, "_models.SearchContextSize"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """High level guidance for the amount of context window space to use for the search. One of - ``low``, ``medium``, or ``high``. ``medium`` is the default. Known values are: \"low\", - \"medium\", and \"high\".""" - - @overload - def __init__( - self, - *, - user_location: Optional["_models.ApproximateLocation"] = None, - search_context_size: Optional[Union[str, "_models.SearchContextSize"]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.WEB_SEARCH_PREVIEW # type: ignore - - -class WebSearchTool(Tool, discriminator="web_search"): - """Web search. - - :ivar type: The type of the web search tool. One of ``web_search`` or - ``web_search_2025_08_26``. Required. WEB_SEARCH. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.WEB_SEARCH - :ivar filters: - :vartype filters: ~azure.ai.agentserver.responses.models.models.WebSearchToolFilters - :ivar user_location: - :vartype user_location: - ~azure.ai.agentserver.responses.models.models.WebSearchApproximateLocation - :ivar search_context_size: High level guidance for the amount of context window space to use - for the search. One of ``low``, ``medium``, or ``high``. ``medium`` is the default. Is one of - the following types: Literal["low"], Literal["medium"], Literal["high"] - :vartype search_context_size: str or str or str - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar custom_search_configuration: The project connections attached to this tool. There can be - a maximum of 1 connection resource attached to the tool. - :vartype custom_search_configuration: - ~azure.ai.agentserver.responses.models.models.WebSearchConfiguration - """ - - type: Literal[ToolType.WEB_SEARCH] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the web search tool. One of ``web_search`` or ``web_search_2025_08_26``. Required. - WEB_SEARCH.""" - filters: Optional["_models.WebSearchToolFilters"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - user_location: Optional["_models.WebSearchApproximateLocation"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - search_context_size: Optional[Literal["low", "medium", "high"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """High level guidance for the amount of context window space to use for the search. One of - ``low``, ``medium``, or ``high``. ``medium`` is the default. Is one of the following types: - Literal[\"low\"], Literal[\"medium\"], Literal[\"high\"]""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - custom_search_configuration: Optional["_models.WebSearchConfiguration"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The project connections attached to this tool. There can be a maximum of 1 connection resource - attached to the tool.""" - - @overload - def __init__( - self, - *, - filters: Optional["_models.WebSearchToolFilters"] = None, - user_location: Optional["_models.WebSearchApproximateLocation"] = None, - search_context_size: Optional[Literal["low", "medium", "high"]] = None, - name: Optional[str] = None, - description: Optional[str] = None, - custom_search_configuration: Optional["_models.WebSearchConfiguration"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.WEB_SEARCH # type: ignore - - -class WebSearchToolFilters(_Model): - """WebSearchToolFilters. - - :ivar allowed_domains: - :vartype allowed_domains: list[str] - """ - - allowed_domains: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - - @overload - def __init__( - self, - *, - allowed_domains: Optional[list[str]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class WorkflowActionOutputItem(OutputItem, discriminator="workflow_action"): - """WorkflowActionOutputItem. - - :ivar agent_reference: The agent that created the item. - :vartype agent_reference: ~azure.ai.agentserver.responses.models.models.AgentReference - :ivar response_id: The response on which the item is created. - :vartype response_id: str - :ivar type: Required. WORKFLOW_ACTION. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.WORKFLOW_ACTION - :ivar kind: The kind of CSDL action (e.g., 'SetVariable', 'InvokeAzureAgent'). Required. - :vartype kind: str - :ivar action_id: Unique identifier for the action. Required. - :vartype action_id: str - :ivar parent_action_id: ID of the parent action if this is a nested action. - :vartype parent_action_id: str - :ivar previous_action_id: ID of the previous action if this action follows another. - :vartype previous_action_id: str - :ivar status: Status of the action (e.g., 'in_progress', 'completed', 'failed', 'cancelled'). - Required. Is one of the following types: Literal["completed"], Literal["failed"], - Literal["in_progress"], Literal["cancelled"] - :vartype status: str or str or str or str - :ivar id: Required. - :vartype id: str - """ - - type: Literal[OutputItemType.WORKFLOW_ACTION] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. WORKFLOW_ACTION.""" - kind: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The kind of CSDL action (e.g., 'SetVariable', 'InvokeAzureAgent'). Required.""" - action_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Unique identifier for the action. Required.""" - parent_action_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """ID of the parent action if this is a nested action.""" - previous_action_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """ID of the previous action if this action follows another.""" - status: Literal["completed", "failed", "in_progress", "cancelled"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Status of the action (e.g., 'in_progress', 'completed', 'failed', 'cancelled'). Required. Is - one of the following types: Literal[\"completed\"], Literal[\"failed\"], - Literal[\"in_progress\"], Literal[\"cancelled\"]""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" - - @overload - def __init__( - self, - *, - kind: str, - action_id: str, - status: Literal["completed", "failed", "in_progress", "cancelled"], - id: str, # pylint: disable=redefined-builtin - agent_reference: Optional["_models.AgentReference"] = None, - response_id: Optional[str] = None, - parent_action_id: Optional[str] = None, - previous_action_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = OutputItemType.WORKFLOW_ACTION # type: ignore - - -class WorkIQPreviewTool(Tool, discriminator="work_iq_preview"): - """A WorkIQ server-side tool. - - :ivar type: The object type, which is always 'work_iq_preview'. Required. WORK_IQ_PREVIEW. - :vartype type: str or ~azure.ai.agentserver.responses.models.models.WORK_IQ_PREVIEW - :ivar work_iq_preview: The WorkIQ tool parameters. Required. - :vartype work_iq_preview: - ~azure.ai.agentserver.responses.models.models.WorkIQPreviewToolParameters - """ - - type: Literal[ToolType.WORK_IQ_PREVIEW] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'work_iq_preview'. Required. WORK_IQ_PREVIEW.""" - work_iq_preview: "_models.WorkIQPreviewToolParameters" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The WorkIQ tool parameters. Required.""" - - @overload - def __init__( - self, - *, - work_iq_preview: "_models.WorkIQPreviewToolParameters", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type = ToolType.WORK_IQ_PREVIEW # type: ignore - - -class WorkIQPreviewToolParameters(_Model): - """The WorkIQ tool parameters. - - :ivar project_connection_id: The ID of the WorkIQ project connection. Required. - :vartype project_connection_id: str - """ - - project_connection_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the WorkIQ project connection. Required.""" - - @overload - def __init__( - self, - *, - project_connection_id: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/models/_patch.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/models/_patch.py deleted file mode 100644 index 9f85da657361..000000000000 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/models/_patch.py +++ /dev/null @@ -1,225 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------- -"""Hand-written customizations injected into the generated models package. - -This file is copied over the generated ``_patch.py`` inside -``sdk/models/models/`` by ``make generate-models``. Anything listed in -``__all__`` is automatically re-exported by the generated ``__init__.py``, -shadowing the generated class of the same name. - -Approach follows the official customization guide: -https://aka.ms/azsdk/python/dpcodegen/python/customize -""" - -from enum import Enum -from typing import TYPE_CHECKING, Any, Optional - -from azure.core import CaseInsensitiveEnumMeta - -from .._utils.model_base import rest_field -from ._models import CreateResponse as CreateResponseGenerated -from ._models import ResponseObject as ResponseObjectGenerated -from ._models import ToolChoiceAllowed as ToolChoiceAllowedGenerated - -if TYPE_CHECKING: - from ._models import OutputItem - -_VISIBILITY = ["read", "create", "update", "delete", "query"] - - -class ResponseIncompleteReason(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Reason a response finished as incomplete. - - The upstream TypeSpec defines this as an inline literal union - (``"max_output_tokens" | "content_filter"``), so the code generator - emits ``Literal[...]`` instead of a named enum. This hand-written - enum provides a friendlier symbolic constant for SDK consumers. - """ - - MAX_OUTPUT_TOKENS = "max_output_tokens" - """The response was cut short because the maximum output token limit was reached.""" - CONTENT_FILTER = "content_filter" - """The response was cut short because of a content filter.""" - - -# --------------------------------------------------------------------------- -# Fix temperature / top_p types: numeric → float (emitter bug workaround) -# -# The upstream TypeSpec defines temperature and top_p as ``numeric | null`` -# (the abstract base scalar for all numbers). The TypeSpec emitter correctly -# maps this to ``double?`` but @azure-tools/typespec-python@0.61.2 maps -# ``numeric`` → ``int``. The OpenAPI 3 spec emits ``type: number`` -# (i.e. float), so ``int`` is wrong. -# -# Per the official customization guide we subclass the generated models and -# re-declare the affected fields with the correct type. The generated -# ``__init__.py`` picks up these subclasses via ``from ._patch import *`` -# which shadows the generated names. -# -# Additionally, we override fields whose generated docstrings contain -# duplicate RST link targets (``Learn more``) or malformed bullet lists -# that break ``sphinx-build -W``. -# --------------------------------------------------------------------------- - -# -- Docstrings for fields with "Learn more" links -------------------------- -# RST named hyperlinks (single trailing ``_``) must be unique per page. -# Because CreateResponse and ResponseObject both share these fields, and -# both appear on the same Sphinx page, the identical "Learn more" targets -# collide. Anonymous hyperlinks (double ``__``) avoid the conflict. - - -class CreateResponse(CreateResponseGenerated): - """Override generated ``CreateResponse`` to correct temperature/top_p types.""" - - temperature: Optional[float] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """Sampling temperature. Float between 0 and 2.""" - top_p: Optional[float] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """Nucleus sampling parameter. Float between 0 and 1.""" - user: Optional[str] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """This field is being replaced by ``safety_identifier`` and - ``prompt_cache_key``. Use ``prompt_cache_key`` instead to maintain - caching optimizations. A stable identifier for your end-users. - Used to boost cache hit rates by better bucketing similar requests - and to help OpenAI detect and prevent abuse. - `Learn more `__.""" - safety_identifier: Optional[str] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """A stable identifier used to help detect users of your application - that may be violating OpenAI's usage policies. The IDs should be a - string that uniquely identifies each user. We recommend hashing - their username or email address, in order to avoid sending us any - identifying information. - `Learn more `__.""" - prompt_cache_key: Optional[str] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """Used by OpenAI to cache responses for similar requests to optimize - your cache hit rates. Replaces the ``user`` field. - `Learn more `__.""" - - -class ResponseObject(ResponseObjectGenerated): - """Override generated ``ResponseObject`` to correct temperature/top_p types - and fix Sphinx docstring warnings.""" - - temperature: Optional[float] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """Sampling temperature. Float between 0 and 2.""" - top_p: Optional[float] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """Nucleus sampling parameter. Float between 0 and 1.""" - output: list["OutputItem"] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """An array of content items generated by the model. - - * The length and order of items in the ``output`` array is dependent - on the model's response. - * Rather than accessing the first item in the ``output`` array and - assuming it's an ``assistant`` message with the content generated by - the model, you might consider using the ``output_text`` property where - supported in SDKs. - - Required.""" - user: Optional[str] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """This field is being replaced by ``safety_identifier`` and - ``prompt_cache_key``. Use ``prompt_cache_key`` instead to maintain - caching optimizations. A stable identifier for your end-users. - Used to boost cache hit rates by better bucketing similar requests - and to help OpenAI detect and prevent abuse. - `Learn more `__.""" - safety_identifier: Optional[str] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """A stable identifier used to help detect users of your application - that may be violating OpenAI's usage policies. The IDs should be a - string that uniquely identifies each user. We recommend hashing - their username or email address, in order to avoid sending us any - identifying information. - `Learn more `__.""" - prompt_cache_key: Optional[str] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """Used by OpenAI to cache responses for similar requests to optimize - your cache hit rates. Replaces the ``user`` field. - `Learn more `__.""" - - -class ToolChoiceAllowed(ToolChoiceAllowedGenerated): - """Override generated ``ToolChoiceAllowed`` to fix Sphinx code-block warning.""" - - tools: list[dict[str, Any]] = rest_field(visibility=_VISIBILITY) # pyright: ignore[reportIncompatibleVariableOverride] - """A list of tool definitions that the model should be allowed to call. - For the Responses API, the list of tool definitions might look like: - - .. code-block:: json - - [ - { "type": "function", "name": "get_weather" }, - { "type": "mcp", "server_label": "deepwiki" }, - { "type": "image_generation" } - ] - - Required.""" - - -__all__: list[str] = [ - "ResponseIncompleteReason", - "CreateResponse", - "ResponseObject", - "ToolChoiceAllowed", -] - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ - # Fix IncludeEnum docstring — bullet list continuation lines need proper - # indentation so that Sphinx doesn't emit "Bullet list ends without a - # blank line; unexpected unindent" warnings. - from ._enums import IncludeEnum - - IncludeEnum.__doc__ = ( - "Specify additional output data to include in the model response." - " Currently supported values are:\n" - "\n" - "* ``web_search_call.action.sources``: Include the sources of the" - " web search tool call.\n" - "* ``code_interpreter_call.outputs``: Includes the outputs of python" - " code execution in code interpreter tool call items.\n" - "* ``computer_call_output.output.image_url``: Include image urls" - " from the computer call output.\n" - "* ``file_search_call.results``: Include the search results of the" - " file search tool call.\n" - "* ``message.input_image.image_url``: Include image urls from the" - " input message.\n" - "* ``message.output_text.logprobs``: Include logprobs with assistant" - " messages.\n" - "* ``reasoning.encrypted_content``: Includes an encrypted version" - " of reasoning tokens in reasoning item outputs. This enables" - " reasoning items to be used in multi-turn conversations when using" - " the Responses API statelessly (like when the ``store`` parameter" - " is set to ``false``, or when an organization is enrolled in the" - " zero data retention program).\n" - ) - - # Fix duplicate "Learn more about built-in tools" RST targets. - # Multiple ToolChoice* classes share the same named hyperlink which causes - # "Duplicate explicit target name" warnings. Use anonymous hyperlinks. - from ._models import ( - ToolChoiceCodeInterpreter, - ToolChoiceComputerUsePreview, - ToolChoiceFileSearch, - ToolChoiceImageGeneration, - ToolChoiceWebSearchPreview, - ToolChoiceWebSearchPreview20250311, - ) - - for cls in ( - ToolChoiceCodeInterpreter, - ToolChoiceComputerUsePreview, - ToolChoiceFileSearch, - ToolChoiceImageGeneration, - ToolChoiceWebSearchPreview, - ToolChoiceWebSearchPreview20250311, - ): - # Only patch the first paragraph (class docstring), keep :ivar lines. - original = cls.__doc__ or "" - if "`Learn more about" in original: - cls.__doc__ = original.replace("`_.", "`__.") diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/py.typed b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/sdk/models/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/types.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/types.py new file mode 100644 index 000000000000..1e9f92d3a322 --- /dev/null +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_generated/types.py @@ -0,0 +1,5 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT license. +"""Compatibility re-export for extension-owned OpenAI Responses models.""" + +from azure.ai.extensions.openai.responses._generated.sdk.models.types import * # type: ignore # noqa: F401,F403 diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_helpers.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_helpers.py index a09c06d47db3..a62dcff7c662 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_helpers.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/_helpers.py @@ -4,63 +4,60 @@ from __future__ import annotations -from typing import Any, Literal, Optional, cast +from typing import Any, Optional, cast -from ._generated import ( +from azure.ai.extensions.openai import get_field as _get_field +from azure.ai.extensions.openai import is_type as _is_wire_type +from azure.ai.extensions.openai import set_field as _set_field +from azure.ai.extensions.openai.responses import ( ConversationParam_2, CreateResponse, Item, ItemMessage, + ItemReferenceParam, MessageContent, MessageContentInputTextContent, MessageRole, OutputItem, ResponseObject, - ToolChoiceAllowed, - ToolChoiceOptions, ToolChoiceParam, ) -from ._generated.sdk.models._utils.model_base import _deserialize - -# --------------------------------------------------------------------------- -# Internal utilities for dict-safe field access -# --------------------------------------------------------------------------- -def _get_field(obj: Any, field: str, default: Any = None) -> Any: - """Get *field* from a model instance or a plain dict. - - :param obj: The model instance or dict to read from. - :type obj: Any - :param field: The field name to retrieve. - :type field: str - :param default: The default value if the field is missing. - :type default: Any - :returns: The field value, or *default*. - :rtype: Any - """ - if isinstance(obj, dict): - return obj.get(field, default) - return getattr(obj, field, default) - - -def _is_type(obj: Any, model_cls: type, type_value: str) -> bool: - """Check whether *obj* is *model_cls* or a dict with matching ``type``. +def _is_type(obj: Any, _model_cls: type, type_value: str) -> bool: + """Check whether *obj* has a matching wire ``type`` discriminator. :param obj: The object to check. :type obj: Any - :param model_cls: The model class to check against. + :param model_cls: Retained for call-site readability; ignored at runtime. :type model_cls: type :param type_value: The string type discriminator to match in dicts. :type type_value: str - :returns: True if *obj* matches the model class or type value. + :returns: True if *obj* matches the wire type value. :rtype: bool """ - if isinstance(obj, model_cls): - return True - if isinstance(obj, dict): - return obj.get("type") == type_value - return False + return _is_wire_type(obj, type_value) + + +def is_item_reference(item: Any) -> bool: + """Return whether *item* is an item reference payload. + + Item references are identified by OpenAI's typed ``item_reference`` shape, + or by the legacy id-only shorthand. + """ + if not isinstance(item, dict): + return False + if item.get("type") == "item_reference": + return "id" in item + return "id" in item and "type" not in item and "role" not in item and "content" not in item + + +def _ensure_item_type(data: dict[str, Any]) -> dict[str, Any]: + if "type" in data or is_item_reference(data): + return data + if "role" in data or "content" in data: + return {**data, "type": "message"} + return data # --------------------------------------------------------------------------- @@ -79,7 +76,7 @@ def get_conversation_id(request: CreateResponse | ResponseObject) -> Optional[st :returns: The conversation ID, or ``None`` if no conversation is set. :rtype: str | None """ - conv = request.conversation + conv = _get_field(request, "conversation") if conv is None: return None if isinstance(conv, str): @@ -103,33 +100,31 @@ def get_input_expanded(request: CreateResponse) -> list[Item]: :returns: A list of typed input items. :rtype: list[Item] """ - inp = request.input + inp = _get_field(request, "input") if inp is None: return [] if isinstance(inp, str): return [ - ItemMessage( - role=MessageRole.USER, - content=[MessageContentInputTextContent(text=inp)], - ) + { + "type": "message", + "role": MessageRole.USER, + "content": [{"type": "input_text", "text": inp}], + } ] # Normalize items: per the OpenAI spec, items without an explicit # ``type`` default to ``"message"`` (C-MSG-01 compliance). items: list[Item] = [] for raw in inp: - d = dict(raw) if isinstance(raw, dict) else raw - if isinstance(d, dict) and "type" not in d: - d = {**d, "type": "message"} - if isinstance(d, Item): - items.append(d) - else: - items.append(_deserialize(Item, d)) + item = raw + if isinstance(item, dict): + item = _ensure_item_type(item) + items.append(item) # Auto-expand string content on message items so downstream consumers # always see list[MessageContent] (matches .NET ExpandContent behaviour). for item in items: - if isinstance(item, ItemMessage) and isinstance(item.content, str): - item.content = get_content_expanded(item) + if _is_type(item, ItemMessage, "message") and isinstance(_get_field(item, "content"), str): + _set_field(item, "content", get_content_expanded(item)) return items @@ -169,23 +164,20 @@ def get_tool_choice_expanded(request: CreateResponse) -> Optional[ToolChoicePara :rtype: ToolChoiceParam | None :raises ValueError: If the tool_choice value is an unrecognized string. """ - tc = request.tool_choice + tc = _get_field(request, "tool_choice") if tc is None: return None - if isinstance(tc, ToolChoiceParam): + if isinstance(tc, dict) and "type" in tc: return tc if isinstance(tc, str): - normalized = tc if not isinstance(tc, ToolChoiceOptions) else tc.value + normalized = getattr(tc, "value", tc) if normalized in ("auto", "required"): - return ToolChoiceAllowed(mode=cast(Literal["auto", "required"], normalized), tools=[]) + return cast(ToolChoiceParam, {"type": "allowed_tools", "mode": normalized, "tools": []}) if normalized == "none": return None raise ValueError( f"Unrecognized tool_choice string value: '{normalized}'. Expected 'auto', 'required', or 'none'." ) - # dict fallback — wrap in ToolChoiceParam if it has a "type" key - if isinstance(tc, dict) and "type" in tc: - return ToolChoiceParam(tc) return None @@ -199,17 +191,13 @@ def get_conversation_expanded(request: CreateResponse) -> Optional[ConversationP :returns: The typed conversation parameter, or ``None``. :rtype: ConversationParam_2 | None """ - conv = request.conversation + conv = _get_field(request, "conversation") if conv is None: return None - if isinstance(conv, ConversationParam_2): + if isinstance(conv, dict) and conv.get("id"): return conv if isinstance(conv, str): - return ConversationParam_2(id=conv) if conv else None - # dict fallback - if isinstance(conv, dict): - cid = conv.get("id") - return ConversationParam_2(id=cid) if cid else None + return cast(ConversationParam_2, {"id": conv}) if conv else None return None @@ -231,19 +219,18 @@ def get_instruction_items(response: ResponseObject) -> list[Item]: :returns: A list of instruction items. :rtype: list[Item] """ - instr = response.instructions + instr = _get_field(response, "instructions") if instr is None: return [] if isinstance(instr, str): return [ - ItemMessage( - { - "id": "", - "status": "completed", - "role": MessageRole.DEVELOPER.value, - "content": [{"type": "input_text", "text": instr}], - } - ) + { + "id": "", + "status": "completed", + "type": "message", + "role": MessageRole.DEVELOPER.value, + "content": [{"type": "input_text", "text": instr}], + } ] return list(instr) @@ -256,9 +243,7 @@ def get_instruction_items(response: ResponseObject) -> list[Item]: def get_output_item_id(item: OutputItem) -> str: """Extract the ``id`` field from any :class:`OutputItem` subtype. - The base :class:`OutputItem` class does not define ``id``, but all - concrete subtypes do. Falls back to dict-style access for unknown - subtypes. + All concrete output item wire payloads must include an ``id`` field. :param item: The output item to extract the ID from. :type item: OutputItem @@ -270,14 +255,6 @@ def get_output_item_id(item: OutputItem) -> str: if item_id is not None: return str(item_id) - # Fallback: Model subclass supports Mapping protocol - try: - raw_id = item["id"] # type: ignore[index] - if raw_id is not None: - return str(raw_id) - except (KeyError, TypeError): - pass - raise ValueError( f"OutputItem of type '{type(item).__name__}' does not have a valid id. " "Ensure the id property is set before accessing it." @@ -306,7 +283,7 @@ def get_content_expanded(message: ItemMessage) -> list[MessageContent]: if content is None: return [] if isinstance(content, str): - return [MessageContentInputTextContent(text=content)] if content else [] + return cast(list[MessageContent], [{"type": "input_text", "text": content}]) if content else [] return list(content) @@ -366,11 +343,8 @@ def to_output_item(item: Item, response_id: str | None = None) -> OutputItem | N Returns ``None`` for :class:`ItemReferenceParam` or unrecognised types. - The conversion leverages ``_deserialize(OutputItem, data)`` which - resolves the correct subtype via the ``type`` discriminator. All 24 - input/output discriminator pairs share the same string values, so the - dict representation produced by ``dict(item)`` is directly compatible - with ``OutputItem`` deserialization. + The input/output discriminator pairs share the same string values, so the + item wire payload is directly compatible with the output item wire contract. :param item: The input item to convert. :type item: Item @@ -387,7 +361,7 @@ def to_output_item(item: Item, response_id: str | None = None) -> OutputItem | N if item_id is None: return None # ItemReferenceParam or unrecognised - data = dict(item) + data = _ensure_item_type(item.copy()) data["id"] = item_id item_type = data.get("type", "") @@ -398,16 +372,15 @@ def to_output_item(item: Item, response_id: str | None = None) -> OutputItem | N elif item_type in _PRESERVE_STATUS_ITEM_TYPES: pass # keep the original status from the input item - return _deserialize(OutputItem, data) + return cast(OutputItem, data) def to_item(output_item: OutputItem) -> Item | None: """Convert an :class:`OutputItem` back to the corresponding :class:`Item`. - Both hierarchies share the same ``type`` discriminator values, so - serialising an :class:`OutputItem` to a dict and deserializing as - :class:`Item` produces the correct concrete subtype (e.g. - :class:`OutputItemMessage` → :class:`ItemMessage`). + Both hierarchies share the same ``type`` discriminator values, so the + output item's wire dict is directly compatible with the input item contract + (e.g. ``OutputItemMessage`` → ``ItemMessage``). Returns ``None`` if the output item type has no :class:`Item` counterpart. @@ -416,8 +389,11 @@ def to_item(output_item: OutputItem) -> Item | None: :returns: The corresponding input item, or ``None``. :rtype: Item | None """ - try: - data = dict(output_item) - return _deserialize(Item, data) - except Exception: # pylint: disable=broad-except + if not isinstance(output_item, dict): + return None + if output_item.get("type") == "output_message": + return cast(Item, {**output_item, "type": "message"}) + item = _ensure_item_type(output_item.copy()) + if "type" not in item: return None + return cast(Item, item) diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/errors.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/errors.py index 31280a457768..e29c12db5f90 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/errors.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/errors.py @@ -6,7 +6,7 @@ from typing import Any -from azure.ai.agentserver.responses.models._generated import ApiErrorResponse, Error +from azure.ai.extensions.openai.responses import ApiErrorResponse, Error class RequestValidationError(ValueError): @@ -31,34 +31,42 @@ def __init__( self.details = details def to_error(self) -> Error: - """Convert this validation error to the generated ``Error`` model. + """Convert this validation error to an error wire payload. - :returns: An ``Error`` instance populated from this validation error's fields. + :returns: An error payload populated from this validation error's fields. :rtype: Error """ detail_errors: list[Error] | None = None if self.details: detail_errors = [ Error( - code=d.get("code", "invalid_value"), - message=d.get("message", ""), - param=d.get("param"), - type="invalid_request_error", + { + "code": d.get("code", "invalid_value"), + "message": d.get("message", ""), + "param": d.get("param"), + "type": "invalid_request_error", + } ) for d in self.details ] - return Error( - code=self.code, - message=self.message, - param=self.param, - type=self.error_type, - details=detail_errors, + error = Error( + { + "code": self.code, + "message": self.message, + "param": self.param, + "type": self.error_type, + } ) + if detail_errors is not None: + error["details"] = detail_errors + if self.debug_info is not None: + error["debug_info"] = self.debug_info + return error def to_api_error_response(self) -> ApiErrorResponse: - """Convert this validation error to the generated API error envelope. + """Convert this validation error to the API error envelope. - :returns: An ``ApiErrorResponse`` wrapping the generated ``Error``. + :returns: An ``ApiErrorResponse`` wrapping the error payload. :rtype: ApiErrorResponse """ return ApiErrorResponse(error=self.to_error()) diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/runtime.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/runtime.py index b5fe56b32387..0fcb365d131a 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/runtime.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/models/runtime.py @@ -9,7 +9,7 @@ from datetime import datetime, timezone from typing import TYPE_CHECKING, Any, Literal, Mapping, cast -from ._generated import AgentReference, OutputItem, ResponseObject, ResponseStreamEvent, ResponseStreamEventType +from azure.ai.extensions.openai.responses import AgentReference, OutputItem, ResponseStreamEvent, ResponseStreamEventType if TYPE_CHECKING: from .._response_context import ResponseContext @@ -58,17 +58,17 @@ def terminal(self) -> bool: } @classmethod - def from_generated(cls, event: ResponseStreamEvent, payload: Mapping[str, Any]) -> "StreamEventRecord": - """Create a stream event record from a generated response stream event model. + def from_event(cls, event: ResponseStreamEvent, payload: Mapping[str, Any]) -> "StreamEventRecord": + """Create a stream event record from a response stream wire payload. - :param event: The generated response stream event. + :param event: The response stream event payload. :type event: ResponseStreamEvent :param payload: The event payload mapping. :type payload: Mapping[str, Any] :returns: A new stream event record. :rtype: StreamEventRecord """ - return cls(sequence_number=event.sequence_number, event_type=event.type, payload=payload) + return cls(sequence_number=event["sequence_number"], event_type=event["type"], payload=payload) class ResponseExecution: # pylint: disable=too-many-instance-attributes @@ -87,7 +87,7 @@ def __init__( updated_at: datetime | None = None, completed_at: datetime | None = None, status: ResponseStatus = "in_progress", - response: ResponseObject | None = None, + response: dict[str, Any] | None = None, execution_task: asyncio.Task[Any] | None = None, cancel_requested: bool = False, client_disconnected: bool = False, @@ -170,7 +170,7 @@ def is_terminal(self) -> bool: """ return self.status in {"completed", "failed", "cancelled", "incomplete"} - def set_response_snapshot(self, response: ResponseObject) -> None: + def set_response_snapshot(self, response: dict[str, Any]) -> None: """Replace the current response snapshot from handler-emitted events. :param response: The latest response snapshot to store. @@ -211,7 +211,7 @@ def apply_event(self, normalized: ResponseStreamEvent, all_events: list[Response Does nothing if the execution is already ``"cancelled"``. - :param normalized: The normalised event (``ResponseStreamEvent`` model instance). + :param normalized: The normalised event wire payload. :type normalized: ResponseStreamEvent :param all_events: The full ordered list of handler events seen so far (used to extract the latest response snapshot). @@ -237,27 +237,25 @@ def apply_event(self, normalized: ResponseStreamEvent, all_events: list[Response agent_reference=agent_reference, model=model, ) - self.set_response_snapshot(ResponseObject(snapshot)) + self.set_response_snapshot(snapshot) resolved = snapshot.get("status") if isinstance(resolved, str): self.status = cast(ResponseStatus, resolved) elif event_type == ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_ADDED.value: item = normalized.get("item") if item is not None and self.response is not None: - item_dict = item.as_dict() if hasattr(item, "as_dict") else item - if isinstance(item_dict, dict): + if isinstance(item, dict): output = self.response.setdefault("output", []) if isinstance(output, list): - output.append(deepcopy(item_dict)) + output.append(deepcopy(item)) elif event_type == ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_DONE.value: item = normalized.get("item") output_index = normalized.get("output_index") if item is not None and isinstance(output_index, int) and self.response is not None: - item_dict = item.as_dict() if hasattr(item, "as_dict") else item - if isinstance(item_dict, dict): + if isinstance(item, dict): output = self.response.get("output", []) if isinstance(output, list) and 0 <= output_index < len(output): - output[output_index] = deepcopy(item_dict) + output[output_index] = deepcopy(item) @property def agent_reference(self) -> AgentReference | dict[str, Any]: @@ -325,7 +323,7 @@ def build_cancelled_response( agent_reference: AgentReference | dict[str, Any], model: str | None, created_at: datetime | None = None, -) -> ResponseObject: +) -> dict[str, Any]: """Build a Response object representing a cancelled terminal state. :param response_id: The response identifier. @@ -336,8 +334,8 @@ def build_cancelled_response( :type model: str | None :param created_at: Optional creation timestamp; defaults to now if omitted. :type created_at: datetime | None - :returns: A Response object with status ``"cancelled"`` and empty output. - :rtype: ResponseObject + :returns: A response wire payload with status ``"cancelled"`` and empty output. + :rtype: dict[str, Any] """ payload: dict[str, Any] = { "id": response_id, @@ -349,8 +347,8 @@ def build_cancelled_response( "output": [], } if created_at is not None: - payload["created_at"] = created_at.isoformat() - return ResponseObject(payload) + payload["created_at"] = int(created_at.timestamp()) + return payload def build_failed_response( @@ -360,8 +358,8 @@ def build_failed_response( created_at: datetime | None = None, error_message: str = "An internal server error occurred.", error_code: str = "server_error", -) -> ResponseObject: - """Build a ResponseObject representing a failed terminal state. +) -> dict[str, Any]: + """Build a response wire payload representing a failed terminal state. :param response_id: The response identifier. :type response_id: str @@ -375,8 +373,8 @@ def build_failed_response( :type error_message: str :param error_code: Error code string (e.g. ``"server_error"`` or ``"storage_error"``). :type error_code: str - :returns: A Response object with status ``"failed"`` and empty output. - :rtype: ResponseObject + :returns: A response wire payload with status ``"failed"`` and empty output. + :rtype: dict[str, Any] """ payload: dict[str, Any] = { "id": response_id, @@ -389,5 +387,5 @@ def build_failed_response( "error": {"code": error_code, "message": error_message}, } if created_at is not None: - payload["created_at"] = created_at.isoformat() - return ResponseObject(payload) + payload["created_at"] = int(created_at.timestamp()) + return payload diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/store/_base.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/store/_base.py index 92da541e2ea8..6b5594d28f88 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/store/_base.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/store/_base.py @@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, Iterable, Protocol, runtime_checkable -from ..models._generated import OutputItem, ResponseObject, ResponseStreamEvent +from azure.ai.extensions.openai.responses import OutputItem, ResponseObject, ResponseStreamEvent if TYPE_CHECKING: from .._response_context import PlatformContext @@ -35,7 +35,7 @@ async def create_response( """Persist a new response envelope and optional input/history references. :param response: The response envelope to persist. - :type response: ~azure.ai.agentserver.responses.models._generated.ResponseObject + :type response: ~azure.ai.extensions.openai.responses.ResponseObject :param input_items: Optional resolved output items to associate with the response. :type input_items: Iterable[OutputItem] | None :param history_item_ids: Optional history item IDs to link to the response. @@ -53,7 +53,7 @@ async def get_response(self, response_id: str, *, context: PlatformContext | Non :keyword context: Platform context for multi-tenant partitioning. :paramtype context: ~azure.ai.agentserver.responses.PlatformContext | None :returns: The response envelope matching the given ID. - :rtype: ~azure.ai.agentserver.responses.models._generated.ResponseObject + :rtype: ~azure.ai.extensions.openai.responses.ResponseObject :raises KeyError: If the response does not exist. """ ... @@ -62,7 +62,7 @@ async def update_response(self, response: ResponseObject, *, context: PlatformCo """Persist an updated response envelope. :param response: The response envelope with updated fields to persist. - :type response: ~azure.ai.agentserver.responses.models._generated.ResponseObject + :type response: ~azure.ai.extensions.openai.responses.ResponseObject :keyword context: Platform context for multi-tenant partitioning. :paramtype context: ~azure.ai.agentserver.responses.PlatformContext | None :rtype: None @@ -165,7 +165,7 @@ async def save_stream_events( """Persist the complete ordered list of SSE events for a response. Called once when the background+stream response reaches terminal state. - The *events* list contains ``ResponseStreamEvent`` model instances. + The *events* list contains ``ResponseStreamEvent`` wire payloads. :param response_id: The unique identifier of the response. :type response_id: str diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/store/_foundry_provider.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/store/_foundry_provider.py index 5ef23ccc9630..73e054ec5318 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/store/_foundry_provider.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/store/_foundry_provider.py @@ -14,9 +14,9 @@ from azure.core.pipeline import PipelineRequest, policies from azure.core.pipeline.policies import SansIOHTTPPolicy from azure.core.rest import HttpRequest +from azure.ai.extensions.openai.responses import OutputItem, ResponseObject from .._version import VERSION -from ..models._generated import OutputItem, ResponseObject # type: ignore[attr-defined] from ._foundry_errors import raise_for_storage_error from ._foundry_logging_policy import FoundryStorageLoggingPolicy from ._foundry_serializer import ( diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/store/_foundry_serializer.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/store/_foundry_serializer.py index e3aa4a381169..2019e0bb0fad 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/store/_foundry_serializer.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/store/_foundry_serializer.py @@ -7,7 +7,12 @@ import json from typing import Any, Iterable -from ..models._generated import OutputItem, ResponseObject # type: ignore[attr-defined] +from azure.ai.extensions.openai import to_wire_dict +from azure.ai.extensions.openai.responses import OutputItem, ResponseObject + + +def _to_dict(value: Any) -> dict[str, Any]: + return to_wire_dict(value) def serialize_create_request( @@ -27,22 +32,22 @@ def serialize_create_request( :rtype: bytes """ payload: dict[str, Any] = { - "response": response.as_dict(), - "input_items": [item.as_dict() for item in (input_items or [])], + "response": _to_dict(response), + "input_items": [_to_dict(item) for item in (input_items or [])], "history_item_ids": list(history_item_ids or []), } return json.dumps(payload).encode("utf-8") def serialize_response(response: ResponseObject) -> bytes: - """Serialize a single :class:`ResponseObject` snapshot to JSON bytes. + """Serialize a single :class:`ResponseObject` wire snapshot to JSON bytes. :param response: The response model to encode. :type response: ResponseObject :returns: UTF-8 encoded JSON body. :rtype: bytes """ - return json.dumps(response.as_dict()).encode("utf-8") + return json.dumps(_to_dict(response)).encode("utf-8") def serialize_batch_request(item_ids: list[str]) -> bytes: @@ -57,21 +62,20 @@ def serialize_batch_request(item_ids: list[str]) -> bytes: def deserialize_response(body: str) -> ResponseObject: - """Deserialize a JSON response body into a :class:`ResponseObject` model. + """Deserialize a JSON response body into a response wire payload. :param body: The raw JSON response text from the storage API. :type body: str - :returns: A populated :class:`ResponseObject` model. + :returns: A response wire payload. :rtype: ResponseObject """ - return ResponseObject(json.loads(body)) # type: ignore[call-arg] + return json.loads(body) def deserialize_paged_items(body: str) -> list[OutputItem]: """Deserialize a paged-response JSON body, extracting the ``data`` array. - The discriminator field ``type`` on each item determines the concrete - :class:`OutputItem` subclass returned. + Items are returned as dict-native ``OutputItem`` wire payloads. :param body: The raw JSON response text from the storage API. :type body: str @@ -79,7 +83,7 @@ def deserialize_paged_items(body: str) -> list[OutputItem]: :rtype: list[OutputItem] """ data = json.loads(body) - return [OutputItem._deserialize(item, []) for item in data.get("data", [])] # type: ignore[attr-defined] # pylint: disable=protected-access + return list(data.get("data", [])) def deserialize_items_array(body: str) -> list[OutputItem | None]: @@ -99,7 +103,7 @@ def deserialize_items_array(body: str) -> list[OutputItem | None]: if item is None: result.append(None) else: - result.append(OutputItem._deserialize(item, [])) # type: ignore[attr-defined] # pylint: disable=protected-access + result.append(item) # type: ignore[arg-type] return result diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/store/_memory.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/store/_memory.py index 8e8969922d6f..e4c8c5bd905b 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/store/_memory.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/store/_memory.py @@ -11,8 +11,10 @@ from datetime import datetime, timedelta, timezone from typing import Any, AsyncIterator, Dict, Iterable +from azure.ai.extensions.openai import get_field, to_wire_dict +from azure.ai.extensions.openai.responses import OutputItem, ResponseObject, ResponseStreamEvent + from .._response_context import PlatformContext -from ..models._generated import OutputItem, ResponseObject, ResponseStreamEvent from ..models._helpers import get_conversation_id from ..models.runtime import ResponseExecution, ResponseModeFlags, ResponseStatus, StreamEventRecord, StreamReplayState from ._base import ResponseProviderProtocol, ResponseStreamProviderProtocol @@ -84,7 +86,7 @@ async def create_response( and tracks conversation membership for history resolution. :param response: The response envelope to persist. - :type response: ~azure.ai.agentserver.responses.models._generated.Response + :type response: ~azure.ai.extensions.openai.responses.Response :param input_items: Optional resolved output items to associate with the response. :type input_items: Iterable[OutputItem] | None :param history_item_ids: Optional history item IDs to link to the response. @@ -94,7 +96,8 @@ async def create_response( :rtype: None :raises ValueError: If a non-deleted response with the same ID already exists. """ - response_id = str(getattr(response, "id")) + response_payload = to_wire_dict(response) + response_id = str(response_payload["id"]) async with self._locked(): entry = self._entries.get(response_id) if entry is not None and not entry.deleted: @@ -110,21 +113,21 @@ async def create_response( input_ids.append(item_id) history_ids = list(history_item_ids) if history_item_ids is not None else [] - output_ids = self._store_output_items_unlocked(response) + output_ids = self._store_output_items_unlocked(response_payload) self._entries[response_id] = _StoreEntry( execution=ResponseExecution( response_id=response_id, - mode_flags=self._resolve_mode_flags_from_response(response), + mode_flags=self._resolve_mode_flags_from_response(response_payload), ), replay=StreamReplayState(response_id=response_id), - response=deepcopy(response), + response=deepcopy(response_payload), input_item_ids=input_ids, output_item_ids=output_ids, history_item_ids=history_ids, deleted=False, ) - conversation_id = get_conversation_id(response) + conversation_id = get_conversation_id(response_payload) if conversation_id is not None: self._conversation_responses[conversation_id].append(response_id) @@ -136,7 +139,7 @@ async def get_response(self, response_id: str, *, context: PlatformContext | Non :keyword context: Platform context for multi-tenant partitioning. :paramtype context: ~azure.ai.agentserver.responses.PlatformContext | None :returns: A deep copy of the stored response envelope. - :rtype: ~azure.ai.agentserver.responses.models._generated.Response + :rtype: ~azure.ai.extensions.openai.responses.Response :raises KeyError: If the response does not exist or has been deleted. """ async with self._locked(): @@ -152,21 +155,22 @@ async def update_response(self, response: ResponseObject, *, context: PlatformCo the execution snapshot. :param response: The response envelope with updated fields. - :type response: ~azure.ai.agentserver.responses.models._generated.Response + :type response: ~azure.ai.extensions.openai.responses.Response :keyword context: Platform context for multi-tenant partitioning. :paramtype context: ~azure.ai.agentserver.responses.PlatformContext | None :rtype: None :raises KeyError: If the response does not exist or has been deleted. """ - response_id = str(getattr(response, "id")) + response_payload = to_wire_dict(response) + response_id = str(response_payload["id"]) async with self._locked(): entry = self._entries.get(response_id) if entry is None or entry.deleted: raise KeyError(f"response '{response_id}' not found") - entry.response = deepcopy(response) - entry.execution.set_response_snapshot(deepcopy(response)) - entry.output_item_ids = self._store_output_items_unlocked(response) + entry.response = deepcopy(response_payload) + entry.execution.set_response_snapshot(deepcopy(response_payload)) + entry.output_item_ids = self._store_output_items_unlocked(response_payload) async def delete_response(self, response_id: str, *, context: PlatformContext | None = None) -> None: """Delete a stored response envelope by identifier. @@ -366,7 +370,7 @@ async def set_response_snapshot( :param response_id: The unique identifier of the response to update. :type response_id: str :param response: The response snapshot to associate with the execution. - :type response: ~azure.ai.agentserver.responses.models._generated.Response + :type response: ~azure.ai.extensions.openai.responses.Response :keyword int or None ttl_seconds: Optional time-to-live in seconds to refresh expiration. :returns: ``True`` if the entry was found and updated, ``False`` otherwise. :rtype: bool @@ -376,7 +380,7 @@ async def set_response_snapshot( if entry is None: return False - entry.execution.set_response_snapshot(response) + entry.execution.set_response_snapshot(to_wire_dict(response)) self._apply_ttl_unlocked(entry, ttl_seconds) return True @@ -665,11 +669,11 @@ def _store_output_items_unlocked(self, response: ResponseObject) -> list[str]: Must be called while holding ``self._lock``. :param response: The response envelope whose output items should be stored. - :type response: ~azure.ai.agentserver.responses.models._generated.Response + :type response: ~azure.ai.extensions.openai.responses.Response :returns: Ordered list of output item IDs. :rtype: list[str] """ - output = getattr(response, "output", None) + output = get_field(response, "output") if not output: return [] output_ids: list[str] = [] @@ -705,12 +709,12 @@ def _resolve_mode_flags_from_response(response: ResponseObject) -> ResponseModeF """Build mode flags from a response snapshot where available. :param response: The response envelope to extract mode flags from. - :type response: ~azure.ai.agentserver.responses.models._generated.Response + :type response: ~azure.ai.extensions.openai.responses.Response :returns: Mode flags derived from the response's ``stream``, ``store``, and ``background`` attributes. :rtype: ~azure.ai.agentserver.responses.models.runtime.ResponseModeFlags """ return ResponseModeFlags( - stream=bool(getattr(response, "stream", False)), - store=bool(getattr(response, "store", True)), - background=bool(getattr(response, "background", False)), + stream=bool(get_field(response, "stream", False)), + store=bool(get_field(response, "store", True)), + background=bool(get_field(response, "background", False)), ) diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_base.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_base.py index 770e497441c4..04f13fb2e2d3 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_base.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_base.py @@ -8,7 +8,9 @@ from enum import Enum from typing import TYPE_CHECKING, Any, cast -from ...models import _generated as generated_models +from azure.ai.extensions.openai import to_wire_dict + +from azure.ai.extensions.openai import responses as response_models if TYPE_CHECKING: from .._event_stream import ResponseEventStream @@ -90,7 +92,7 @@ def _ensure_transition(self, expected: BuilderLifecycleState, new_state: Builder ) self._lifecycle_state = new_state - def _emit_added(self, item: dict[str, Any]) -> generated_models.ResponseOutputItemAddedEvent: + def _emit_added(self, item: dict[str, Any]) -> response_models.ResponseOutputItemAddedEvent: """Emit an ``output_item.added`` event with lifecycle guard. :param item: The output item dict to include in the event. @@ -102,17 +104,17 @@ def _emit_added(self, item: dict[str, Any]) -> generated_models.ResponseOutputIt self._ensure_transition(BuilderLifecycleState.NOT_STARTED, BuilderLifecycleState.ADDED) stamped_item = self._stream._with_output_item_defaults(item) # pylint: disable=protected-access return cast( - generated_models.ResponseOutputItemAddedEvent, + response_models.ResponseOutputItemAddedEvent, self._stream._emit_event( # pylint: disable=protected-access { - "type": generated_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_ADDED.value, + "type": response_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_ADDED.value, "output_index": self._output_index, "item": stamped_item, } ), ) - def _emit_done(self, item: dict[str, Any]) -> generated_models.ResponseOutputItemDoneEvent: + def _emit_done(self, item: dict[str, Any]) -> response_models.ResponseOutputItemDoneEvent: """Emit an ``output_item.done`` event with lifecycle guard. :param item: The completed output item dict to include in the event. @@ -124,10 +126,10 @@ def _emit_done(self, item: dict[str, Any]) -> generated_models.ResponseOutputIte self._ensure_transition(BuilderLifecycleState.ADDED, BuilderLifecycleState.DONE) stamped_item = self._stream._with_output_item_defaults(item) # pylint: disable=protected-access return cast( - generated_models.ResponseOutputItemDoneEvent, + response_models.ResponseOutputItemDoneEvent, self._stream._emit_event( # pylint: disable=protected-access { - "type": generated_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_DONE.value, + "type": response_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_DONE.value, "output_index": self._output_index, "item": stamped_item, } @@ -136,7 +138,7 @@ def _emit_done(self, item: dict[str, Any]) -> generated_models.ResponseOutputIte def _emit_item_state_event( self, event_type: str, *, extra_payload: dict[str, Any] | None = None - ) -> generated_models.ResponseStreamEvent: + ) -> response_models.ResponseStreamEvent: """Emit an item-level state event (e.g., in-progress, searching, completed). :param event_type: The event type string. @@ -159,7 +161,7 @@ def _emit_item_state_event( class OutputItemBuilder(BaseOutputItemBuilder): """Generic output-item builder for item types without dedicated scoped builders.""" - def emit_added(self, item: generated_models.OutputItem) -> generated_models.ResponseOutputItemAddedEvent: + def emit_added(self, item: response_models.OutputItem) -> response_models.ResponseOutputItemAddedEvent: """Emit an ``output_item.added`` event for a generic item. :param item: The output item model instance. @@ -167,9 +169,9 @@ def emit_added(self, item: generated_models.OutputItem) -> generated_models.Resp :returns: The emitted event. :rtype: ResponseOutputItemAddedEvent """ - return self._emit_added(item.as_dict()) + return self._emit_added(to_wire_dict(item)) - def emit_done(self, item: generated_models.OutputItem) -> generated_models.ResponseOutputItemDoneEvent: + def emit_done(self, item: response_models.OutputItem) -> response_models.ResponseOutputItemDoneEvent: """Emit an ``output_item.done`` event for a generic item. :param item: The completed output item model instance. @@ -177,4 +179,4 @@ def emit_done(self, item: generated_models.OutputItem) -> generated_models.Respo :returns: The emitted event. :rtype: ResponseOutputItemDoneEvent """ - return self._emit_done(item.as_dict()) + return self._emit_done(to_wire_dict(item)) diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_function.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_function.py index 795f92d174df..875a4cdad4bc 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_function.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_function.py @@ -8,7 +8,7 @@ from copy import deepcopy from typing import TYPE_CHECKING, AsyncIterator, Iterator, cast -from ...models import _generated as generated_models +from azure.ai.extensions.openai import responses as response_models from ._base import BaseOutputItemBuilder, _require_non_empty if TYPE_CHECKING: @@ -62,7 +62,7 @@ def call_id(self) -> str: """ return self._call_id - def emit_added(self) -> generated_models.ResponseOutputItemAddedEvent: + def emit_added(self) -> response_models.ResponseOutputItemAddedEvent: """Emit an ``output_item.added`` event for this function call. :returns: The emitted event. @@ -79,7 +79,7 @@ def emit_added(self) -> generated_models.ResponseOutputItemAddedEvent: } ) - def emit_arguments_delta(self, delta: str) -> generated_models.ResponseFunctionCallArgumentsDeltaEvent: + def emit_arguments_delta(self, delta: str) -> response_models.ResponseFunctionCallArgumentsDeltaEvent: """Emit a function-call arguments delta event. :param delta: The incremental arguments text fragment. @@ -88,10 +88,10 @@ def emit_arguments_delta(self, delta: str) -> generated_models.ResponseFunctionC :rtype: ResponseFunctionCallArgumentsDeltaEvent """ return cast( - generated_models.ResponseFunctionCallArgumentsDeltaEvent, + response_models.ResponseFunctionCallArgumentsDeltaEvent, self._stream._emit_event( # pylint: disable=protected-access { - "type": generated_models.ResponseStreamEventType.RESPONSE_FUNCTION_CALL_ARGUMENTS_DELTA.value, + "type": response_models.ResponseStreamEventType.RESPONSE_FUNCTION_CALL_ARGUMENTS_DELTA.value, "item_id": self._item_id, "output_index": self._output_index, "delta": delta, @@ -99,7 +99,7 @@ def emit_arguments_delta(self, delta: str) -> generated_models.ResponseFunctionC ), ) - def emit_arguments_done(self, arguments: str) -> generated_models.ResponseFunctionCallArgumentsDoneEvent: + def emit_arguments_done(self, arguments: str) -> response_models.ResponseFunctionCallArgumentsDoneEvent: """Emit a function-call arguments done event. :param arguments: The final, complete arguments string. @@ -109,10 +109,10 @@ def emit_arguments_done(self, arguments: str) -> generated_models.ResponseFuncti """ self._final_arguments = arguments return cast( - generated_models.ResponseFunctionCallArgumentsDoneEvent, + response_models.ResponseFunctionCallArgumentsDoneEvent, self._stream._emit_event( # pylint: disable=protected-access { - "type": generated_models.ResponseStreamEventType.RESPONSE_FUNCTION_CALL_ARGUMENTS_DONE.value, + "type": response_models.ResponseStreamEventType.RESPONSE_FUNCTION_CALL_ARGUMENTS_DONE.value, "item_id": self._item_id, "output_index": self._output_index, "name": self._name, @@ -121,7 +121,7 @@ def emit_arguments_done(self, arguments: str) -> generated_models.ResponseFuncti ), ) - def emit_done(self) -> generated_models.ResponseOutputItemDoneEvent: + def emit_done(self) -> response_models.ResponseOutputItemDoneEvent: """Emit an ``output_item.done`` event for this function call. :returns: The emitted event. @@ -140,7 +140,7 @@ def emit_done(self) -> generated_models.ResponseOutputItemDoneEvent: # ---- Sub-item convenience generators (S-053) ---- - def arguments(self, args: str) -> Iterator[generated_models.ResponseStreamEvent]: + def arguments(self, args: str) -> Iterator[response_models.ResponseStreamEvent]: """Yield the argument delta and done events. Emits ``function_call_arguments.delta`` followed by @@ -154,7 +154,7 @@ def arguments(self, args: str) -> Iterator[generated_models.ResponseStreamEvent] yield self.emit_arguments_delta(args) yield self.emit_arguments_done(args) - async def aarguments(self, args: str | AsyncIterable[str]) -> AsyncIterator[generated_models.ResponseStreamEvent]: + async def aarguments(self, args: str | AsyncIterable[str]) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`arguments` with streaming support. When *args* is a string, behaves identically to :meth:`arguments`. @@ -204,9 +204,9 @@ def __init__( self._final_output: ( str | list[ - generated_models.InputTextContentParam - | generated_models.InputImageContentParamAutoParam - | generated_models.InputFileContentParam + response_models.InputTextContentParam + | response_models.InputImageContentParamAutoParam + | response_models.InputFileContentParam ] | None ) = None @@ -224,12 +224,12 @@ def emit_added( self, output: str | list[ - generated_models.InputTextContentParam - | generated_models.InputImageContentParamAutoParam - | generated_models.InputFileContentParam + response_models.InputTextContentParam + | response_models.InputImageContentParamAutoParam + | response_models.InputFileContentParam ] | None = None, - ) -> generated_models.ResponseOutputItemAddedEvent: + ) -> response_models.ResponseOutputItemAddedEvent: """Emit an ``output_item.added`` event for this function-call output. :param output: Optional initial output value. @@ -251,12 +251,12 @@ def emit_done( self, output: str | list[ - generated_models.InputTextContentParam - | generated_models.InputImageContentParamAutoParam - | generated_models.InputFileContentParam + response_models.InputTextContentParam + | response_models.InputImageContentParamAutoParam + | response_models.InputFileContentParam ] | None = None, - ) -> generated_models.ResponseOutputItemDoneEvent: + ) -> response_models.ResponseOutputItemDoneEvent: """Emit an ``output_item.done`` event for this function-call output. :param output: Optional final output value. Uses previously set output if ``None``. diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_message.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_message.py index ab02b2875af3..d6fbc337d426 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_message.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_message.py @@ -8,7 +8,9 @@ from copy import deepcopy from typing import TYPE_CHECKING, Any, AsyncIterator, Iterator, cast -from ...models import _generated as generated_models +from azure.ai.extensions.openai import to_wire_dict + +from azure.ai.extensions.openai import responses as response_models from ._base import BaseOutputItemBuilder, BuilderLifecycleState if TYPE_CHECKING: @@ -62,7 +64,7 @@ def content_index(self) -> int: """ return self._content_index - def emit_added(self) -> generated_models.ResponseContentPartAddedEvent: + def emit_added(self) -> response_models.ResponseContentPartAddedEvent: """Emit a ``content_part.added`` event for this text content. :returns: The emitted event dict. @@ -73,10 +75,10 @@ def emit_added(self) -> generated_models.ResponseContentPartAddedEvent: raise ValueError(f"cannot call emit_added in '{self._lifecycle_state.value}' state") self._lifecycle_state = BuilderLifecycleState.ADDED return cast( - generated_models.ResponseContentPartAddedEvent, + response_models.ResponseContentPartAddedEvent, self._stream._emit_event( # pylint: disable=protected-access { - "type": generated_models.ResponseStreamEventType.RESPONSE_CONTENT_PART_ADDED.value, + "type": response_models.ResponseStreamEventType.RESPONSE_CONTENT_PART_ADDED.value, "item_id": self._item_id, "output_index": self._output_index, "content_index": self._content_index, @@ -85,15 +87,15 @@ def emit_added(self) -> generated_models.ResponseContentPartAddedEvent: ), ) - def emit_delta(self, text: str) -> generated_models.ResponseTextDeltaEvent: + def emit_delta(self, text: str) -> response_models.ResponseTextDeltaEvent: if self._lifecycle_state is not BuilderLifecycleState.ADDED: raise ValueError(f"cannot call emit_delta in '{self._lifecycle_state.value}' state") self._delta_fragments.append(text) return cast( - generated_models.ResponseTextDeltaEvent, + response_models.ResponseTextDeltaEvent, self._stream._emit_event( # pylint: disable=protected-access { - "type": generated_models.ResponseStreamEventType.RESPONSE_OUTPUT_TEXT_DELTA.value, + "type": response_models.ResponseStreamEventType.RESPONSE_OUTPUT_TEXT_DELTA.value, "item_id": self._item_id, "output_index": self._output_index, "content_index": self._content_index, @@ -103,7 +105,7 @@ def emit_delta(self, text: str) -> generated_models.ResponseTextDeltaEvent: ), ) - def emit_text_done(self, final_text: str | None = None) -> generated_models.ResponseTextDoneEvent: + def emit_text_done(self, final_text: str | None = None) -> response_models.ResponseTextDoneEvent: """Emit an ``output_text.done`` event with the merged final text. Call this after all deltas have been emitted. After this, you may @@ -125,10 +127,10 @@ def emit_text_done(self, final_text: str | None = None) -> generated_models.Resp merged_text = final_text self._final_text = merged_text return cast( - generated_models.ResponseTextDoneEvent, + response_models.ResponseTextDoneEvent, self._stream._emit_event( # pylint: disable=protected-access { - "type": generated_models.ResponseStreamEventType.RESPONSE_OUTPUT_TEXT_DONE.value, + "type": response_models.ResponseStreamEventType.RESPONSE_OUTPUT_TEXT_DONE.value, "item_id": self._item_id, "output_index": self._output_index, "content_index": self._content_index, @@ -138,7 +140,7 @@ def emit_text_done(self, final_text: str | None = None) -> generated_models.Resp ), ) - def emit_done(self) -> generated_models.ResponseContentPartDoneEvent: + def emit_done(self) -> response_models.ResponseContentPartDoneEvent: """Emit a ``content_part.done`` event, closing this content part. Must be called after ``emit_text_done()``. @@ -153,10 +155,10 @@ def emit_done(self) -> generated_models.ResponseContentPartDoneEvent: raise ValueError("must call emit_text_done() before emit_done()") self._lifecycle_state = BuilderLifecycleState.DONE return cast( - generated_models.ResponseContentPartDoneEvent, + response_models.ResponseContentPartDoneEvent, self._stream._emit_event( # pylint: disable=protected-access { - "type": generated_models.ResponseStreamEventType.RESPONSE_CONTENT_PART_DONE.value, + "type": response_models.ResponseStreamEventType.RESPONSE_CONTENT_PART_DONE.value, "item_id": self._item_id, "output_index": self._output_index, "content_index": self._content_index, @@ -171,8 +173,8 @@ def emit_done(self) -> generated_models.ResponseContentPartDoneEvent: ) def emit_annotation_added( - self, annotation: generated_models.Annotation - ) -> generated_models.ResponseOutputTextAnnotationAddedEvent: + self, annotation: response_models.Annotation + ) -> response_models.ResponseOutputTextAnnotationAddedEvent: """Emit a text annotation added event. :param annotation: The annotation to attach—a typed @@ -183,12 +185,12 @@ def emit_annotation_added( """ annotation_index = self._annotation_index self._annotation_index += 1 - annotation_payload = deepcopy(annotation.as_dict()) + annotation_payload = to_wire_dict(annotation) return cast( - generated_models.ResponseOutputTextAnnotationAddedEvent, + response_models.ResponseOutputTextAnnotationAddedEvent, self._stream._emit_event( # pylint: disable=protected-access { - "type": generated_models.ResponseStreamEventType.RESPONSE_OUTPUT_TEXT_ANNOTATION_ADDED.value, + "type": response_models.ResponseStreamEventType.RESPONSE_OUTPUT_TEXT_ANNOTATION_ADDED.value, "item_id": self._item_id, "output_index": self._output_index, "content_index": self._content_index, @@ -244,7 +246,7 @@ def content_index(self) -> int: """ return self._content_index - def emit_added(self) -> generated_models.ResponseContentPartAddedEvent: + def emit_added(self) -> response_models.ResponseContentPartAddedEvent: """Emit a ``content_part.added`` event for this refusal content. :returns: The emitted event dict. @@ -255,10 +257,10 @@ def emit_added(self) -> generated_models.ResponseContentPartAddedEvent: raise ValueError(f"cannot call emit_added in '{self._lifecycle_state.value}' state") self._lifecycle_state = BuilderLifecycleState.ADDED return cast( - generated_models.ResponseContentPartAddedEvent, + response_models.ResponseContentPartAddedEvent, self._stream._emit_event( # pylint: disable=protected-access { - "type": generated_models.ResponseStreamEventType.RESPONSE_CONTENT_PART_ADDED.value, + "type": response_models.ResponseStreamEventType.RESPONSE_CONTENT_PART_ADDED.value, "item_id": self._item_id, "output_index": self._output_index, "content_index": self._content_index, @@ -267,7 +269,7 @@ def emit_added(self) -> generated_models.ResponseContentPartAddedEvent: ), ) - def emit_delta(self, text: str) -> generated_models.ResponseRefusalDeltaEvent: + def emit_delta(self, text: str) -> response_models.ResponseRefusalDeltaEvent: """Emit a refusal delta event. :param text: The incremental refusal text fragment. @@ -276,10 +278,10 @@ def emit_delta(self, text: str) -> generated_models.ResponseRefusalDeltaEvent: :rtype: ResponseRefusalDeltaEvent """ return cast( - generated_models.ResponseRefusalDeltaEvent, + response_models.ResponseRefusalDeltaEvent, self._stream._emit_event( # pylint: disable=protected-access { - "type": generated_models.ResponseStreamEventType.RESPONSE_REFUSAL_DELTA.value, + "type": response_models.ResponseStreamEventType.RESPONSE_REFUSAL_DELTA.value, "item_id": self._item_id, "output_index": self._output_index, "content_index": self._content_index, @@ -288,7 +290,7 @@ def emit_delta(self, text: str) -> generated_models.ResponseRefusalDeltaEvent: ), ) - def emit_refusal_done(self, final_refusal: str) -> generated_models.ResponseRefusalDoneEvent: + def emit_refusal_done(self, final_refusal: str) -> response_models.ResponseRefusalDoneEvent: """Emit a ``refusal.done`` event. Call this after all deltas have been emitted and before ``emit_done()``. @@ -306,10 +308,10 @@ def emit_refusal_done(self, final_refusal: str) -> generated_models.ResponseRefu self._refusal_done = True self._final_refusal = final_refusal return cast( - generated_models.ResponseRefusalDoneEvent, + response_models.ResponseRefusalDoneEvent, self._stream._emit_event( # pylint: disable=protected-access { - "type": generated_models.ResponseStreamEventType.RESPONSE_REFUSAL_DONE.value, + "type": response_models.ResponseStreamEventType.RESPONSE_REFUSAL_DONE.value, "item_id": self._item_id, "output_index": self._output_index, "content_index": self._content_index, @@ -318,7 +320,7 @@ def emit_refusal_done(self, final_refusal: str) -> generated_models.ResponseRefu ), ) - def emit_done(self) -> generated_models.ResponseContentPartDoneEvent: + def emit_done(self) -> response_models.ResponseContentPartDoneEvent: """Emit a ``content_part.done`` event, closing this content part. Must be called after ``emit_refusal_done()``. @@ -333,10 +335,10 @@ def emit_done(self) -> generated_models.ResponseContentPartDoneEvent: raise ValueError("must call emit_refusal_done() before emit_done()") self._lifecycle_state = BuilderLifecycleState.DONE return cast( - generated_models.ResponseContentPartDoneEvent, + response_models.ResponseContentPartDoneEvent, self._stream._emit_event( # pylint: disable=protected-access { - "type": generated_models.ResponseStreamEventType.RESPONSE_CONTENT_PART_DONE.value, + "type": response_models.ResponseStreamEventType.RESPONSE_CONTENT_PART_DONE.value, "item_id": self._item_id, "output_index": self._output_index, "content_index": self._content_index, @@ -371,7 +373,7 @@ def __init__( self._content_index = 0 self._content_builders: list[TextContentBuilder | RefusalContentBuilder] = [] - def emit_added(self) -> generated_models.ResponseOutputItemAddedEvent: + def emit_added(self) -> response_models.ResponseOutputItemAddedEvent: """Emit an ``output_item.added`` event for this message item. :returns: The emitted event dict. @@ -421,7 +423,7 @@ def add_refusal_content(self) -> RefusalContentBuilder: self._content_builders.append(rc) return rc - def emit_done(self) -> generated_models.ResponseOutputItemDoneEvent: + def emit_done(self) -> response_models.ResponseOutputItemDoneEvent: """Emit an ``output_item.done`` event for this message item. Builds the content list from the tracked child content builders. @@ -462,7 +464,7 @@ def emit_done(self) -> generated_models.ResponseOutputItemDoneEvent: # ---- Sub-item convenience generators (S-053) ---- - def text_content(self, text: str) -> Iterator[generated_models.ResponseStreamEvent]: + def text_content(self, text: str) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for a text content part. Creates the sub-builder, emits ``content_part.added``, @@ -481,7 +483,7 @@ def text_content(self, text: str) -> Iterator[generated_models.ResponseStreamEve async def atext_content( self, text: str | AsyncIterable[str] - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`text_content` with streaming support. When *text* is a string, behaves identically to :meth:`text_content`. @@ -505,7 +507,7 @@ async def atext_content( yield tc.emit_text_done() yield tc.emit_done() - def refusal_content(self, text: str) -> Iterator[generated_models.ResponseStreamEvent]: + def refusal_content(self, text: str) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for a refusal content part. Creates the sub-builder, emits ``content_part.added``, @@ -524,7 +526,7 @@ def refusal_content(self, text: str) -> Iterator[generated_models.ResponseStream async def arefusal_content( self, text: str | AsyncIterable[str] - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`refusal_content` with streaming support. When *text* is a string, behaves identically to :meth:`refusal_content`. diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_reasoning.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_reasoning.py index f3392208e264..d93f64550742 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_reasoning.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_reasoning.py @@ -7,7 +7,7 @@ from collections.abc import AsyncIterable from typing import TYPE_CHECKING, AsyncIterator, Iterator, cast -from ...models import _generated as generated_models +from azure.ai.extensions.openai import responses as response_models from ._base import BaseOutputItemBuilder, BuilderLifecycleState if TYPE_CHECKING: @@ -54,7 +54,7 @@ def summary_index(self) -> int: """ return self._summary_index - def emit_added(self) -> generated_models.ResponseReasoningSummaryPartAddedEvent: + def emit_added(self) -> response_models.ResponseReasoningSummaryPartAddedEvent: """Emit a ``reasoning_summary_part.added`` event. :returns: The emitted event. @@ -65,10 +65,10 @@ def emit_added(self) -> generated_models.ResponseReasoningSummaryPartAddedEvent: raise ValueError(f"cannot call emit_added in '{self._lifecycle_state.value}' state") self._lifecycle_state = BuilderLifecycleState.ADDED return cast( - generated_models.ResponseReasoningSummaryPartAddedEvent, + response_models.ResponseReasoningSummaryPartAddedEvent, self._stream._emit_event( # pylint: disable=protected-access { - "type": generated_models.ResponseStreamEventType.RESPONSE_REASONING_SUMMARY_PART_ADDED.value, + "type": response_models.ResponseStreamEventType.RESPONSE_REASONING_SUMMARY_PART_ADDED.value, "item_id": self._item_id, "output_index": self._output_index, "summary_index": self._summary_index, @@ -77,7 +77,7 @@ def emit_added(self) -> generated_models.ResponseReasoningSummaryPartAddedEvent: ), ) - def emit_text_delta(self, text: str) -> generated_models.ResponseReasoningSummaryTextDeltaEvent: + def emit_text_delta(self, text: str) -> response_models.ResponseReasoningSummaryTextDeltaEvent: """Emit a reasoning summary text delta event. :param text: The incremental summary text fragment. @@ -86,10 +86,10 @@ def emit_text_delta(self, text: str) -> generated_models.ResponseReasoningSummar :rtype: ResponseReasoningSummaryTextDeltaEvent """ return cast( - generated_models.ResponseReasoningSummaryTextDeltaEvent, + response_models.ResponseReasoningSummaryTextDeltaEvent, self._stream._emit_event( # pylint: disable=protected-access { - "type": generated_models.ResponseStreamEventType.RESPONSE_REASONING_SUMMARY_TEXT_DELTA.value, + "type": response_models.ResponseStreamEventType.RESPONSE_REASONING_SUMMARY_TEXT_DELTA.value, "item_id": self._item_id, "output_index": self._output_index, "summary_index": self._summary_index, @@ -98,7 +98,7 @@ def emit_text_delta(self, text: str) -> generated_models.ResponseReasoningSummar ), ) - def emit_text_done(self, final_text: str) -> generated_models.ResponseReasoningSummaryTextDoneEvent: + def emit_text_done(self, final_text: str) -> response_models.ResponseReasoningSummaryTextDoneEvent: """Emit a reasoning summary text done event. :param final_text: The final, complete summary text. @@ -108,10 +108,10 @@ def emit_text_done(self, final_text: str) -> generated_models.ResponseReasoningS """ self._final_text = final_text return cast( - generated_models.ResponseReasoningSummaryTextDoneEvent, + response_models.ResponseReasoningSummaryTextDoneEvent, self._stream._emit_event( # pylint: disable=protected-access { - "type": generated_models.ResponseStreamEventType.RESPONSE_REASONING_SUMMARY_TEXT_DONE.value, + "type": response_models.ResponseStreamEventType.RESPONSE_REASONING_SUMMARY_TEXT_DONE.value, "item_id": self._item_id, "output_index": self._output_index, "summary_index": self._summary_index, @@ -120,7 +120,7 @@ def emit_text_done(self, final_text: str) -> generated_models.ResponseReasoningS ), ) - def emit_done(self) -> generated_models.ResponseReasoningSummaryPartDoneEvent: + def emit_done(self) -> response_models.ResponseReasoningSummaryPartDoneEvent: """Emit a ``reasoning_summary_part.done`` event. :returns: The emitted event. @@ -131,10 +131,10 @@ def emit_done(self) -> generated_models.ResponseReasoningSummaryPartDoneEvent: raise ValueError(f"cannot call emit_done in '{self._lifecycle_state.value}' state") self._lifecycle_state = BuilderLifecycleState.DONE return cast( - generated_models.ResponseReasoningSummaryPartDoneEvent, + response_models.ResponseReasoningSummaryPartDoneEvent, self._stream._emit_event( # pylint: disable=protected-access { - "type": generated_models.ResponseStreamEventType.RESPONSE_REASONING_SUMMARY_PART_DONE.value, + "type": response_models.ResponseStreamEventType.RESPONSE_REASONING_SUMMARY_PART_DONE.value, "item_id": self._item_id, "output_index": self._output_index, "summary_index": self._summary_index, @@ -161,7 +161,7 @@ def __init__(self, stream: "ResponseEventStream", output_index: int, item_id: st self._summary_index = 0 self._summary_builders: list[ReasoningSummaryPartBuilder] = [] - def emit_added(self) -> generated_models.ResponseOutputItemAddedEvent: + def emit_added(self) -> response_models.ResponseOutputItemAddedEvent: """Emit an ``output_item.added`` event for this reasoning item. :returns: The emitted event. @@ -181,7 +181,7 @@ def add_summary_part(self) -> ReasoningSummaryPartBuilder: self._summary_builders.append(part) return part - def emit_done(self) -> generated_models.ResponseOutputItemDoneEvent: + def emit_done(self) -> response_models.ResponseOutputItemDoneEvent: """Emit an ``output_item.done`` event for this reasoning item. :returns: The emitted event. @@ -199,7 +199,7 @@ def emit_done(self) -> generated_models.ResponseOutputItemDoneEvent: # ---- Sub-item convenience generators (S-053) ---- - def summary_part(self, text: str) -> Iterator[generated_models.ResponseStreamEvent]: + def summary_part(self, text: str) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for a reasoning summary part. Creates the sub-builder, emits ``reasoning_summary_part.added``, @@ -220,7 +220,7 @@ def summary_part(self, text: str) -> Iterator[generated_models.ResponseStreamEve async def asummary_part( self, text: str | AsyncIterable[str], - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`summary_part` with streaming support. When *text* is a string, behaves identically to :meth:`summary_part`. diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_tools.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_tools.py index 66bac939d386..51a081d38837 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_tools.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_builders/_tools.py @@ -7,7 +7,7 @@ from collections.abc import AsyncIterable from typing import TYPE_CHECKING, Any, AsyncIterator, Iterator, cast -from ...models import _generated as generated_models +from azure.ai.extensions.openai import responses as response_models from ._base import BaseOutputItemBuilder, _require_non_empty if TYPE_CHECKING: @@ -17,7 +17,7 @@ class OutputItemFileSearchCallBuilder(BaseOutputItemBuilder): """Scoped builder for file search tool call events.""" - def emit_added(self) -> generated_models.ResponseOutputItemAddedEvent: + def emit_added(self) -> response_models.ResponseOutputItemAddedEvent: """Emit an ``output_item.added`` event for a file search call. :returns: The emitted event dict. @@ -32,46 +32,46 @@ def emit_added(self) -> generated_models.ResponseOutputItemAddedEvent: } ) - def emit_in_progress(self) -> generated_models.ResponseFileSearchCallInProgressEvent: + def emit_in_progress(self) -> response_models.ResponseFileSearchCallInProgressEvent: """Emit a file-search in-progress state event. :returns: The emitted event dict. :rtype: ResponseFileSearchCallInProgressEvent """ return cast( - generated_models.ResponseFileSearchCallInProgressEvent, + response_models.ResponseFileSearchCallInProgressEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_FILE_SEARCH_CALL_IN_PROGRESS.value + response_models.ResponseStreamEventType.RESPONSE_FILE_SEARCH_CALL_IN_PROGRESS.value ), ) - def emit_searching(self) -> generated_models.ResponseFileSearchCallSearchingEvent: + def emit_searching(self) -> response_models.ResponseFileSearchCallSearchingEvent: """Emit a file-search searching state event. :returns: The emitted event dict. :rtype: ResponseFileSearchCallSearchingEvent """ return cast( - generated_models.ResponseFileSearchCallSearchingEvent, + response_models.ResponseFileSearchCallSearchingEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_FILE_SEARCH_CALL_SEARCHING.value + response_models.ResponseStreamEventType.RESPONSE_FILE_SEARCH_CALL_SEARCHING.value ), ) - def emit_completed(self) -> generated_models.ResponseFileSearchCallCompletedEvent: + def emit_completed(self) -> response_models.ResponseFileSearchCallCompletedEvent: """Emit a file-search completed state event. :returns: The emitted event dict. :rtype: ResponseFileSearchCallCompletedEvent """ return cast( - generated_models.ResponseFileSearchCallCompletedEvent, + response_models.ResponseFileSearchCallCompletedEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_FILE_SEARCH_CALL_COMPLETED.value + response_models.ResponseStreamEventType.RESPONSE_FILE_SEARCH_CALL_COMPLETED.value ), ) - def emit_done(self) -> generated_models.ResponseOutputItemDoneEvent: + def emit_done(self) -> response_models.ResponseOutputItemDoneEvent: """Emit an ``output_item.done`` event for this file search call. :returns: The emitted event dict. @@ -83,7 +83,7 @@ def emit_done(self) -> generated_models.ResponseOutputItemDoneEvent: class OutputItemWebSearchCallBuilder(BaseOutputItemBuilder): """Scoped builder for web search tool call events.""" - def emit_added(self) -> generated_models.ResponseOutputItemAddedEvent: + def emit_added(self) -> response_models.ResponseOutputItemAddedEvent: """Emit an ``output_item.added`` event for a web search call. :returns: The emitted event dict. @@ -91,46 +91,46 @@ def emit_added(self) -> generated_models.ResponseOutputItemAddedEvent: """ return self._emit_added({"type": "web_search_call", "id": self._item_id, "status": "in_progress", "action": {}}) - def emit_in_progress(self) -> generated_models.ResponseWebSearchCallInProgressEvent: + def emit_in_progress(self) -> response_models.ResponseWebSearchCallInProgressEvent: """Emit a web-search in-progress state event. :returns: The emitted event dict. :rtype: ResponseWebSearchCallInProgressEvent """ return cast( - generated_models.ResponseWebSearchCallInProgressEvent, + response_models.ResponseWebSearchCallInProgressEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_WEB_SEARCH_CALL_IN_PROGRESS.value + response_models.ResponseStreamEventType.RESPONSE_WEB_SEARCH_CALL_IN_PROGRESS.value ), ) - def emit_searching(self) -> generated_models.ResponseWebSearchCallSearchingEvent: + def emit_searching(self) -> response_models.ResponseWebSearchCallSearchingEvent: """Emit a web-search searching state event. :returns: The emitted event dict. :rtype: ResponseWebSearchCallSearchingEvent """ return cast( - generated_models.ResponseWebSearchCallSearchingEvent, + response_models.ResponseWebSearchCallSearchingEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_WEB_SEARCH_CALL_SEARCHING.value + response_models.ResponseStreamEventType.RESPONSE_WEB_SEARCH_CALL_SEARCHING.value ), ) - def emit_completed(self) -> generated_models.ResponseWebSearchCallCompletedEvent: + def emit_completed(self) -> response_models.ResponseWebSearchCallCompletedEvent: """Emit a web-search completed state event. :returns: The emitted event dict. :rtype: ResponseWebSearchCallCompletedEvent """ return cast( - generated_models.ResponseWebSearchCallCompletedEvent, + response_models.ResponseWebSearchCallCompletedEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_WEB_SEARCH_CALL_COMPLETED.value + response_models.ResponseStreamEventType.RESPONSE_WEB_SEARCH_CALL_COMPLETED.value ), ) - def emit_done(self) -> generated_models.ResponseOutputItemDoneEvent: + def emit_done(self) -> response_models.ResponseOutputItemDoneEvent: """Emit an ``output_item.done`` event for this web search call. :returns: The emitted event dict. @@ -155,7 +155,7 @@ def __init__(self, stream: "ResponseEventStream", output_index: int, item_id: st super().__init__(stream=stream, output_index=output_index, item_id=item_id) self._final_code: str | None = None - def emit_added(self) -> generated_models.ResponseOutputItemAddedEvent: + def emit_added(self) -> response_models.ResponseOutputItemAddedEvent: """Emit an ``output_item.added`` event for a code interpreter call. :returns: The emitted event dict. @@ -172,33 +172,33 @@ def emit_added(self) -> generated_models.ResponseOutputItemAddedEvent: } ) - def emit_in_progress(self) -> generated_models.ResponseCodeInterpreterCallInProgressEvent: + def emit_in_progress(self) -> response_models.ResponseCodeInterpreterCallInProgressEvent: """Emit a code-interpreter in-progress state event. :returns: The emitted event dict. :rtype: ResponseCodeInterpreterCallInProgressEvent """ return cast( - generated_models.ResponseCodeInterpreterCallInProgressEvent, + response_models.ResponseCodeInterpreterCallInProgressEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_IN_PROGRESS.value + response_models.ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_IN_PROGRESS.value ), ) - def emit_interpreting(self) -> generated_models.ResponseCodeInterpreterCallInterpretingEvent: + def emit_interpreting(self) -> response_models.ResponseCodeInterpreterCallInterpretingEvent: """Emit a code-interpreter interpreting state event. :returns: The emitted event dict. :rtype: ResponseCodeInterpreterCallInterpretingEvent """ return cast( - generated_models.ResponseCodeInterpreterCallInterpretingEvent, + response_models.ResponseCodeInterpreterCallInterpretingEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_INTERPRETING.value + response_models.ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_INTERPRETING.value ), ) - def emit_code_delta(self, delta: str) -> generated_models.ResponseCodeInterpreterCallCodeDeltaEvent: + def emit_code_delta(self, delta: str) -> response_models.ResponseCodeInterpreterCallCodeDeltaEvent: """Emit a code-interpreter code delta event. :param delta: The incremental code fragment. @@ -207,14 +207,14 @@ def emit_code_delta(self, delta: str) -> generated_models.ResponseCodeInterprete :rtype: ResponseCodeInterpreterCallCodeDeltaEvent """ return cast( - generated_models.ResponseCodeInterpreterCallCodeDeltaEvent, + response_models.ResponseCodeInterpreterCallCodeDeltaEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_CODE_DELTA.value, + response_models.ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_CODE_DELTA.value, extra_payload={"delta": delta}, ), ) - def emit_code_done(self, code: str) -> generated_models.ResponseCodeInterpreterCallCodeDoneEvent: + def emit_code_done(self, code: str) -> response_models.ResponseCodeInterpreterCallCodeDoneEvent: """Emit a code-interpreter code done event. :param code: The final, complete code string. @@ -224,27 +224,27 @@ def emit_code_done(self, code: str) -> generated_models.ResponseCodeInterpreterC """ self._final_code = code return cast( - generated_models.ResponseCodeInterpreterCallCodeDoneEvent, + response_models.ResponseCodeInterpreterCallCodeDoneEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_CODE_DONE.value, + response_models.ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_CODE_DONE.value, extra_payload={"code": code}, ), ) - def emit_completed(self) -> generated_models.ResponseCodeInterpreterCallCompletedEvent: + def emit_completed(self) -> response_models.ResponseCodeInterpreterCallCompletedEvent: """Emit a code-interpreter completed state event. :returns: The emitted event dict. :rtype: ResponseCodeInterpreterCallCompletedEvent """ return cast( - generated_models.ResponseCodeInterpreterCallCompletedEvent, + response_models.ResponseCodeInterpreterCallCompletedEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_COMPLETED.value + response_models.ResponseStreamEventType.RESPONSE_CODE_INTERPRETER_CALL_COMPLETED.value ), ) - def emit_done(self) -> generated_models.ResponseOutputItemDoneEvent: + def emit_done(self) -> response_models.ResponseOutputItemDoneEvent: """Emit an ``output_item.done`` event for this code interpreter call. :returns: The emitted event dict. @@ -263,7 +263,7 @@ def emit_done(self) -> generated_models.ResponseOutputItemDoneEvent: # ---- Sub-item convenience generators (S-053) ---- - def code(self, code_text: str) -> Iterator[generated_models.ResponseStreamEvent]: + def code(self, code_text: str) -> Iterator[response_models.ResponseStreamEvent]: """Yield the code delta and code done events. Emits ``code_interpreter_call.code.delta`` followed by @@ -277,7 +277,7 @@ def code(self, code_text: str) -> Iterator[generated_models.ResponseStreamEvent] yield self.emit_code_delta(code_text) yield self.emit_code_done(code_text) - async def acode(self, code_text: str | AsyncIterable[str]) -> AsyncIterator[generated_models.ResponseStreamEvent]: + async def acode(self, code_text: str | AsyncIterable[str]) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`code` with streaming support. When *code_text* is a string, behaves identically to :meth:`code`. @@ -317,7 +317,7 @@ def __init__(self, stream: "ResponseEventStream", output_index: int, item_id: st super().__init__(stream=stream, output_index=output_index, item_id=item_id) self._partial_image_index = 0 - def emit_added(self) -> generated_models.ResponseOutputItemAddedEvent: + def emit_added(self) -> response_models.ResponseOutputItemAddedEvent: """Emit an ``output_item.added`` event for an image generation call. :returns: The emitted event dict. @@ -332,33 +332,33 @@ def emit_added(self) -> generated_models.ResponseOutputItemAddedEvent: } ) - def emit_in_progress(self) -> generated_models.ResponseImageGenCallInProgressEvent: + def emit_in_progress(self) -> response_models.ResponseImageGenCallInProgressEvent: """Emit an image-generation in-progress state event. :returns: The emitted event dict. :rtype: ResponseImageGenCallInProgressEvent """ return cast( - generated_models.ResponseImageGenCallInProgressEvent, + response_models.ResponseImageGenCallInProgressEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_IMAGE_GENERATION_CALL_IN_PROGRESS.value + response_models.ResponseStreamEventType.RESPONSE_IMAGE_GENERATION_CALL_IN_PROGRESS.value ), ) - def emit_generating(self) -> generated_models.ResponseImageGenCallGeneratingEvent: + def emit_generating(self) -> response_models.ResponseImageGenCallGeneratingEvent: """Emit an image-generation generating state event. :returns: The emitted event dict. :rtype: ResponseImageGenCallGeneratingEvent """ return cast( - generated_models.ResponseImageGenCallGeneratingEvent, + response_models.ResponseImageGenCallGeneratingEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_IMAGE_GENERATION_CALL_GENERATING.value + response_models.ResponseStreamEventType.RESPONSE_IMAGE_GENERATION_CALL_GENERATING.value ), ) - def emit_partial_image(self, partial_image_b64: str) -> generated_models.ResponseImageGenCallPartialImageEvent: + def emit_partial_image(self, partial_image_b64: str) -> response_models.ResponseImageGenCallPartialImageEvent: """Emit a partial image event with base64-encoded image data. :param partial_image_b64: Base64-encoded partial image data. @@ -369,27 +369,27 @@ def emit_partial_image(self, partial_image_b64: str) -> generated_models.Respons partial_index = self._partial_image_index self._partial_image_index += 1 return cast( - generated_models.ResponseImageGenCallPartialImageEvent, + response_models.ResponseImageGenCallPartialImageEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_IMAGE_GENERATION_CALL_PARTIAL_IMAGE.value, + response_models.ResponseStreamEventType.RESPONSE_IMAGE_GENERATION_CALL_PARTIAL_IMAGE.value, extra_payload={"partial_image_index": partial_index, "partial_image_b64": partial_image_b64}, ), ) - def emit_completed(self) -> generated_models.ResponseImageGenCallCompletedEvent: + def emit_completed(self) -> response_models.ResponseImageGenCallCompletedEvent: """Emit an image-generation completed state event. :returns: The emitted event dict. :rtype: ResponseImageGenCallCompletedEvent """ return cast( - generated_models.ResponseImageGenCallCompletedEvent, + response_models.ResponseImageGenCallCompletedEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_IMAGE_GENERATION_CALL_COMPLETED.value + response_models.ResponseStreamEventType.RESPONSE_IMAGE_GENERATION_CALL_COMPLETED.value ), ) - def emit_done(self, result: str) -> generated_models.ResponseOutputItemDoneEvent: + def emit_done(self, result: str) -> response_models.ResponseOutputItemDoneEvent: """Emit an ``output_item.done`` event for this image generation call. :param result: The base64-encoded image result. @@ -455,7 +455,7 @@ def name(self) -> str: """ return self._name - def emit_added(self) -> generated_models.ResponseOutputItemAddedEvent: + def emit_added(self) -> response_models.ResponseOutputItemAddedEvent: """Emit an ``output_item.added`` event for an MCP call. :returns: The emitted event dict. @@ -472,18 +472,18 @@ def emit_added(self) -> generated_models.ResponseOutputItemAddedEvent: } ) - def emit_in_progress(self) -> generated_models.ResponseMCPCallInProgressEvent: + def emit_in_progress(self) -> response_models.ResponseMCPCallInProgressEvent: """Emit an MCP call in-progress state event. :returns: The emitted event dict. :rtype: ResponseMCPCallInProgressEvent """ return cast( - generated_models.ResponseMCPCallInProgressEvent, - self._emit_item_state_event(generated_models.ResponseStreamEventType.RESPONSE_MCP_CALL_IN_PROGRESS.value), + response_models.ResponseMCPCallInProgressEvent, + self._emit_item_state_event(response_models.ResponseStreamEventType.RESPONSE_MCP_CALL_IN_PROGRESS.value), ) - def emit_arguments_delta(self, delta: str) -> generated_models.ResponseMCPCallArgumentsDeltaEvent: + def emit_arguments_delta(self, delta: str) -> response_models.ResponseMCPCallArgumentsDeltaEvent: """Emit an MCP call arguments delta event. :param delta: The incremental arguments text fragment. @@ -492,14 +492,14 @@ def emit_arguments_delta(self, delta: str) -> generated_models.ResponseMCPCallAr :rtype: ResponseMCPCallArgumentsDeltaEvent """ return cast( - generated_models.ResponseMCPCallArgumentsDeltaEvent, + response_models.ResponseMCPCallArgumentsDeltaEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_MCP_CALL_ARGUMENTS_DELTA.value, + response_models.ResponseStreamEventType.RESPONSE_MCP_CALL_ARGUMENTS_DELTA.value, extra_payload={"delta": delta}, ), ) - def emit_arguments_done(self, arguments: str) -> generated_models.ResponseMCPCallArgumentsDoneEvent: + def emit_arguments_done(self, arguments: str) -> response_models.ResponseMCPCallArgumentsDoneEvent: """Emit an MCP call arguments done event. :param arguments: The final, complete arguments string. @@ -509,14 +509,14 @@ def emit_arguments_done(self, arguments: str) -> generated_models.ResponseMCPCal """ self._final_arguments = arguments return cast( - generated_models.ResponseMCPCallArgumentsDoneEvent, + response_models.ResponseMCPCallArgumentsDoneEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_MCP_CALL_ARGUMENTS_DONE.value, + response_models.ResponseStreamEventType.RESPONSE_MCP_CALL_ARGUMENTS_DONE.value, extra_payload={"arguments": arguments}, ), ) - def emit_completed(self) -> generated_models.ResponseMCPCallCompletedEvent: + def emit_completed(self) -> response_models.ResponseMCPCallCompletedEvent: """Emit an MCP call completed state event. :returns: The emitted event dict. @@ -524,11 +524,11 @@ def emit_completed(self) -> generated_models.ResponseMCPCallCompletedEvent: """ self._terminal_status = "completed" return cast( - generated_models.ResponseMCPCallCompletedEvent, - self._emit_item_state_event(generated_models.ResponseStreamEventType.RESPONSE_MCP_CALL_COMPLETED.value), + response_models.ResponseMCPCallCompletedEvent, + self._emit_item_state_event(response_models.ResponseStreamEventType.RESPONSE_MCP_CALL_COMPLETED.value), ) - def emit_failed(self) -> generated_models.ResponseMCPCallFailedEvent: + def emit_failed(self) -> response_models.ResponseMCPCallFailedEvent: """Emit an MCP call failed state event. :returns: The emitted event dict. @@ -536,8 +536,8 @@ def emit_failed(self) -> generated_models.ResponseMCPCallFailedEvent: """ self._terminal_status = "failed" return cast( - generated_models.ResponseMCPCallFailedEvent, - self._emit_item_state_event(generated_models.ResponseStreamEventType.RESPONSE_MCP_CALL_FAILED.value), + response_models.ResponseMCPCallFailedEvent, + self._emit_item_state_event(response_models.ResponseStreamEventType.RESPONSE_MCP_CALL_FAILED.value), ) def emit_done( @@ -545,7 +545,7 @@ def emit_done( *, output: str | None = None, error: dict[str, Any] | None = None, - ) -> generated_models.ResponseOutputItemDoneEvent: + ) -> response_models.ResponseOutputItemDoneEvent: """Emit an ``output_item.done`` event for this MCP call. The ``status`` field reflects the most recent terminal state event @@ -576,7 +576,7 @@ def emit_done( # ---- Sub-item convenience generators (S-053) ---- - def arguments(self, args: str) -> Iterator[generated_models.ResponseStreamEvent]: + def arguments(self, args: str) -> Iterator[response_models.ResponseStreamEvent]: """Yield the argument delta and done events. Emits ``mcp_call_arguments.delta`` followed by @@ -590,7 +590,7 @@ def arguments(self, args: str) -> Iterator[generated_models.ResponseStreamEvent] yield self.emit_arguments_delta(args) yield self.emit_arguments_done(args) - async def aarguments(self, args: str | AsyncIterable[str]) -> AsyncIterator[generated_models.ResponseStreamEvent]: + async def aarguments(self, args: str | AsyncIterable[str]) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`arguments` with streaming support. When *args* is a string, behaves identically to :meth:`arguments`. @@ -641,7 +641,7 @@ def server_label(self) -> str: """ return self._server_label - def emit_added(self) -> generated_models.ResponseOutputItemAddedEvent: + def emit_added(self) -> response_models.ResponseOutputItemAddedEvent: """Emit an ``output_item.added`` event for MCP list-tools. :returns: The emitted event dict. @@ -656,44 +656,44 @@ def emit_added(self) -> generated_models.ResponseOutputItemAddedEvent: } ) - def emit_in_progress(self) -> generated_models.ResponseMCPListToolsInProgressEvent: + def emit_in_progress(self) -> response_models.ResponseMCPListToolsInProgressEvent: """Emit an MCP list-tools in-progress state event. :returns: The emitted event dict. :rtype: ResponseMCPListToolsInProgressEvent """ return cast( - generated_models.ResponseMCPListToolsInProgressEvent, + response_models.ResponseMCPListToolsInProgressEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_MCP_LIST_TOOLS_IN_PROGRESS.value + response_models.ResponseStreamEventType.RESPONSE_MCP_LIST_TOOLS_IN_PROGRESS.value ), ) - def emit_completed(self) -> generated_models.ResponseMCPListToolsCompletedEvent: + def emit_completed(self) -> response_models.ResponseMCPListToolsCompletedEvent: """Emit an MCP list-tools completed state event. :returns: The emitted event dict. :rtype: ResponseMCPListToolsCompletedEvent """ return cast( - generated_models.ResponseMCPListToolsCompletedEvent, + response_models.ResponseMCPListToolsCompletedEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_MCP_LIST_TOOLS_COMPLETED.value + response_models.ResponseStreamEventType.RESPONSE_MCP_LIST_TOOLS_COMPLETED.value ), ) - def emit_failed(self) -> generated_models.ResponseMCPListToolsFailedEvent: + def emit_failed(self) -> response_models.ResponseMCPListToolsFailedEvent: """Emit an MCP list-tools failed state event. :returns: The emitted event dict. :rtype: ResponseMCPListToolsFailedEvent """ return cast( - generated_models.ResponseMCPListToolsFailedEvent, - self._emit_item_state_event(generated_models.ResponseStreamEventType.RESPONSE_MCP_LIST_TOOLS_FAILED.value), + response_models.ResponseMCPListToolsFailedEvent, + self._emit_item_state_event(response_models.ResponseStreamEventType.RESPONSE_MCP_LIST_TOOLS_FAILED.value), ) - def emit_done(self) -> generated_models.ResponseOutputItemDoneEvent: + def emit_done(self) -> response_models.ResponseOutputItemDoneEvent: """Emit an ``output_item.done`` event for MCP list-tools. :returns: The emitted event dict. @@ -756,7 +756,7 @@ def name(self) -> str: """ return self._name - def emit_added(self) -> generated_models.ResponseOutputItemAddedEvent: + def emit_added(self) -> response_models.ResponseOutputItemAddedEvent: """Emit an ``output_item.added`` event for a custom tool call. :returns: The emitted event dict. @@ -772,7 +772,7 @@ def emit_added(self) -> generated_models.ResponseOutputItemAddedEvent: } ) - def emit_input_delta(self, delta: str) -> generated_models.ResponseCustomToolCallInputDeltaEvent: + def emit_input_delta(self, delta: str) -> response_models.ResponseCustomToolCallInputDeltaEvent: """Emit a custom tool call input delta event. :param delta: The incremental input text fragment. @@ -781,14 +781,14 @@ def emit_input_delta(self, delta: str) -> generated_models.ResponseCustomToolCal :rtype: ResponseCustomToolCallInputDeltaEvent """ return cast( - generated_models.ResponseCustomToolCallInputDeltaEvent, + response_models.ResponseCustomToolCallInputDeltaEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_CUSTOM_TOOL_CALL_INPUT_DELTA.value, + response_models.ResponseStreamEventType.RESPONSE_CUSTOM_TOOL_CALL_INPUT_DELTA.value, extra_payload={"delta": delta}, ), ) - def emit_input_done(self, input_text: str) -> generated_models.ResponseCustomToolCallInputDoneEvent: + def emit_input_done(self, input_text: str) -> response_models.ResponseCustomToolCallInputDoneEvent: """Emit a custom tool call input done event. :param input_text: The final, complete input text. @@ -798,14 +798,14 @@ def emit_input_done(self, input_text: str) -> generated_models.ResponseCustomToo """ self._final_input = input_text return cast( - generated_models.ResponseCustomToolCallInputDoneEvent, + response_models.ResponseCustomToolCallInputDoneEvent, self._emit_item_state_event( - generated_models.ResponseStreamEventType.RESPONSE_CUSTOM_TOOL_CALL_INPUT_DONE.value, + response_models.ResponseStreamEventType.RESPONSE_CUSTOM_TOOL_CALL_INPUT_DONE.value, extra_payload={"input": input_text}, ), ) - def emit_done(self) -> generated_models.ResponseOutputItemDoneEvent: + def emit_done(self) -> response_models.ResponseOutputItemDoneEvent: """Emit an ``output_item.done`` event for this custom tool call. :returns: The emitted event dict. @@ -823,7 +823,7 @@ def emit_done(self) -> generated_models.ResponseOutputItemDoneEvent: # ---- Sub-item convenience generators (S-053) ---- - def input(self, input_text: str) -> Iterator[generated_models.ResponseStreamEvent]: + def input(self, input_text: str) -> Iterator[response_models.ResponseStreamEvent]: """Yield the input delta and input done events. Emits ``custom_tool_call_input.delta`` followed by @@ -837,7 +837,7 @@ def input(self, input_text: str) -> Iterator[generated_models.ResponseStreamEven yield self.emit_input_delta(input_text) yield self.emit_input_done(input_text) - async def ainput(self, input_text: str | AsyncIterable[str]) -> AsyncIterator[generated_models.ResponseStreamEvent]: + async def ainput(self, input_text: str | AsyncIterable[str]) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`input` with streaming support. When *input_text* is a string, behaves identically to :meth:`input`. diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_event_stream.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_event_stream.py index 8d1ecbe94fe2..ee306724e5cc 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_event_stream.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_event_stream.py @@ -9,10 +9,11 @@ from datetime import datetime, timezone from typing import Any, AsyncIterator, Iterator, Sequence, cast +from azure.ai.extensions.openai import to_wire_dict +from azure.ai.extensions.openai import responses as response_models +from azure.ai.extensions.openai.responses import AgentReference + from .._id_generator import IdGenerator -from ..models import _generated as generated_models -from ..models._generated import AgentReference -from ..models._generated.sdk.models._utils.model_base import Model as _Model from . import _internals from ._builders import ( OutputItemBuilder, @@ -28,7 +29,6 @@ OutputItemReasoningItemBuilder, OutputItemWebSearchCallBuilder, ) -from ._internals import construct_event_model from ._state_machine import EventStreamValidator # Event types whose payload is a full Response snapshot. @@ -41,10 +41,10 @@ def _resolve_conversation_param(raw: Any) -> str | None: The input side of ``CreateResponse.conversation`` is ``Union[str, ConversationParam_2]`` whereas the output side ``ResponseObject.conversation`` is always a ``ConversationReference`` - (object form ``{"id": "..."}``. This helper extracts the string ID from whichever - form was supplied. + (object form ``{"id": "..."}``). This helper extracts the string ID from whichever + wire form was supplied. - :param raw: The raw conversation value from the request (string, dict, model, or None). + :param raw: The raw conversation value from the request (string, dict, or None). :type raw: Any :returns: The conversation ID string, or ``None`` if absent/empty. :rtype: str | None @@ -56,17 +56,12 @@ def _resolve_conversation_param(raw: Any) -> str | None: if isinstance(raw, dict): cid = raw.get("id") return str(cid) if cid else None - if hasattr(raw, "id"): - cid = raw.id - return str(cid) if cid else None return None -def _as_dict(obj: _Model | dict[str, Any]) -> dict[str, Any]: # pylint: disable=docstring-missing-param,docstring-missing-return,docstring-missing-rtype +def _as_dict(obj: Any) -> dict[str, Any]: # pylint: disable=docstring-missing-param,docstring-missing-return,docstring-missing-rtype """Convert a model or dict-like object to a plain dictionary.""" - if isinstance(obj, _Model): - return obj.as_dict() - return obj + return to_wire_dict(obj) class ResponseEventStream: # pylint: disable=too-many-public-methods @@ -78,8 +73,8 @@ def __init__( response_id: str | None = None, agent_reference: AgentReference | None = None, model: str | None = None, - request: generated_models.CreateResponse | None = None, - response: generated_models.ResponseObject | None = None, + request: response_models.CreateResponse | None = None, + response: response_models.ResponseObject | None = None, ) -> None: """Initialize a new response event stream. @@ -90,9 +85,9 @@ def __init__( :param model: Optional model identifier to stamp on the response. :type model: str | None :param request: Optional create-response request to seed the response envelope from. - :type request: ~azure.ai.agentserver.responses.models._generated.CreateResponse | None + :type request: ~azure.ai.extensions.openai.responses.CreateResponse | None :param response: Optional pre-existing response envelope to build upon. - :type response: ~azure.ai.agentserver.responses.models._generated.ResponseObject | None + :type response: ~azure.ai.extensions.openai.responses.ResponseObject | None :raises ValueError: If both *request* and *response* are provided, or if *response_id* cannot be resolved. """ if request is not None and response is not None: @@ -117,125 +112,123 @@ def __init__( payload["id"] = self._response_id payload.setdefault("object", "response") payload.setdefault("output", []) - self._response = generated_models.ResponseObject(payload) + self._response = payload else: - self._response = generated_models.ResponseObject( - { - "id": self._response_id, - "object": "response", - "output": [], - "created_at": datetime.now(timezone.utc), - } - ) + self._response = { + "id": self._response_id, + "object": "response", + "output": [], + "created_at": datetime.now(timezone.utc), + } if request_mapping is not None: for field_name in ("metadata", "background", "previous_response_id"): value = request_mapping.get(field_name) if value is not None: - setattr(self._response, field_name, deepcopy(value)) + self._response[field_name] = deepcopy(value) # Normalize polymorphic conversation (str | ConversationParam_2) # to the response-side ConversationReference object form. conversation_id = _resolve_conversation_param(request_mapping.get("conversation")) if conversation_id is not None: - self._response.conversation = generated_models.ConversationReference(id=conversation_id) + self._response["conversation"] = {"id": conversation_id} request_model = request_mapping.get("model") if isinstance(request_model, str) and request_model: - self._response.model = request_model + self._response["model"] = request_model request_agent_reference = request_mapping.get("agent_reference") if isinstance(request_agent_reference, dict): - self._response.agent_reference = deepcopy(request_agent_reference) # type: ignore[assignment] + self._response["agent_reference"] = deepcopy(request_agent_reference) if model is not None: - self._response.model = model + self._response["model"] = model if agent_reference is not None: - self._response.agent_reference = deepcopy(agent_reference) # type: ignore[assignment] + self._response["agent_reference"] = deepcopy(agent_reference) self._agent_reference, self._model = _internals.extract_response_fields(self._response) - self._events: list[generated_models.ResponseStreamEvent] = [] + self._events: list[response_models.ResponseStreamEvent] = [] self._validator = EventStreamValidator() self._output_index = 0 @property - def response(self) -> generated_models.ResponseObject: + def response(self) -> dict[str, Any]: """Return the current response envelope. :returns: The mutable response envelope being built by this stream. - :rtype: ~azure.ai.agentserver.responses.models._generated.ResponseObject + :rtype: ~azure.ai.extensions.openai.responses.ResponseObject """ return self._response - def emit_queued(self) -> generated_models.ResponseQueuedEvent: + def emit_queued(self) -> response_models.ResponseQueuedEvent: """Emit a ``response.queued`` lifecycle event. :returns: The emitted event model instance. - :rtype: ~azure.ai.agentserver.responses.models._generated.ResponseQueuedEvent + :rtype: ~azure.ai.extensions.openai.responses.ResponseQueuedEvent """ - self._response.status = "queued" + self._response["status"] = "queued" return cast( - generated_models.ResponseQueuedEvent, + response_models.ResponseQueuedEvent, self._emit_event( { - "type": generated_models.ResponseStreamEventType.RESPONSE_QUEUED.value, + "type": response_models.ResponseStreamEventType.RESPONSE_QUEUED.value, "response": self._response_payload(), } ), ) - def emit_created(self, *, status: str = "in_progress") -> generated_models.ResponseCreatedEvent: + def emit_created(self, *, status: str = "in_progress") -> response_models.ResponseCreatedEvent: """Emit a ``response.created`` lifecycle event. :keyword status: Initial status to set on the response. Defaults to ``"in_progress"``. :keyword type status: str :returns: The emitted event model instance. - :rtype: ~azure.ai.agentserver.responses.models._generated.ResponseCreatedEvent + :rtype: ~azure.ai.extensions.openai.responses.ResponseCreatedEvent """ - self._response.status = status # type: ignore[assignment] + self._response["status"] = status return cast( - generated_models.ResponseCreatedEvent, + response_models.ResponseCreatedEvent, self._emit_event( { - "type": generated_models.ResponseStreamEventType.RESPONSE_CREATED.value, + "type": response_models.ResponseStreamEventType.RESPONSE_CREATED.value, "response": self._response_payload(), } ), ) - def emit_in_progress(self) -> generated_models.ResponseInProgressEvent: + def emit_in_progress(self) -> response_models.ResponseInProgressEvent: """Emit a ``response.in_progress`` lifecycle event. :returns: The emitted event model instance. - :rtype: ~azure.ai.agentserver.responses.models._generated.ResponseInProgressEvent + :rtype: ~azure.ai.extensions.openai.responses.ResponseInProgressEvent """ - self._response.status = "in_progress" + self._response["status"] = "in_progress" return cast( - generated_models.ResponseInProgressEvent, + response_models.ResponseInProgressEvent, self._emit_event( { - "type": generated_models.ResponseStreamEventType.RESPONSE_IN_PROGRESS.value, + "type": response_models.ResponseStreamEventType.RESPONSE_IN_PROGRESS.value, "response": self._response_payload(), } ), ) def emit_completed( - self, *, usage: generated_models.ResponseUsage | None = None - ) -> generated_models.ResponseCompletedEvent: + self, *, usage: response_models.ResponseUsage | None = None + ) -> response_models.ResponseCompletedEvent: """Emit a ``response.completed`` terminal lifecycle event. :keyword usage: Optional usage statistics to attach to the response. - :keyword type usage: ~azure.ai.agentserver.responses.models._generated.ResponseUsage | None + :keyword type usage: ~azure.ai.extensions.openai.responses.ResponseUsage | None :returns: The emitted event model instance. - :rtype: ~azure.ai.agentserver.responses.models._generated.ResponseCompletedEvent + :rtype: ~azure.ai.extensions.openai.responses.ResponseCompletedEvent """ - self._response.status = "completed" - self._response.error = None # type: ignore[assignment] - self._response.incomplete_details = None # type: ignore[assignment] + self._response["status"] = "completed" + self._response["error"] = None + self._response["incomplete_details"] = None self._set_terminal_fields(usage=usage) return cast( - generated_models.ResponseCompletedEvent, + response_models.ResponseCompletedEvent, self._emit_event( { - "type": generated_models.ResponseStreamEventType.RESPONSE_COMPLETED.value, + "type": response_models.ResponseStreamEventType.RESPONSE_COMPLETED.value, "response": self._response_payload(), } ), @@ -244,35 +237,33 @@ def emit_completed( def emit_failed( self, *, - code: str | generated_models.ResponseErrorCode = "server_error", + code: str | response_models.ResponseErrorCode = "server_error", message: str = "An internal server error occurred.", - usage: generated_models.ResponseUsage | None = None, - ) -> generated_models.ResponseFailedEvent: + usage: response_models.ResponseUsage | None = None, + ) -> response_models.ResponseFailedEvent: """Emit a ``response.failed`` terminal lifecycle event. :keyword code: Error code describing the failure. - :keyword type code: str | ~azure.ai.agentserver.responses.models._generated.ResponseErrorCode + :keyword type code: str | ~azure.ai.extensions.openai.responses.ResponseErrorCode :keyword message: Human-readable error message. :keyword type message: str :keyword usage: Optional usage statistics to attach to the response. - :keyword type usage: ~azure.ai.agentserver.responses.models._generated.ResponseUsage | None + :keyword type usage: ~azure.ai.extensions.openai.responses.ResponseUsage | None :returns: The emitted event model instance. - :rtype: ~azure.ai.agentserver.responses.models._generated.ResponseFailedEvent - """ - self._response.status = "failed" - self._response.incomplete_details = None # type: ignore[assignment] - self._response.error = generated_models.ResponseErrorInfo( - { - "code": _internals.enum_value(code), - "message": message, - } - ) + :rtype: ~azure.ai.extensions.openai.responses.ResponseFailedEvent + """ + self._response["status"] = "failed" + self._response["incomplete_details"] = None + self._response["error"] = { + "code": _internals.enum_value(code), + "message": message, + } self._set_terminal_fields(usage=usage) return cast( - generated_models.ResponseFailedEvent, + response_models.ResponseFailedEvent, self._emit_event( { - "type": generated_models.ResponseStreamEventType.RESPONSE_FAILED.value, + "type": response_models.ResponseStreamEventType.RESPONSE_FAILED.value, "response": self._response_payload(), } ), @@ -282,34 +273,30 @@ def emit_incomplete( self, *, reason: str | None = None, - usage: generated_models.ResponseUsage | None = None, - ) -> generated_models.ResponseIncompleteEvent: + usage: response_models.ResponseUsage | None = None, + ) -> response_models.ResponseIncompleteEvent: """Emit a ``response.incomplete`` terminal lifecycle event. :keyword reason: Optional reason for incompleteness. - :keyword type reason: str | ~azure.ai.agentserver.responses.models._generated.ResponseIncompleteReason + :keyword type reason: str | ~azure.ai.extensions.openai.responses.ResponseIncompleteReason | None :keyword usage: Optional usage statistics to attach to the response. - :keyword type usage: ~azure.ai.agentserver.responses.models._generated.ResponseUsage | None + :keyword type usage: ~azure.ai.extensions.openai.responses.ResponseUsage | None :returns: The emitted event model instance. - :rtype: ~azure.ai.agentserver.responses.models._generated.ResponseIncompleteEvent + :rtype: ~azure.ai.extensions.openai.responses.ResponseIncompleteEvent """ - self._response.status = "incomplete" - self._response.error = None # type: ignore[assignment] + self._response["status"] = "incomplete" + self._response["error"] = None if reason is None: - self._response.incomplete_details = None # type: ignore[assignment] + self._response["incomplete_details"] = None else: - self._response.incomplete_details = generated_models.ResponseIncompleteDetails( - { - "reason": _internals.enum_value(reason), - } - ) + self._response["incomplete_details"] = {"reason": _internals.enum_value(reason)} self._set_terminal_fields(usage=usage) return cast( - generated_models.ResponseIncompleteEvent, + response_models.ResponseIncompleteEvent, self._emit_event( { - "type": generated_models.ResponseStreamEventType.RESPONSE_INCOMPLETE.value, + "type": response_models.ResponseStreamEventType.RESPONSE_INCOMPLETE.value, "response": self._response_payload(), } ), @@ -661,44 +648,39 @@ def add_output_item_compaction(self) -> OutputItemBuilder: item_id = IdGenerator.new_compaction_item_id(self._response_id) return OutputItemBuilder(self, output_index=output_index, item_id=item_id) - def events(self) -> list[generated_models.ResponseStreamEvent]: + def events(self) -> list[response_models.ResponseStreamEvent]: """Return copies of all events emitted so far as typed model instances. :returns: A list of ``ResponseStreamEvent`` model instances. - :rtype: list[~azure.ai.agentserver.responses.models._generated.ResponseStreamEvent] + :rtype: list[~azure.ai.extensions.openai.responses.ResponseStreamEvent] """ - return [construct_event_model(event.as_dict()) for event in self._events] + return [deepcopy(event) for event in self._events] - def _emit_event(self, event: dict[str, Any]) -> generated_models.ResponseStreamEvent: + def _emit_event(self, event: dict[str, Any]) -> response_models.ResponseStreamEvent: """Emit a single event, applying defaults and validating the stream. - Accepts a **wire-format** dict (no ``"payload"`` wrapper), constructs - a typed ``ResponseStreamEvent`` model instance via polymorphic - deserialization, stamps defaults and sequence number, stores the - model, and returns it. + Accepts a **wire-format** dict (no ``"payload"`` wrapper), stamps + defaults and sequence number, stores the event, and returns it. :param event: A wire-format event dict. :type event: dict[str, Any] :returns: The typed event model instance. - :rtype: ~azure.ai.agentserver.responses.models._generated.ResponseStreamEvent + :rtype: ~azure.ai.extensions.openai.responses.ResponseStreamEvent """ candidate = deepcopy(event) # Stamp sequence number before model construction candidate["sequence_number"] = len(self._events) - # Construct typed model via polymorphic deserialization - model = construct_event_model(candidate) - # Apply response-level defaults to lifecycle events _internals.apply_common_defaults( - [model], response_id=self._response_id, agent_reference=self._agent_reference, model=self._model + [candidate], response_id=self._response_id, agent_reference=self._agent_reference, model=self._model ) # Track completed output items on the response envelope - _internals.track_completed_output_item(self._response, model) + _internals.track_completed_output_item(self._response, candidate) self._validator.validate_next(candidate) - self._events.append(model) - return model + self._events.append(candidate) + return cast(response_models.ResponseStreamEvent, candidate) # ---- Generator convenience methods (S-056/S-057) ---- # Output-item convenience generators that encapsulate the full lifecycle. @@ -709,7 +691,7 @@ def _emit_event(self, event: dict[str, Any]) -> generated_models.ResponseStreamE @staticmethod def _emit_simple_item( builder: OutputItemBuilder, item: dict[str, Any] - ) -> Iterator[generated_models.ResponseStreamEvent]: + ) -> Iterator[response_models.ResponseStreamEvent]: """Emit the added→done pair for a simple output item. :param builder: The generic output item builder. @@ -726,8 +708,8 @@ def output_item_message( self, text: str, *, - annotations: Sequence[generated_models.Annotation] | None = None, - ) -> Iterator[generated_models.ResponseStreamEvent]: + annotations: Sequence[response_models.Annotation] | None = None, + ) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for a text message output item. Emits output_item.added, content_part.added, output_text.delta, @@ -755,7 +737,7 @@ def output_item_message( def output_item_function_call( self, name: str, call_id: str, arguments: str - ) -> Iterator[generated_models.ResponseStreamEvent]: + ) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for a function call output item. Emits output_item.added, function_call_arguments.delta, @@ -777,7 +759,7 @@ def output_item_function_call( def output_item_function_call_output( self, call_id: str, output: str - ) -> Iterator[generated_models.ResponseStreamEvent]: + ) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for a function call output item. Emits output_item.added and output_item.done. @@ -793,7 +775,7 @@ def output_item_function_call_output( yield fco.emit_added(output) yield fco.emit_done(output) - def output_item_reasoning_item(self, summary_text: str) -> Iterator[generated_models.ResponseStreamEvent]: + def output_item_reasoning_item(self, summary_text: str) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for a reasoning output item. Emits output_item.added, reasoning_summary_part.added, @@ -810,7 +792,7 @@ def output_item_reasoning_item(self, summary_text: str) -> Iterator[generated_mo yield from item.summary_part(summary_text) yield item.emit_done() - def output_item_image_gen_call(self, result_base64: str) -> Iterator[generated_models.ResponseStreamEvent]: + def output_item_image_gen_call(self, result_base64: str) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for an image generation call. Emits added → in_progress → generating → completed → done(result). @@ -827,7 +809,7 @@ def output_item_image_gen_call(self, result_base64: str) -> Iterator[generated_m yield ig.emit_completed() yield ig.emit_done(result_base64) - def output_item_structured_outputs(self, output: Any) -> Iterator[generated_models.ResponseStreamEvent]: + def output_item_structured_outputs(self, output: Any) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for a structured outputs item. Emits output_item.added and output_item.done. @@ -844,11 +826,11 @@ def output_item_structured_outputs(self, output: Any) -> Iterator[generated_mode def output_item_computer_call( self, call_id: str, - action: generated_models.ComputerAction, + action: response_models.ComputerAction, *, - pending_safety_checks: list[generated_models.ComputerCallSafetyCheckParam] | None = None, + pending_safety_checks: list[response_models.ComputerCallSafetyCheckParam] | None = None, status: str = "completed", - ) -> Iterator[generated_models.ResponseStreamEvent]: + ) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for a computer call output item. :param call_id: Unique identifier for this tool call. @@ -878,10 +860,10 @@ def output_item_computer_call( def output_item_computer_call_output( self, call_id: str, - output: generated_models.ComputerScreenshotImage, + output: response_models.ComputerScreenshotImage, *, - acknowledged_safety_checks: list[generated_models.ComputerCallSafetyCheckParam] | None = None, - ) -> Iterator[generated_models.ResponseStreamEvent]: + acknowledged_safety_checks: list[response_models.ComputerCallSafetyCheckParam] | None = None, + ) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for a computer call output item. :param call_id: The call ID this output belongs to. @@ -908,10 +890,10 @@ def output_item_computer_call_output( def output_item_local_shell_call( self, call_id: str, - action: generated_models.LocalShellExecAction, + action: response_models.LocalShellExecAction, *, status: str = "completed", - ) -> Iterator[generated_models.ResponseStreamEvent]: + ) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for a local shell call output item. :param call_id: Unique identifier for this tool call. @@ -934,7 +916,7 @@ def output_item_local_shell_call( } yield from self._emit_simple_item(builder, item) - def output_item_local_shell_call_output(self, output: str) -> Iterator[generated_models.ResponseStreamEvent]: + def output_item_local_shell_call_output(self, output: str) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for a local shell call output item. :param output: The shell output string. @@ -949,11 +931,11 @@ def output_item_local_shell_call_output(self, output: str) -> Iterator[generated def output_item_function_shell_call( self, call_id: str, - action: generated_models.FunctionShellAction, - environment: generated_models.FunctionShellCallEnvironment, + action: response_models.FunctionShellAction, + environment: response_models.FunctionShellCallEnvironment, *, status: str = "completed", - ) -> Iterator[generated_models.ResponseStreamEvent]: + ) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for a function shell call output item. :param call_id: Unique identifier for this tool call. @@ -983,11 +965,11 @@ def output_item_function_shell_call( def output_item_function_shell_call_output( self, call_id: str, - output: list[generated_models.FunctionShellCallOutputContent], + output: list[response_models.FunctionShellCallOutputContent], *, status: str = "completed", max_output_length: int | None = None, - ) -> Iterator[generated_models.ResponseStreamEvent]: + ) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for a function shell call output item. :param call_id: The call ID this output belongs to. @@ -1016,10 +998,10 @@ def output_item_function_shell_call_output( def output_item_apply_patch_call( self, call_id: str, - operation: generated_models.ApplyPatchFileOperation, + operation: response_models.ApplyPatchFileOperation, *, status: str = "completed", - ) -> Iterator[generated_models.ResponseStreamEvent]: + ) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for an apply-patch call output item. :param call_id: Unique identifier for this tool call. @@ -1048,7 +1030,7 @@ def output_item_apply_patch_call_output( *, status: str = "completed", output: str | None = None, - ) -> Iterator[generated_models.ResponseStreamEvent]: + ) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for an apply-patch call output item. :param call_id: The call ID this output belongs to. @@ -1074,8 +1056,8 @@ def output_item_apply_patch_call_output( def output_item_custom_tool_call_output( self, call_id: str, - output: str | list[generated_models.FunctionAndCustomToolCallOutput], - ) -> Iterator[generated_models.ResponseStreamEvent]: + output: str | list[response_models.FunctionAndCustomToolCallOutput], + ) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for a custom tool call output item. :param call_id: The call ID this output belongs to. @@ -1101,7 +1083,7 @@ def output_item_custom_tool_call_output( def output_item_mcp_approval_request( self, server_label: str, name: str, arguments: str - ) -> Iterator[generated_models.ResponseStreamEvent]: + ) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for an MCP approval request item. :param server_label: Label identifying the MCP server. @@ -1129,7 +1111,7 @@ def output_item_mcp_approval_response( approve: bool, *, reason: str | None = None, - ) -> Iterator[generated_models.ResponseStreamEvent]: + ) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for an MCP approval response item. :param approval_request_id: The request ID being responded to. @@ -1152,7 +1134,7 @@ def output_item_mcp_approval_response( item["reason"] = reason yield from self._emit_simple_item(builder, item) - def output_item_compaction(self, encrypted_content: str) -> Iterator[generated_models.ResponseStreamEvent]: + def output_item_compaction(self, encrypted_content: str) -> Iterator[response_models.ResponseStreamEvent]: """Yield the full lifecycle for a compaction output item. :param encrypted_content: The encrypted compaction content. @@ -1171,8 +1153,8 @@ async def aoutput_item_message( self, text: str | AsyncIterable[str], *, - annotations: Sequence[generated_models.Annotation] | None = None, - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + annotations: Sequence[response_models.Annotation] | None = None, + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`output_item_message` with streaming support. When *text* is a string, emits the same events as the sync variant. @@ -1208,7 +1190,7 @@ async def aoutput_item_message( async def aoutput_item_function_call( self, name: str, call_id: str, arguments: str | AsyncIterable[str] - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`output_item_function_call` with streaming support. When *arguments* is a string, emits the same events as the sync variant. @@ -1236,7 +1218,7 @@ async def aoutput_item_function_call( async def aoutput_item_function_call_output( self, call_id: str, output: str - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`output_item_function_call_output`. :param call_id: The call ID of the function call this output belongs to. @@ -1251,7 +1233,7 @@ async def aoutput_item_function_call_output( async def aoutput_item_reasoning_item( self, summary_text: str | AsyncIterable[str] - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`output_item_reasoning_item` with streaming support. When *summary_text* is a string, emits the same events as the sync variant. @@ -1278,7 +1260,7 @@ async def aoutput_item_image_gen_call( result_base64: str, *, partials: AsyncIterable[str] | None = None, - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`output_item_image_gen_call` with optional partial streaming. When *partials* is provided, emits ``partial_image`` events between @@ -1301,7 +1283,7 @@ async def aoutput_item_image_gen_call( yield ig.emit_completed() yield ig.emit_done(result_base64) - async def aoutput_item_structured_outputs(self, output: Any) -> AsyncIterator[generated_models.ResponseStreamEvent]: + async def aoutput_item_structured_outputs(self, output: Any) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`output_item_structured_outputs`. :param output: The structured output data. @@ -1315,11 +1297,11 @@ async def aoutput_item_structured_outputs(self, output: Any) -> AsyncIterator[ge async def aoutput_item_computer_call( self, call_id: str, - action: generated_models.ComputerAction, + action: response_models.ComputerAction, *, - pending_safety_checks: list[generated_models.ComputerCallSafetyCheckParam] | None = None, + pending_safety_checks: list[response_models.ComputerCallSafetyCheckParam] | None = None, status: str = "completed", - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`output_item_computer_call`. :param call_id: Unique identifier for this tool call. @@ -1341,10 +1323,10 @@ async def aoutput_item_computer_call( async def aoutput_item_computer_call_output( self, call_id: str, - output: generated_models.ComputerScreenshotImage, + output: response_models.ComputerScreenshotImage, *, - acknowledged_safety_checks: list[generated_models.ComputerCallSafetyCheckParam] | None = None, - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + acknowledged_safety_checks: list[response_models.ComputerCallSafetyCheckParam] | None = None, + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`output_item_computer_call_output`. :param call_id: The call ID this output belongs to. @@ -1364,10 +1346,10 @@ async def aoutput_item_computer_call_output( async def aoutput_item_local_shell_call( self, call_id: str, - action: generated_models.LocalShellExecAction, + action: response_models.LocalShellExecAction, *, status: str = "completed", - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`output_item_local_shell_call`. :param call_id: Unique identifier for this tool call. @@ -1384,7 +1366,7 @@ async def aoutput_item_local_shell_call( async def aoutput_item_local_shell_call_output( self, output: str - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`output_item_local_shell_call_output`. :param output: The shell output string. @@ -1398,11 +1380,11 @@ async def aoutput_item_local_shell_call_output( async def aoutput_item_function_shell_call( self, call_id: str, - action: generated_models.FunctionShellAction, - environment: generated_models.FunctionShellCallEnvironment, + action: response_models.FunctionShellAction, + environment: response_models.FunctionShellCallEnvironment, *, status: str = "completed", - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`output_item_function_shell_call`. :param call_id: Unique identifier for this tool call. @@ -1422,11 +1404,11 @@ async def aoutput_item_function_shell_call( async def aoutput_item_function_shell_call_output( self, call_id: str, - output: list[generated_models.FunctionShellCallOutputContent], + output: list[response_models.FunctionShellCallOutputContent], *, status: str = "completed", max_output_length: int | None = None, - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`output_item_function_shell_call_output`. :param call_id: The call ID this output belongs to. @@ -1448,10 +1430,10 @@ async def aoutput_item_function_shell_call_output( async def aoutput_item_apply_patch_call( self, call_id: str, - operation: generated_models.ApplyPatchFileOperation, + operation: response_models.ApplyPatchFileOperation, *, status: str = "completed", - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`output_item_apply_patch_call`. :param call_id: Unique identifier for this tool call. @@ -1472,7 +1454,7 @@ async def aoutput_item_apply_patch_call_output( *, status: str = "completed", output: str | None = None, - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`output_item_apply_patch_call_output`. :param call_id: The call ID this output belongs to. @@ -1490,8 +1472,8 @@ async def aoutput_item_apply_patch_call_output( async def aoutput_item_custom_tool_call_output( self, call_id: str, - output: str | list[generated_models.FunctionAndCustomToolCallOutput], - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + output: str | list[response_models.FunctionAndCustomToolCallOutput], + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`output_item_custom_tool_call_output`. :param call_id: The call ID this output belongs to. @@ -1506,7 +1488,7 @@ async def aoutput_item_custom_tool_call_output( async def aoutput_item_mcp_approval_request( self, server_label: str, name: str, arguments: str - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`output_item_mcp_approval_request`. :param server_label: Label identifying the MCP server. @@ -1527,7 +1509,7 @@ async def aoutput_item_mcp_approval_response( approve: bool, *, reason: str | None = None, - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`output_item_mcp_approval_response`. :param approval_request_id: The request ID being responded to. @@ -1544,7 +1526,7 @@ async def aoutput_item_mcp_approval_response( async def aoutput_item_compaction( self, encrypted_content: str - ) -> AsyncIterator[generated_models.ResponseStreamEvent]: + ) -> AsyncIterator[response_models.ResponseStreamEvent]: """Async variant of :meth:`output_item_compaction`. :param encrypted_content: The encrypted compaction content. @@ -1563,7 +1545,7 @@ def _response_payload(self) -> dict[str, Any]: :returns: A materialized dict representation of the response. :rtype: dict[str, Any] """ - return _internals.materialize_generated_payload(self._response.as_dict()) + return _internals.materialize_wire_payload(self._response) def _with_output_item_defaults(self, item: dict[str, Any]) -> dict[str, Any]: """Stamp an output item dict with response-level defaults. @@ -1580,16 +1562,16 @@ def _with_output_item_defaults(self, item: dict[str, Any]) -> dict[str, Any]: stamped["agent_reference"] = self._agent_reference return stamped - def _set_terminal_fields(self, *, usage: generated_models.ResponseUsage | None) -> None: + def _set_terminal_fields(self, *, usage: response_models.ResponseUsage | None) -> None: """Set terminal fields on the response envelope (completed_at, usage). :keyword usage: Optional usage statistics to attach. - :keyword type usage: ~azure.ai.agentserver.responses.models._generated.ResponseUsage | None + :keyword type usage: ~azure.ai.extensions.openai.responses.ResponseUsage | None :rtype: None """ # B6: completed_at is non-null only for completed status - if self._response.status == "completed": - self._response.completed_at = datetime.now(timezone.utc) + if self._response.get("status") == "completed": + self._response["completed_at"] = datetime.now(timezone.utc) else: - self._response.completed_at = None # type: ignore[assignment] - self._response.usage = _internals.coerce_usage(usage) + self._response["completed_at"] = None + self._response["usage"] = _internals.coerce_usage(usage) diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_helpers.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_helpers.py index d7a2844ef9c1..1b85616fb2ce 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_helpers.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_helpers.py @@ -8,8 +8,8 @@ from copy import deepcopy from typing import Any, AsyncIterator -from ..models import _generated as generated_models -from ..models._generated import AgentReference +from azure.ai.extensions.openai import responses as response_models +from azure.ai.extensions.openai.responses import AgentReference from . import _internals from ._event_stream import ResponseEventStream from ._internals import _RESPONSE_SNAPSHOT_EVENT_TYPES @@ -37,10 +37,10 @@ def _build_events( include_progress: bool, agent_reference: AgentReference | dict[str, Any] | None, model: str | None, -) -> list[generated_models.ResponseStreamEvent]: +) -> list[response_models.ResponseStreamEvent]: """Build a minimal lifecycle event sequence for a response. - Returns ``ResponseStreamEvent`` model instances representing the standard + Returns ``ResponseStreamEvent`` wire payloads representing the standard lifecycle: ``response.created`` → (optionally) ``response.in_progress`` → ``response.completed``. @@ -48,22 +48,16 @@ def _build_events( :type response_id: str :keyword include_progress: Whether to include an ``in_progress`` event. :keyword type include_progress: bool - :keyword agent_reference: Agent reference model or metadata dict. + :keyword agent_reference: Agent reference metadata dict. :keyword type agent_reference: AgentReference | dict[str, Any] :keyword model: Optional model identifier. :keyword type model: str | None - :returns: A list of typed ``ResponseStreamEvent`` model instances. - :rtype: list[~azure.ai.agentserver.responses.models._generated.ResponseStreamEvent] + :returns: A list of typed ``ResponseStreamEvent`` wire payloads. + :rtype: list[~azure.ai.extensions.openai.responses.ResponseStreamEvent] """ - if agent_reference is None: - ref = None - elif isinstance(agent_reference, AgentReference): - ref = agent_reference - else: - ref = AgentReference(agent_reference) stream = ResponseEventStream( response_id=response_id, - agent_reference=ref, + agent_reference=agent_reference, model=model, ) stream.emit_created(status="in_progress") @@ -73,8 +67,8 @@ def _build_events( return list(stream._events) # pylint: disable=protected-access -async def _encode_sse(events: list[generated_models.ResponseStreamEvent]) -> AsyncIterator[str]: - """Encode a list of ``ResponseStreamEvent`` model instances as SSE-formatted strings. +async def _encode_sse(events: list[response_models.ResponseStreamEvent]) -> AsyncIterator[str]: + """Encode a list of ``ResponseStreamEvent`` wire payloads as SSE-formatted strings. :param events: The events to encode. :type events: list[ResponseStreamEvent] @@ -86,16 +80,12 @@ async def _encode_sse(events: list[generated_models.ResponseStreamEvent]) -> Asy def _coerce_handler_event( - handler_event: generated_models.ResponseStreamEvent | dict[str, Any], -) -> generated_models.ResponseStreamEvent: - """Coerce a handler event to a ``ResponseStreamEvent`` model instance. + handler_event: response_models.ResponseStreamEvent | dict[str, Any], +) -> response_models.ResponseStreamEvent: + """Coerce a handler event to a response stream wire payload. Handlers may yield events in any of these shapes: - - **Generated event models** (already typed):: - - ResponseCreatedEvent(response={...}, sequence_number=0) - - **Wire / SSE format** for lifecycle events:: {"type": "response.created", "response": {"id": "...", "status": "in_progress", ...}, "sequence_number": 0} @@ -104,38 +94,29 @@ def _coerce_handler_event( {"type": "response.output_text.delta", "output_index": 0, "delta": "Hello", "sequence_number": 3} - All shapes are normalised to a ``ResponseStreamEvent`` model instance - for typed internal pipeline processing. + Events are normalised to plain dict wire payloads for internal processing. - :param handler_event: The event to normalize (dict or model instance). + :param handler_event: The event to normalize. :type handler_event: ResponseStreamEvent | dict[str, Any] - :returns: A typed ``ResponseStreamEvent`` model instance. - :rtype: ~azure.ai.agentserver.responses.models._generated.ResponseStreamEvent - :raises TypeError: If the event is not a dict or a model with ``as_dict()``. + :returns: A response stream wire payload. + :rtype: ~azure.ai.extensions.openai.responses.ResponseStreamEvent + :raises TypeError: If the event is not a dict. :raises ValueError: If the event does not include a non-empty ``type``. """ - from ._internals import construct_event_model # pylint: disable=import-outside-toplevel - - # Already a typed model — return a copy via as_dict() round-trip. - if isinstance(handler_event, generated_models.ResponseStreamEvent): - return construct_event_model(handler_event.as_dict()) - if isinstance(handler_event, dict): event_data = deepcopy(handler_event) - elif hasattr(handler_event, "as_dict"): - event_data = handler_event.as_dict() else: - raise TypeError("handler events must be dictionaries or generated event models") + raise TypeError("handler events must be dictionaries") event_type = event_data.get("type") if not isinstance(event_type, str) or not event_type: raise ValueError("handler event must include a non-empty 'type'") - return construct_event_model(event_data) + return event_data def _apply_stream_event_defaults( - event: generated_models.ResponseStreamEvent, + event: response_models.ResponseStreamEvent, *, response_id: str, agent_reference: AgentReference | dict[str, Any], @@ -143,10 +124,10 @@ def _apply_stream_event_defaults( sequence_number: int | None, agent_session_id: str | None = None, conversation_id: str | None = None, -) -> generated_models.ResponseStreamEvent: - """Apply response-level defaults to a ``ResponseStreamEvent`` model instance. +) -> response_models.ResponseStreamEvent: + """Apply response-level defaults to a ``ResponseStreamEvent`` wire payload. - For lifecycle events whose ``response`` attribute carries a ``Response`` + For lifecycle events whose ``response`` key carries a ``Response`` snapshot, stamps ``id``, ``response_id``, ``object``, ``agent_reference``, ``model``, and ``agent_session_id`` using ``setdefault`` so handler-supplied values are not overwritten (except ``agent_session_id`` which is forcibly @@ -155,11 +136,11 @@ def _apply_stream_event_defaults( ``sequence_number`` is always applied at the top level of the event, because it lives on the ``ResponseStreamEvent`` base class. - :param event: The event model instance to enrich. + :param event: The event payload to enrich. :type event: ResponseStreamEvent :keyword response_id: Response ID to stamp in lifecycle-event payloads. :keyword type response_id: str - :keyword agent_reference: Agent reference model or metadata dict. + :keyword agent_reference: Agent reference metadata dict. :keyword type agent_reference: AgentReference | dict[str, Any] :keyword model: Optional model identifier. :keyword type model: str | None @@ -177,7 +158,7 @@ def _apply_stream_event_defaults( _internals.apply_common_defaults( [normalized], response_id=response_id, - agent_reference=agent_reference if agent_reference else {}, + agent_reference=agent_reference, model=model, agent_session_id=agent_session_id, conversation_id=conversation_id, @@ -200,7 +181,7 @@ def _apply_stream_event_defaults( def _extract_response_snapshot_from_events( - events: list[generated_models.ResponseStreamEvent], + events: list[response_models.ResponseStreamEvent], *, response_id: str, agent_reference: AgentReference | dict[str, Any], @@ -219,7 +200,7 @@ def _extract_response_snapshot_from_events( :type events: list[dict[str, Any]] :keyword response_id: Response ID for default stamping. :keyword type response_id: str - :keyword agent_reference: Agent reference model or metadata dict. + :keyword agent_reference: Agent reference metadata dict. :keyword type agent_reference: AgentReference | dict[str, Any] :keyword model: Optional model identifier. :keyword type model: str | None @@ -236,13 +217,16 @@ def _extract_response_snapshot_from_events( event_type = event.get("type") snapshot_source = event.get("response") if event_type in _RESPONSE_SNAPSHOT_EVENT_TYPES and isinstance(snapshot_source, MutableMapping): - if hasattr(snapshot_source, "as_dict"): - snapshot = snapshot_source.as_dict() # type: ignore[union-attr] - else: - snapshot = deepcopy(dict(snapshot_source)) + snapshot = deepcopy(snapshot_source) snapshot.setdefault("id", response_id) snapshot.setdefault("response_id", response_id) - snapshot.setdefault("agent_reference", deepcopy(agent_reference)) + existing_agent_reference = snapshot.get("agent_reference") + if ( + not isinstance(existing_agent_reference, MutableMapping) + or not existing_agent_reference + or (_internals.is_default_agent_reference(existing_agent_reference) and bool(agent_reference)) + ): + snapshot["agent_reference"] = _internals.response_agent_reference(agent_reference) snapshot.setdefault("object", "response") snapshot.setdefault("output", []) if model is not None: @@ -263,11 +247,11 @@ def _extract_response_snapshot_from_events( agent_reference=agent_reference, model=model, ) - # _build_events returns model instances — extract snapshot from the last lifecycle event. + # _build_events returns wire payloads — extract snapshot from the last lifecycle event. last_event = fallback_events[-1] - last_wire = last_event.as_dict() - fallback_snapshot = dict(last_wire.get("response", {})) + fallback_snapshot = deepcopy(last_event.get("response", {})) fallback_snapshot.setdefault("output", []) + fallback_snapshot["agent_reference"] = _internals.response_agent_reference(agent_reference) # S-038: forcibly stamp session ID on fallback snapshot if agent_session_id is not None: fallback_snapshot["agent_session_id"] = agent_session_id diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_internals.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_internals.py index 4013fdb8a62a..50896aec1882 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_internals.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_internals.py @@ -2,59 +2,53 @@ # Licensed under the MIT license. """Internal helper functions extracted from ResponseEventStream. -These are pure or near-pure functions that operate on event dicts -and generated model objects. They carry no mutable state of their own. +These are pure or near-pure functions that operate on event dicts and wire +payloads. They carry no mutable state of their own. """ from __future__ import annotations -from collections.abc import Callable, MutableMapping +from collections.abc import MutableMapping from copy import deepcopy from types import GeneratorType from typing import Any, cast -from ..models import _generated as generated_models -from ..models._generated import AgentReference +from azure.ai.extensions.openai import responses as response_models +from azure.ai.extensions.openai.responses import AgentReference # Event types whose ``response`` field is a full Response snapshot. # Only these events should carry id/response_id/object/agent_reference/model. _RESPONSE_SNAPSHOT_EVENT_TYPES: frozenset[str] = frozenset( { - generated_models.ResponseStreamEventType.RESPONSE_QUEUED.value, - generated_models.ResponseStreamEventType.RESPONSE_CREATED.value, - generated_models.ResponseStreamEventType.RESPONSE_IN_PROGRESS.value, - generated_models.ResponseStreamEventType.RESPONSE_COMPLETED.value, - generated_models.ResponseStreamEventType.RESPONSE_FAILED.value, - generated_models.ResponseStreamEventType.RESPONSE_INCOMPLETE.value, + response_models.ResponseStreamEventType.RESPONSE_QUEUED.value, + response_models.ResponseStreamEventType.RESPONSE_CREATED.value, + response_models.ResponseStreamEventType.RESPONSE_IN_PROGRESS.value, + response_models.ResponseStreamEventType.RESPONSE_COMPLETED.value, + response_models.ResponseStreamEventType.RESPONSE_FAILED.value, + response_models.ResponseStreamEventType.RESPONSE_INCOMPLETE.value, } ) +_DEFAULT_AGENT_REFERENCE: dict[str, str] = { + "type": "agent_reference", + "name": "server-default-agent", +} + # --------------------------------------------------------------------------- # Pure / near-pure helpers # --------------------------------------------------------------------------- -def construct_event_model(wire_dict: dict[str, Any]) -> generated_models.ResponseStreamEvent: - """Construct a typed ``ResponseStreamEvent`` subclass from a wire-format dict. - - Uses the discriminator-based ``__mapping__`` on the base class for - polymorphic dispatch. For example, a dict with ``"type": "response.created"`` - produces a ``ResponseCreatedEvent`` instance. +def construct_event_model(wire_dict: dict[str, Any]) -> response_models.ResponseStreamEvent: + """Return a copied ``ResponseStreamEvent`` wire payload. :param wire_dict: A wire-format event dict. :type wire_dict: dict[str, Any] - :returns: A typed event model instance. - :rtype: ~azure.ai.agentserver.responses.models._generated.ResponseStreamEvent + :returns: A copied event wire payload. + :rtype: ~azure.ai.extensions.openai.responses.ResponseStreamEvent """ - event_type = wire_dict.get("type", "") - if isinstance(event_type, str): - event_class = generated_models.ResponseStreamEvent.__mapping__.get(event_type) - if event_class is not None: - # __mapping__ values are classes; the generated type annotation is imprecise. - constructor = cast(Callable[[dict[str, Any]], generated_models.ResponseStreamEvent], event_class) - return constructor(wire_dict) - return generated_models.ResponseStreamEvent(wire_dict) + return cast(response_models.ResponseStreamEvent, deepcopy(wire_dict)) def enum_value(value: Any) -> Any: @@ -69,9 +63,9 @@ def enum_value(value: Any) -> Any: def coerce_model_mapping(value: Any) -> dict[str, Any] | None: - """Normalise a generated model, dict, or ``None`` to a plain dict copy. + """Normalise a wire mapping or ``None`` to a plain dict copy. - :param value: A generated model, a dict, or ``None``. + :param value: A wire mapping, or ``None``. :type value: Any :returns: A deep-copied plain dict, or ``None`` if *value* is ``None`` or not coercible. :rtype: dict[str, Any] | None @@ -80,14 +74,31 @@ def coerce_model_mapping(value: Any) -> dict[str, Any] | None: return None if isinstance(value, dict): return deepcopy(value) - if hasattr(value, "as_dict"): - result = value.as_dict() - if isinstance(result, dict): - return result return None -def materialize_generated_payload(value: Any) -> Any: +def response_agent_reference(agent_reference: AgentReference | dict[str, Any] | None) -> dict[str, Any]: + """Return a valid response-level agent reference wire payload. + + An empty dict is still used elsewhere as the sentinel for "do not stamp + output items", but response snapshots must carry a valid agent_reference + object. + """ + if isinstance(agent_reference, MutableMapping) and agent_reference: + return deepcopy(agent_reference) + return deepcopy(_DEFAULT_AGENT_REFERENCE) + + +def is_default_agent_reference(value: Any) -> bool: + return ( + isinstance(value, MutableMapping) + and value.get("type") == _DEFAULT_AGENT_REFERENCE["type"] + and value.get("name") == _DEFAULT_AGENT_REFERENCE["name"] + and not value.get("version") + ) + + +def materialize_wire_payload(value: Any) -> Any: """Recursively resolve generators/tuples to plain lists/dicts. :param value: A nested structure that may contain generators or tuples. @@ -96,18 +107,18 @@ def materialize_generated_payload(value: Any) -> Any: :rtype: Any """ if isinstance(value, dict): - return {key: materialize_generated_payload(item) for key, item in value.items()} + return {key: materialize_wire_payload(item) for key, item in value.items()} if isinstance(value, list): - return [materialize_generated_payload(item) for item in value] + return [materialize_wire_payload(item) for item in value] if isinstance(value, tuple): - return [materialize_generated_payload(item) for item in value] + return [materialize_wire_payload(item) for item in value] if isinstance(value, GeneratorType): - return [materialize_generated_payload(item) for item in value] + return [materialize_wire_payload(item) for item in value] return value def apply_common_defaults( - events: list[generated_models.ResponseStreamEvent], + events: list[response_models.ResponseStreamEvent], *, response_id: str, agent_reference: AgentReference | dict[str, Any] | None, @@ -125,7 +136,7 @@ def apply_common_defaults( event types carry different schemas per the contract and are left untouched. Events must use wire format where the snapshot is nested under the - ``"response"`` key (``ResponseStreamEvent`` models or equivalent dicts). + ``"response"`` key. **S-038**: ``agent_session_id`` is forcibly stamped (not ``setdefault``) on every ``response.*`` event so the resolved session ID is always @@ -134,7 +145,7 @@ def apply_common_defaults( **S-040**: ``conversation`` is forcibly stamped on every ``response.*`` event so the resolved conversation round-trips on all lifecycle events. - :param events: The list of events to mutate (``ResponseStreamEvent`` models). + :param events: The list of event payloads to mutate. :type events: list[ResponseStreamEvent] :keyword response_id: Response ID to set as default. :keyword type response_id: str @@ -158,8 +169,13 @@ def apply_common_defaults( snapshot.setdefault("id", response_id) snapshot.setdefault("response_id", response_id) snapshot.setdefault("object", "response") - if agent_reference is not None: - snapshot.setdefault("agent_reference", deepcopy(agent_reference)) + existing_agent_reference = snapshot.get("agent_reference") + if ( + not isinstance(existing_agent_reference, MutableMapping) + or not existing_agent_reference + or (is_default_agent_reference(existing_agent_reference) and bool(agent_reference)) + ): + snapshot["agent_reference"] = response_agent_reference(agent_reference) if model is not None: snapshot.setdefault("model", model) # S-038: forcibly stamp session ID on every response.* event @@ -171,8 +187,8 @@ def apply_common_defaults( def track_completed_output_item( - response: generated_models.ResponseObject, - event: generated_models.ResponseStreamEvent, + response: response_models.ResponseObject, + event: response_models.ResponseStreamEvent, ) -> None: """When an output-item-done event arrives, persist the item on the response. @@ -180,12 +196,12 @@ def track_completed_output_item( stores the item at the appropriate index in ``response.output``. :param response: The response envelope to which the completed item is attached. - :type response: ~azure.ai.agentserver.responses.models._generated.Response - :param event: The event to inspect (``ResponseStreamEvent`` model instance). + :type response: ~azure.ai.extensions.openai.responses.ResponseObject + :param event: The event to inspect. :type event: ResponseStreamEvent :rtype: None """ - if event.get("type") != generated_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_DONE.value: + if event.get("type") != response_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_DONE.value: return output_index = event.get("output_index") @@ -194,56 +210,46 @@ def track_completed_output_item( if not isinstance(output_index, int) or output_index < 0 or item_raw is None: return - # Coerce item to a plain dict for the OutputItem constructor - if hasattr(item_raw, "as_dict"): - item_dict = item_raw.as_dict() - elif isinstance(item_raw, dict): + if isinstance(item_raw, dict): item_dict = deepcopy(item_raw) else: return - output_items: list[Any] = response.output if isinstance(response.output, list) else [] - if not isinstance(response.output, list): - response.output = output_items - - try: - typed_item: Any = generated_models.OutputItem._deserialize(item_dict, []) # pylint: disable=protected-access - except Exception: # pylint: disable=broad-exception-caught - typed_item = deepcopy(item_dict) + output_items: list[Any] = response.get("output") if isinstance(response.get("output"), list) else [] + if not isinstance(response.get("output"), list): + response["output"] = output_items while len(output_items) <= output_index: output_items.append(None) - output_items[output_index] = typed_item + output_items[output_index] = deepcopy(item_dict) def coerce_usage( - usage: generated_models.ResponseUsage | dict[str, Any] | None, -) -> generated_models.ResponseUsage | None: - """Normalise a usage value to a generated ``ResponseUsage`` instance. - - :param usage: A usage dict, a ``ResponseUsage`` model, or ``None``. - :type usage: ~azure.ai.agentserver.responses.models._generated.ResponseUsage | dict[str, Any] | None - :returns: A ``ResponseUsage`` instance, or ``None`` if *usage* is ``None``. - :rtype: ~azure.ai.agentserver.responses.models._generated.ResponseUsage | None - :raises TypeError: If *usage* is not a dict or a generated ``ResponseUsage`` model. + usage: response_models.ResponseUsage | dict[str, Any] | None, +) -> dict[str, Any] | None: + """Normalise a usage value to a plain wire dict. + + :param usage: A usage dict or ``None``. + :type usage: ~azure.ai.extensions.openai.responses.ResponseUsage | dict[str, Any] | None + :returns: A usage dict, or ``None`` if *usage* is ``None``. + :rtype: dict[str, Any] | None + :raises TypeError: If *usage* is not a dict. """ if usage is None: return None if isinstance(usage, dict): - return generated_models.ResponseUsage(deepcopy(usage)) - if hasattr(usage, "as_dict"): - return generated_models.ResponseUsage(usage.as_dict()) - raise TypeError("usage must be a dict or a generated ResponseUsage model") + return deepcopy(usage) + raise TypeError("usage must be a dict") def extract_response_fields( - response: generated_models.ResponseObject, + response: response_models.ResponseObject, ) -> tuple[AgentReference | dict[str, Any] | None, str | None]: """Pull ``agent_reference`` and ``model`` from a response in one pass. :param response: The response envelope to inspect. - :type response: ~azure.ai.agentserver.responses.models.ResponseObject + :type response: ~azure.ai.extensions.openai.responses.ResponseObject :returns: Tuple of (agent_reference or None, model string or None). :rtype: tuple[~azure.ai.agentserver.responses.models.AgentReference | dict[str, Any] | None, str | None] """ @@ -252,7 +258,7 @@ def extract_response_fields( return None, None agent_reference = payload.get("agent_reference") agent_ref: AgentReference | dict[str, Any] | None = ( - dict(agent_reference) if isinstance(agent_reference, MutableMapping) else None + deepcopy(agent_reference) if isinstance(agent_reference, MutableMapping) else None ) model = payload.get("model") model_str = model if isinstance(model, str) and model else None diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_sse.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_sse.py index 9152500afa10..3f2f01fee895 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_sse.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_sse.py @@ -10,7 +10,7 @@ from datetime import date, datetime, time, timedelta from typing import Any, Mapping -from ..models._generated import ResponseStreamEvent +from azure.ai.extensions.openai.responses import ResponseStreamEvent _stream_counter_var: ContextVar[itertools.count] = ContextVar("_stream_counter_var") @@ -18,8 +18,7 @@ def _json_default(o: Any) -> Any: """JSON encoder default for datetime and bytes. - Handles datetime objects that leak through model ``as_dict()`` calls - by serializing to ISO-8601 strings (or Unix timestamps for datetime). + Serializes datetime-like values to JSON-friendly wire values. :param o: The object to encode. :type o: Any @@ -68,9 +67,7 @@ def _next_sequence_number() -> int: def _coerce_payload(event: Any) -> tuple[str, dict[str, Any]]: - """Extract and normalize event type and payload from an event object. - - Supports dict-like, model-with-``as_dict()``, and plain-object event sources. + """Extract and normalize event type and payload from an event mapping. :param event: The SSE event object to coerce. :type event: Any @@ -78,18 +75,10 @@ def _coerce_payload(event: Any) -> tuple[str, dict[str, Any]]: :rtype: tuple[str, dict[str, Any]] :raises ValueError: If the event does not include a non-empty ``type``. """ - event_type = getattr(event, "type", None) - - if isinstance(event, Mapping): - payload = dict(event) - if event_type is None: - event_type = payload.get("type") - elif hasattr(event, "as_dict"): - payload = event.as_dict() # type: ignore[assignment] - if event_type is None: - event_type = payload.get("type") - else: - payload = {key: value for key, value in vars(event).items() if not key.startswith("_")} + if not isinstance(event, Mapping): + raise TypeError("SSE event must be a mapping") + payload = event.copy() if isinstance(event, dict) else {key: value for key, value in event.items()} + event_type = payload.get("type") if not event_type: raise ValueError("SSE event must include a non-empty 'type'") @@ -101,14 +90,14 @@ def _coerce_payload(event: Any) -> tuple[str, dict[str, Any]]: def _ensure_sequence_number(event: Any, payload: dict[str, Any]) -> None: """Ensure the payload has a valid ``sequence_number``, assigning one if missing. - :param event: The original event object (used for attribute fallback). + :param event: The original event mapping. :type event: Any :param payload: The payload dict to mutate. :type payload: dict[str, Any] :rtype: None """ explicit = payload.get("sequence_number") - event_value = getattr(event, "sequence_number", None) + event_value = event.get("sequence_number") if isinstance(event, Mapping) else None candidate = explicit if explicit is not None else event_value if not isinstance(candidate, int) or candidate < 0: @@ -139,17 +128,11 @@ def _build_sse_frame(event_type: str, payload: dict[str, Any]) -> str: def encode_sse_event(event: ResponseStreamEvent) -> str: """Encode a response stream event into SSE wire format. - :param event: Generated response stream event model. - :type event: ~azure.ai.agentserver.responses.models._generated.ResponseStreamEvent + :param event: Response stream event wire payload. + :type event: ~azure.ai.extensions.openai.responses.ResponseStreamEvent :returns: Encoded SSE payload string. :rtype: str """ - if hasattr(event, "as_dict"): - wire = event.as_dict() - event_type = str(wire.get("type", "")) - _ensure_sequence_number(event, wire) - return _build_sse_frame(event_type, wire) - # Fallback for non-model event objects (e.g. plain dataclass-like) event_type, payload = _coerce_payload(event) _ensure_sequence_number(event, payload) return _build_sse_frame(event_type, {"type": event_type, **payload}) diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_state_machine.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_state_machine.py index 1d31d92815d0..eda2610fad16 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_state_machine.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_state_machine.py @@ -7,14 +7,14 @@ from copy import deepcopy from typing import Any, Mapping, MutableMapping, Sequence, cast -from ..models import _generated as generated_models +from azure.ai.extensions.openai import responses as response_models OUTPUT_ITEM_DELTA_EVENT_TYPE = "response.output_item.delta" _TERMINAL_EVENT_TYPES = { - generated_models.ResponseStreamEventType.RESPONSE_COMPLETED.value, - generated_models.ResponseStreamEventType.RESPONSE_FAILED.value, - generated_models.ResponseStreamEventType.RESPONSE_INCOMPLETE.value, + response_models.ResponseStreamEventType.RESPONSE_COMPLETED.value, + response_models.ResponseStreamEventType.RESPONSE_FAILED.value, + response_models.ResponseStreamEventType.RESPONSE_INCOMPLETE.value, } _TERMINAL_TYPE_STATUS: dict[str, set[str]] = { "response.completed": {"completed"}, @@ -22,16 +22,16 @@ "response.incomplete": {"incomplete"}, } _OUTPUT_ITEM_EVENT_TYPES = { - generated_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_ADDED.value, + response_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_ADDED.value, OUTPUT_ITEM_DELTA_EVENT_TYPE, - generated_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_DONE.value, + response_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_DONE.value, } _EVENT_STAGES = { - generated_models.ResponseStreamEventType.RESPONSE_CREATED.value: 0, - generated_models.ResponseStreamEventType.RESPONSE_IN_PROGRESS.value: 1, - generated_models.ResponseStreamEventType.RESPONSE_COMPLETED.value: 2, - generated_models.ResponseStreamEventType.RESPONSE_FAILED.value: 2, - generated_models.ResponseStreamEventType.RESPONSE_INCOMPLETE.value: 2, + response_models.ResponseStreamEventType.RESPONSE_CREATED.value: 0, + response_models.ResponseStreamEventType.RESPONSE_IN_PROGRESS.value: 1, + response_models.ResponseStreamEventType.RESPONSE_COMPLETED.value: 2, + response_models.ResponseStreamEventType.RESPONSE_FAILED.value: 2, + response_models.ResponseStreamEventType.RESPONSE_INCOMPLETE.value: 2, } @@ -62,7 +62,7 @@ def validate_next(self, event: Mapping[str, Any]) -> None: if not isinstance(event_type, str) or not event_type: raise ValueError("each lifecycle event must include a non-empty type") - if self._event_count == 0 and event_type != generated_models.ResponseStreamEventType.RESPONSE_CREATED.value: + if self._event_count == 0 and event_type != response_models.ResponseStreamEventType.RESPONSE_CREATED.value: raise ValueError("first lifecycle event must be response.created") self._event_count += 1 @@ -99,7 +99,7 @@ def validate_next(self, event: Mapping[str, Any]) -> None: output_index_raw = event.get("output_index", 0) output_index = output_index_raw if isinstance(output_index_raw, int) and output_index_raw >= 0 else 0 - if event_type == generated_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_ADDED.value: + if event_type == response_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_ADDED.value: if output_index in self._done_indexes: raise ValueError("cannot add output item after it has been marked done") self._added_indexes.add(output_index) @@ -108,7 +108,7 @@ def validate_next(self, event: Mapping[str, Any]) -> None: if output_index not in self._added_indexes: raise ValueError("output item delta/done requires a preceding output_item.added") - if event_type == generated_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_DONE.value: + if event_type == response_models.ResponseStreamEventType.RESPONSE_OUTPUT_ITEM_DONE.value: self._done_indexes.add(output_index) return @@ -175,7 +175,7 @@ def _normalize_lifecycle_events( if not normalized: normalized = [ { - "type": generated_models.ResponseStreamEventType.RESPONSE_CREATED.value, + "type": response_models.ResponseStreamEventType.RESPONSE_CREATED.value, "response": { "id": response_id, "object": "response", @@ -193,7 +193,7 @@ def _normalize_lifecycle_events( if terminal_count == 0: normalized.append( { - "type": generated_models.ResponseStreamEventType.RESPONSE_FAILED.value, + "type": response_models.ResponseStreamEventType.RESPONSE_FAILED.value, "response": { "id": response_id, "object": "response", diff --git a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_text_response.py b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_text_response.py index 5e557ff19c85..43c517d88777 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_text_response.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/azure/ai/agentserver/responses/streaming/_text_response.py @@ -19,12 +19,12 @@ from collections.abc import AsyncIterable from typing import TYPE_CHECKING, AsyncIterator, Awaitable, Callable, Union -from ..models import _generated as generated_models +from azure.ai.extensions.openai import responses as response_models from ._event_stream import ResponseEventStream if TYPE_CHECKING: from .._response_context import ResponseContext - from ..models._generated import CreateResponse, ResponseObject + from azure.ai.extensions.openai.responses import CreateResponse, ResponseObject #: Union of all accepted text sources. TextSource = Union[str, Callable[[], Union[str, Awaitable[str]]], AsyncIterable[str]] @@ -86,10 +86,10 @@ def __init__( self._text = text self._configure = configure - def __aiter__(self) -> AsyncIterator[generated_models.ResponseStreamEvent]: + def __aiter__(self) -> AsyncIterator[response_models.ResponseStreamEvent]: return self._generate() - async def _generate(self) -> AsyncIterator[generated_models.ResponseStreamEvent]: + async def _generate(self) -> AsyncIterator[response_models.ResponseStreamEvent]: stream = ResponseEventStream( response_id=self._context.response_id, request=self._request, diff --git a/sdk/agentserver/azure-ai-agentserver-responses/pyproject.toml b/sdk/agentserver/azure-ai-agentserver-responses/pyproject.toml index 8d86e6e143a1..d920fb32b427 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/pyproject.toml +++ b/sdk/agentserver/azure-ai-agentserver-responses/pyproject.toml @@ -19,6 +19,7 @@ classifiers = [ ] dependencies = [ "azure-ai-agentserver-core>=2.0.0b7", + "azure-ai-extensions-openai>=1.0.0b1", "azure-core>=1.30.0", "isodate>=0.6.1", "aiohttp>=3.10.0,<4.0.0", @@ -63,6 +64,7 @@ pythonpath = ["."] [tool.uv.sources] azure-ai-agentserver-core = { path = "../azure-ai-agentserver-core", editable = true } +azure-ai-extensions-openai = { path = "../../ai/azure-ai-extensions-openai", editable = true } azure-core = { path = "../../core/azure-core" } azure-sdk-tools = { path = "../../../eng/tools/azure-sdk-tools" } diff --git a/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_04_function_calling.py b/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_04_function_calling.py index 62a6ee7dd3b4..536994d34cdd 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_04_function_calling.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_04_function_calling.py @@ -46,16 +46,14 @@ ResponseEventStream, ResponsesAgentServerHost, ) -from azure.ai.agentserver.responses.models import FunctionCallOutputItemParam - app = ResponsesAgentServerHost() async def _find_function_call_output(context: ResponseContext) -> str | None: """Return the output string from the first function_call_output item, or None.""" for item in await context.get_input_items(): - if isinstance(item, FunctionCallOutputItemParam): - output = item.output + if item.get("type") == "function_call_output": + output = item.get("output") if isinstance(output, str): return output return None diff --git a/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_07_customization.py b/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_07_customization.py index b01485ea29de..e6452884a59a 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_07_customization.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_07_customization.py @@ -7,7 +7,7 @@ - ``ResponsesServerOptions`` for default model, SSE keep-alive, and shutdown grace period. - ``log_level`` on the host for verbose logging. - - A handler that relies on ``request.model``, which is automatically + - A handler that relies on ``request["model"]``, which is automatically filled from ``default_model`` when the client omits it. Usage:: @@ -53,7 +53,7 @@ async def handler(request: CreateResponse, context: ResponseContext, cancellation_signal: asyncio.Event): """Echo handler that reports which model is being used.""" input_text = await context.get_input_text() - return TextResponse(context, request, text=f"[model={request.model}] Echo: {input_text}") + return TextResponse(context, request, text=f"[model={request.get('model')}] Echo: {input_text}") def main() -> None: diff --git a/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_10_streaming_upstream.py b/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_10_streaming_upstream.py index 060480873a2a..272ee0462320 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_10_streaming_upstream.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_10_streaming_upstream.py @@ -67,17 +67,17 @@ def _build_response_snapshot(request: CreateResponse, context: ResponseContext) "id": context.response_id, "object": "response", "status": "in_progress", - "model": request.model or "", + "model": request.get("model") or "", "output": [], } - if request.metadata is not None: - snapshot["metadata"] = request.metadata - if request.background is not None: - snapshot["background"] = request.background - if request.previous_response_id is not None: - snapshot["previous_response_id"] = request.previous_response_id + if request.get("metadata") is not None: + snapshot["metadata"] = request["metadata"] + if request.get("background") is not None: + snapshot["background"] = request["background"] + if request.get("previous_response_id") is not None: + snapshot["previous_response_id"] = request["previous_response_id"] # Normalize conversation to ConversationReference form. - conv = request.conversation + conv = request.get("conversation") if isinstance(conv, str): snapshot["conversation"] = {"id": conv} elif isinstance(conv, dict) and conv.get("id"): @@ -100,7 +100,7 @@ async def handler( # Build the upstream request — translate every input item. # Both model stacks share the same JSON wire contract, so # serializing our Item to dict round-trips to the OpenAI SDK. - input_items = [item.as_dict() for item in await context.get_input_items()] + input_items = [dict(item) for item in await context.get_input_items()] # This handler owns the response lifecycle — construct the # response snapshot directly instead of forwarding the upstream's. @@ -119,7 +119,7 @@ async def handler( upstream_failed = False async with await upstream.responses.create( - model=request.model or "gpt-4o-mini", + model=request.get("model") or "gpt-4o-mini", input=input_items, # type: ignore[arg-type] stream=True, ) as upstream_stream: diff --git a/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_11_non_streaming_upstream.py b/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_11_non_streaming_upstream.py index 63239e29c716..f068f1d12e99 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_11_non_streaming_upstream.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_11_non_streaming_upstream.py @@ -72,11 +72,11 @@ async def handler( # Build the upstream request — translate every input item. # Both model stacks share the same JSON wire contract, so # serializing our Item to dict round-trips to the OpenAI SDK. - input_items = [item.as_dict() for item in await context.get_input_items()] + input_items = [dict(item) for item in await context.get_input_items()] # Call upstream without streaming and get the complete response. result = await upstream.responses.create( - model=request.model or "gpt-4o-mini", + model=request.get("model") or "gpt-4o-mini", input=input_items, # type: ignore[arg-type] ) diff --git a/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_13_image_input.py b/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_13_image_input.py index 0f85d2caec61..9bb59b0a1ef0 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_13_image_input.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_13_image_input.py @@ -54,7 +54,6 @@ TextResponse, ) from azure.ai.agentserver.responses._data_url import get_media_type, is_data_url, try_decode_bytes -from azure.ai.agentserver.responses.models import ItemMessage, MessageContentInputImageContent app = ResponsesAgentServerHost() @@ -63,10 +62,10 @@ def _extract_images(items): """Extract ``MessageContentInputImageContent`` from expanded input items.""" images = [] for item in items: - if not isinstance(item, ItemMessage): + if item.get("type") != "message": continue - for content in item.content or []: - if isinstance(content, MessageContentInputImageContent): + for content in item.get("content") or []: + if isinstance(content, dict) and content.get("type") == "input_image": images.append(content) return images @@ -78,7 +77,7 @@ async def url_handler(request: CreateResponse, context: ResponseContext): items = await context.get_input_items() images = _extract_images(items) - urls = [img.image_url for img in images if img.image_url and not is_data_url(img.image_url)] + urls = [img["image_url"] for img in images if img.get("image_url") and not is_data_url(img["image_url"])] return TextResponse(context, request, text=f"Received {len(urls)} image URL(s): {', '.join(urls)}") @@ -91,9 +90,10 @@ async def base64_handler(request: CreateResponse, context: ResponseContext): results = [] for img in images: - if img.image_url and is_data_url(img.image_url): - raw = try_decode_bytes(img.image_url) - media = get_media_type(img.image_url) + image_url = img.get("image_url") + if image_url and is_data_url(image_url): + raw = try_decode_bytes(image_url) + media = get_media_type(image_url) size = len(raw) if raw else 0 results.append(f"{media or 'unknown'} ({size} bytes)") return TextResponse(context, request, text=f"Decoded {len(results)} image(s): {'; '.join(results)}") @@ -106,7 +106,7 @@ async def file_id_handler(request: CreateResponse, context: ResponseContext): items = await context.get_input_items() images = _extract_images(items) - file_ids = [img.file_id for img in images if img.file_id] + file_ids = [img["file_id"] for img in images if img.get("file_id")] return TextResponse(context, request, text=f"Received {len(file_ids)} file ID(s): {', '.join(file_ids)}") diff --git a/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_14_file_inputs.py b/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_14_file_inputs.py index 6636d3a3f829..aadd47c22752 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_14_file_inputs.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_14_file_inputs.py @@ -51,7 +51,6 @@ TextResponse, ) from azure.ai.agentserver.responses._data_url import get_media_type, is_data_url, try_decode_bytes -from azure.ai.agentserver.responses.models import ItemMessage, MessageContentInputFileContent app = ResponsesAgentServerHost() @@ -60,10 +59,10 @@ def _extract_files(items): """Extract ``MessageContentInputFileContent`` from expanded input items.""" files = [] for item in items: - if not isinstance(item, ItemMessage): + if item.get("type") != "message": continue - for content in item.content or []: - if isinstance(content, MessageContentInputFileContent): + for content in item.get("content") or []: + if isinstance(content, dict) and content.get("type") == "input_file": files.append(content) return files @@ -77,9 +76,10 @@ async def base64_handler(request: CreateResponse, context: ResponseContext): results = [] for f in files: - if f.file_data and is_data_url(f.file_data): - raw = try_decode_bytes(f.file_data) - media = get_media_type(f.file_data) + file_data = f.get("file_data") + if file_data and is_data_url(file_data): + raw = try_decode_bytes(file_data) + media = get_media_type(file_data) size = len(raw) if raw else 0 results.append(f"{media or 'unknown'} ({size} bytes)") return TextResponse(context, request, text=f"Decoded {len(results)} file(s): {'; '.join(results)}") @@ -92,7 +92,7 @@ async def url_handler(request: CreateResponse, context: ResponseContext): items = await context.get_input_items() files = _extract_files(items) - urls = [f.file_url for f in files if f.file_url] + urls = [f["file_url"] for f in files if f.get("file_url")] return TextResponse(context, request, text=f"Received {len(urls)} file URL(s): {', '.join(urls)}") @@ -103,7 +103,7 @@ async def file_id_handler(request: CreateResponse, context: ResponseContext): items = await context.get_input_items() files = _extract_files(items) - file_ids = [f.file_id for f in files if f.file_id] + file_ids = [f["file_id"] for f in files if f.get("file_id")] return TextResponse(context, request, text=f"Received {len(file_ids)} file ID(s): {', '.join(file_ids)}") diff --git a/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_16_structured_outputs.py b/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_16_structured_outputs.py index d39b2dde18c5..141bb587f47f 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_16_structured_outputs.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/samples/sample_16_structured_outputs.py @@ -23,7 +23,7 @@ ResponseEventStream, ResponsesAgentServerHost, ) -from azure.ai.agentserver.responses.models._generated import StructuredOutputsOutputItem +from azure.ai.extensions.openai.responses import StructuredOutputsOutputItem app = ResponsesAgentServerHost() diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/contract/test_bg_isolation_propagation.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/contract/test_bg_isolation_propagation.py index d9ce0b6f30d8..7a6ab8fd4a59 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/contract/test_bg_isolation_propagation.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/contract/test_bg_isolation_propagation.py @@ -21,7 +21,7 @@ from azure.ai.agentserver.responses import ResponsesAgentServerHost from azure.ai.agentserver.responses._response_context import PlatformContext -from azure.ai.agentserver.responses.models._generated import OutputItem, ResponseObject +from azure.ai.extensions.openai.responses import OutputItem, ResponseObject from azure.ai.agentserver.responses.store._memory import InMemoryResponseProvider from azure.ai.agentserver.responses.streaming import ResponseEventStream from tests._helpers import poll_until diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/contract/test_response_invariants.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/contract/test_response_invariants.py index ca77a6334f26..09e85d238c09 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/contract/test_response_invariants.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/contract/test_response_invariants.py @@ -611,18 +611,12 @@ def test_output_item__agent_reference_stamped_on_item() -> None: def _handler_with_agent_ref(request: Any, context: Any, cancellation_signal: Any): """Handler that creates a stream with agent_reference and emits a message item.""" - agent_ref = None - if hasattr(request, "agent_reference") and request.agent_reference is not None: - agent_ref_raw = request.agent_reference - if hasattr(agent_ref_raw, "as_dict"): - agent_ref = agent_ref_raw.as_dict() - elif isinstance(agent_ref_raw, dict): - agent_ref = agent_ref_raw + agent_ref = request.get("agent_reference") if isinstance(request, dict) else None async def _events(): stream = ResponseEventStream( response_id=context.response_id, - model=getattr(request, "model", None), + model=request.get("model") if isinstance(request, dict) else None, agent_reference=agent_ref, ) yield stream.emit_created() diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/contract/test_stream_event_lifecycle.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/contract/test_stream_event_lifecycle.py index 4b692142b993..e90b4b96f179 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/contract/test_stream_event_lifecycle.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/contract/test_stream_event_lifecycle.py @@ -27,7 +27,7 @@ from starlette.testclient import TestClient from azure.ai.agentserver.responses import ResponsesAgentServerHost -from azure.ai.agentserver.responses.models._generated import OutputItem, ResponseObject +from azure.ai.extensions.openai.responses import OutputItem, ResponseObject from azure.ai.agentserver.responses.store._base import ( ResponseProviderProtocol, ResponseStreamProviderProtocol, diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/contract/test_stream_provider_fallback.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/contract/test_stream_provider_fallback.py index e7f7008594dd..53adda482aec 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/contract/test_stream_provider_fallback.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/contract/test_stream_provider_fallback.py @@ -19,7 +19,7 @@ from starlette.testclient import TestClient from azure.ai.agentserver.responses import ResponsesAgentServerHost -from azure.ai.agentserver.responses.models._generated import OutputItem, ResponseObject +from azure.ai.extensions.openai.responses import OutputItem, ResponseObject from azure.ai.agentserver.responses.store._base import ( ResponseProviderProtocol, ResponseStreamProviderProtocol, diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/e2e/test_proxy_e2e.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/e2e/test_proxy_e2e.py index e6d14f72a6f6..fca6b2f28400 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/e2e/test_proxy_e2e.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/e2e/test_proxy_e2e.py @@ -96,7 +96,7 @@ def _emit_text_only_handler(text: str): def handler(request: CreateResponse, context: ResponseContext, cancellation_signal: Any): async def _events(): - stream = ResponseEventStream(response_id=context.response_id, model=request.model) + stream = ResponseEventStream(response_id=context.response_id, model=request.get("model")) yield stream.emit_created() yield stream.emit_in_progress() @@ -119,7 +119,7 @@ def _emit_multi_output_handler(request: CreateResponse, context: ResponseContext """Emit 3 output items: reasoning + function_call + text message.""" async def _events(): - stream = ResponseEventStream(response_id=context.response_id, model=request.model) + stream = ResponseEventStream(response_id=context.response_id, model=request.get("model")) yield stream.emit_created() yield stream.emit_in_progress() @@ -162,7 +162,7 @@ def _emit_failed_handler(request: CreateResponse, context: ResponseContext, canc """Emit created, in_progress, then failed.""" async def _events(): - stream = ResponseEventStream(response_id=context.response_id, model=request.model) + stream = ResponseEventStream(response_id=context.response_id, model=request.get("model")) yield stream.emit_created() yield stream.emit_in_progress() yield stream.emit_failed(code="server_error", message="Backend processing error") @@ -180,7 +180,7 @@ def _make_streaming_proxy_handler(upstream_client: openai.AsyncOpenAI): def handler(request: CreateResponse, context: ResponseContext, cancellation_signal: Any): async def _events(): - stream = ResponseEventStream(response_id=context.response_id, model=request.model) + stream = ResponseEventStream(response_id=context.response_id, model=request.get("model")) yield stream.emit_created() yield stream.emit_in_progress() @@ -193,7 +193,7 @@ async def _events(): full_text: list[str] = [] async with await upstream_client.responses.create( - model=request.model or "gpt-4o-mini", + model=request.get("model") or "gpt-4o-mini", input=user_text, stream=True, ) as upstream_stream: @@ -221,7 +221,7 @@ async def _events(): user_text = await context.get_input_text() or "hello" result = await upstream_client.responses.create( - model=request.model or "gpt-4o-mini", + model=request.get("model") or "gpt-4o-mini", input=user_text, ) @@ -233,7 +233,7 @@ async def _events(): if part.type == "output_text": output_text += part.text - stream = ResponseEventStream(response_id=context.response_id, model=request.model) + stream = ResponseEventStream(response_id=context.response_id, model=request.get("model")) yield stream.emit_created() yield stream.emit_in_progress() @@ -257,7 +257,7 @@ def _make_upstream_integration_handler(upstream_client: openai.AsyncOpenAI): def handler(request: CreateResponse, context: ResponseContext, cancellation_signal: Any): async def _events(): - stream = ResponseEventStream(response_id=context.response_id, model=request.model) + stream = ResponseEventStream(response_id=context.response_id, model=request.get("model")) yield stream.emit_created() yield stream.emit_in_progress() @@ -272,7 +272,7 @@ async def _events(): text_builder = None async with await upstream_client.responses.create( - model=request.model or "gpt-4o-mini", + model=request.get("model") or "gpt-4o-mini", input=user_text, stream=True, ) as upstream_stream: diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/e2e/test_sample_e2e.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/e2e/test_sample_e2e.py index f198fdfb905b..6f8ce66f9cdc 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/e2e/test_sample_e2e.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/e2e/test_sample_e2e.py @@ -19,8 +19,7 @@ ResponsesServerOptions, TextResponse, ) -from azure.ai.agentserver.responses.models import FunctionCallOutputItemParam, ItemMessage -from azure.ai.agentserver.responses.models._generated import StructuredOutputsOutputItem +from azure.ai.extensions.openai.responses import StructuredOutputsOutputItem # --------------------------------------------------------------------------- # Helpers @@ -62,6 +61,18 @@ def _collect_stream_events(response: Any) -> list[dict[str, Any]]: return events +def _is_item_type(item: Any, type_value: str) -> bool: + return isinstance(item, dict) and item.get("type") == type_value + + +def _message_texts(item: dict[str, Any]) -> list[str]: + return [ + part["text"] + for part in item.get("content") or [] + if isinstance(part, dict) and isinstance(part.get("text"), str) + ] + + def _post_json(client: TestClient, payload: dict[str, Any]) -> Any: return client.post("/responses", json=payload) @@ -245,7 +256,7 @@ def test_sample3_greeting_includes_input() -> None: async def _sample4_handler(request: CreateResponse, context: ResponseContext, cancellation_signal: asyncio.Event): """Function-calling handler: uses convenience generators for both turns.""" items = await context.get_input_items() - has_fn_output = any(isinstance(item, FunctionCallOutputItemParam) for item in items) + has_fn_output = any(_is_item_type(item, "function_call_output") for item in items) stream = ResponseEventStream(response_id=context.response_id, request=request) yield stream.emit_created() @@ -255,8 +266,8 @@ async def _sample4_handler(request: CreateResponse, context: ResponseContext, ca # Second turn: extract function output and echo it as text fn_output_text = "" for item in items: - if isinstance(item, FunctionCallOutputItemParam): - fn_output_text = item.output or "" + if _is_item_type(item, "function_call_output"): + fn_output_text = item.get("output") or "" break for event in stream.output_item_message(f"The weather is: {fn_output_text}"): yield event @@ -316,10 +327,10 @@ def test_sample4_turn2_returns_weather_text() -> None: async def _sample5_handler(request: CreateResponse, context: ResponseContext, cancellation_signal: asyncio.Event): """Study tutor handler using TextResponse: welcome on first turn, references previous_response_id on second turn.""" - has_previous = request.previous_response_id is not None and str(request.previous_response_id).strip() != "" + has_previous = request.get("previous_response_id") is not None and str(request.get("previous_response_id")).strip() != "" user_text = await context.get_input_text() if has_previous: - text = f"Building on our previous discussion ({request.previous_response_id}): {user_text}" + text = f"Building on our previous discussion ({request.get('previous_response_id')}): {user_text}" else: text = f"Welcome! I'm your study tutor. You asked: {user_text}" @@ -422,7 +433,7 @@ def _sample7_handler(request: CreateResponse, context: ResponseContext, cancella return TextResponse( context, request, - text=lambda: f"[model={request.model}]", + text=lambda: f"[model={request.get('model')}]", ) @@ -625,7 +636,7 @@ async def _events(): "id": context.response_id, "object": "response", "status": "in_progress", - "model": request.model or "", + "model": request.get("model") or "", "output": [], } @@ -787,15 +798,11 @@ async def _item_ref_echo_handler(request: CreateResponse, context: ResponseConte items = await context.get_input_items() summaries = [] for item in items: - if isinstance(item, ItemMessage): - texts = [] - for part in getattr(item, "content", None) or []: - t = getattr(part, "text", None) - if t: - texts.append(t) + if _is_item_type(item, "message"): + texts = _message_texts(item) summaries.append({"type": "message", "text": " ".join(texts)}) else: - summaries.append({"type": getattr(item, "type", "unknown")}) + summaries.append({"type": item.get("type", "unknown") if isinstance(item, dict) else "unknown"}) return TextResponse(context, request, text=lambda: json.dumps(summaries)) @@ -950,7 +957,7 @@ async def _unresolved_handler( items = await context.get_input_items(resolve_references=False) summaries = [] for item in items: - item_type = getattr(item, "type", "unknown") + item_type = item.get("type", "unknown") if isinstance(item, dict) else "unknown" summaries.append({"type": item_type}) return TextResponse(context, request, text=lambda: json.dumps(summaries)) @@ -1111,53 +1118,50 @@ def test_sample12_image_gen_non_streaming_returns_result() -> None: async def _image_url_handler(request: CreateResponse, context: ResponseContext, cancellation_signal: asyncio.Event): from azure.ai.agentserver.responses._data_url import is_data_url - from azure.ai.agentserver.responses.models import MessageContentInputImageContent items = await context.get_input_items() images = [] for item in items: - if not isinstance(item, ItemMessage): + if not _is_item_type(item, "message"): continue - for content in item.content or []: - if isinstance(content, MessageContentInputImageContent): + for content in item.get("content") or []: + if isinstance(content, dict) and content.get("type") == "input_image": images.append(content) - urls = [img.image_url for img in images if img.image_url and not is_data_url(img.image_url)] + urls = [img["image_url"] for img in images if img.get("image_url") and not is_data_url(img["image_url"])] return TextResponse(context, request, text=f"URLs: {', '.join(urls)}") async def _image_base64_handler(request: CreateResponse, context: ResponseContext, cancellation_signal: asyncio.Event): from azure.ai.agentserver.responses._data_url import get_media_type, is_data_url, try_decode_bytes - from azure.ai.agentserver.responses.models import MessageContentInputImageContent items = await context.get_input_items() images = [] for item in items: - if not isinstance(item, ItemMessage): + if not _is_item_type(item, "message"): continue - for content in item.content or []: - if isinstance(content, MessageContentInputImageContent): + for content in item.get("content") or []: + if isinstance(content, dict) and content.get("type") == "input_image": images.append(content) results = [] for img in images: - if img.image_url and is_data_url(img.image_url): - raw = try_decode_bytes(img.image_url) - media = get_media_type(img.image_url) + image_url = img.get("image_url") + if image_url and is_data_url(image_url): + raw = try_decode_bytes(image_url) + media = get_media_type(image_url) results.append(f"{media} ({len(raw)} bytes)") return TextResponse(context, request, text=f"Decoded: {'; '.join(results)}") async def _image_file_id_handler(request: CreateResponse, context: ResponseContext, cancellation_signal: asyncio.Event): - from azure.ai.agentserver.responses.models import MessageContentInputImageContent - items = await context.get_input_items() images = [] for item in items: - if not isinstance(item, ItemMessage): + if not _is_item_type(item, "message"): continue - for content in item.content or []: - if isinstance(content, MessageContentInputImageContent): + for content in item.get("content") or []: + if isinstance(content, dict) and content.get("type") == "input_image": images.append(content) - file_ids = [img.file_id for img in images if img.file_id] + file_ids = [img["file_id"] for img in images if img.get("file_id")] return TextResponse(context, request, text=f"File IDs: {', '.join(file_ids)}") @@ -1208,52 +1212,48 @@ def test_sample13_image_input_file_id_handler() -> None: async def _file_base64_handler(request: CreateResponse, context: ResponseContext, cancellation_signal: asyncio.Event): from azure.ai.agentserver.responses._data_url import get_media_type, is_data_url, try_decode_bytes - from azure.ai.agentserver.responses.models import ItemMessage, MessageContentInputFileContent items = await context.get_input_items() files = [] for item in items: - if not isinstance(item, ItemMessage): + if not _is_item_type(item, "message"): continue - for content in item.content or []: - if isinstance(content, MessageContentInputFileContent): + for content in item.get("content") or []: + if isinstance(content, dict) and content.get("type") == "input_file": files.append(content) results = [] for f in files: - if f.file_data and is_data_url(f.file_data): - raw = try_decode_bytes(f.file_data) - media = get_media_type(f.file_data) + file_data = f.get("file_data") + if file_data and is_data_url(file_data): + raw = try_decode_bytes(file_data) + media = get_media_type(file_data) results.append(f"{media} ({len(raw)} bytes)") return TextResponse(context, request, text=f"Decoded: {'; '.join(results)}") async def _file_url_handler(request: CreateResponse, context: ResponseContext, cancellation_signal: asyncio.Event): - from azure.ai.agentserver.responses.models import ItemMessage, MessageContentInputFileContent - items = await context.get_input_items() files = [] for item in items: - if not isinstance(item, ItemMessage): + if not _is_item_type(item, "message"): continue - for content in item.content or []: - if isinstance(content, MessageContentInputFileContent): + for content in item.get("content") or []: + if isinstance(content, dict) and content.get("type") == "input_file": files.append(content) - urls = [f.file_url for f in files if f.file_url] + urls = [f["file_url"] for f in files if f.get("file_url")] return TextResponse(context, request, text=f"URLs: {', '.join(urls)}") async def _file_id_handler(request: CreateResponse, context: ResponseContext, cancellation_signal: asyncio.Event): - from azure.ai.agentserver.responses.models import ItemMessage, MessageContentInputFileContent - items = await context.get_input_items() files = [] for item in items: - if not isinstance(item, ItemMessage): + if not _is_item_type(item, "message"): continue - for content in item.content or []: - if isinstance(content, MessageContentInputFileContent): + for content in item.get("content") or []: + if isinstance(content, dict) and content.get("type") == "input_file": files.append(content) - file_ids = [f.file_id for f in files if f.file_id] + file_ids = [f["file_id"] for f in files if f.get("file_id")] return TextResponse(context, request, text=f"File IDs: {', '.join(file_ids)}") diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/interop/test_openai_wire_compliance.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/interop/test_openai_wire_compliance.py index 693ffb4cba52..2e7984ee9ec6 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/interop/test_openai_wire_compliance.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/interop/test_openai_wire_compliance.py @@ -43,7 +43,7 @@ def _capture_handler(request: CreateResponse, context: ResponseContext, cancella _captured["request"] = request async def _events(): - stream = ResponseEventStream(response_id=context.response_id, model=request.model) + stream = ResponseEventStream(response_id=context.response_id, model=request.get("model")) yield stream.emit_created() yield stream.emit_in_progress() @@ -252,10 +252,10 @@ def test_c_func_01__function_tool_without_strict_accepted() -> None: }] } """) - assert request.tools is not None - assert len(request.tools) == 1 - assert request.tools[0].get("type") == "function" - assert request.tools[0].get("name") == "get_weather" + assert request.get("tools") is not None + assert len(request.get("tools")) == 1 + assert request.get("tools")[0].get("type") == "function" + assert request.get("tools")[0].get("name") == "get_weather" def test_c_func_02__function_tool_without_parameters_accepted() -> None: @@ -268,9 +268,9 @@ def test_c_func_02__function_tool_without_parameters_accepted() -> None: }] } """) - assert request.tools is not None - assert len(request.tools) == 1 - assert request.tools[0].get("name") == "no_params_tool" + assert request.get("tools") is not None + assert len(request.get("tools")) == 1 + assert request.get("tools")[0].get("name") == "no_params_tool" def test_c_func_01_02__function_tool_minimal_form_accepted() -> None: @@ -280,9 +280,9 @@ def test_c_func_01_02__function_tool_minimal_form_accepted() -> None: "tools": [{ "type": "function", "name": "minimal_tool" }] } """) - assert request.tools is not None - assert len(request.tools) == 1 - assert request.tools[0].get("name") == "minimal_tool" + assert request.get("tools") is not None + assert len(request.get("tools")) == 1 + assert request.get("tools")[0].get("name") == "minimal_tool" def test_c_func_01__function_tool_with_strict_null_accepted() -> None: @@ -297,8 +297,8 @@ def test_c_func_01__function_tool_with_strict_null_accepted() -> None: }] } """) - assert request.tools is not None - assert len(request.tools) == 1 + assert request.get("tools") is not None + assert len(request.get("tools")) == 1 def test_c_func_01__function_tool_with_strict_true_accepted() -> None: @@ -313,8 +313,8 @@ def test_c_func_01__function_tool_with_strict_true_accepted() -> None: }] } """) - assert request.tools is not None - assert len(request.tools) == 1 + assert request.get("tools") is not None + assert len(request.get("tools")) == 1 # ═══════════════════════════════════════════════════════════════════ @@ -492,27 +492,27 @@ def test_input_mixed_types_all_deserialize() -> None: def test_create_response_model() -> None: req = _send_and_capture('{"model": "gpt-4o-mini"}') - assert req.model == "gpt-4o-mini" + assert req["model"] == "gpt-4o-mini" def test_create_response_instructions() -> None: req = _send_and_capture('{"model": "test", "instructions": "Be helpful"}') - assert req.instructions == "Be helpful" + assert req["instructions"] == "Be helpful" def test_create_response_temperature() -> None: req = _send_and_capture('{"model": "test", "temperature": 0.7}') - assert abs(req.temperature - 0.7) < 0.001 + assert abs(req["temperature"] - 0.7) < 0.001 def test_create_response_top_p() -> None: req = _send_and_capture('{"model": "test", "top_p": 0.9}') - assert abs(req.top_p - 0.9) < 0.001 + assert abs(req["top_p"] - 0.9) < 0.001 def test_create_response_max_output_tokens() -> None: req = _send_and_capture('{"model": "test", "max_output_tokens": 1024}') - assert req.max_output_tokens == 1024 + assert req["max_output_tokens"] == 1024 def test_create_response_previous_response_id() -> None: @@ -520,46 +520,46 @@ def test_create_response_previous_response_id() -> None: valid_id = IdGenerator.new_response_id() req = _send_and_capture(f'{{"model": "test", "previous_response_id": "{valid_id}"}}') - assert req.previous_response_id == valid_id + assert req["previous_response_id"] == valid_id def test_create_response_store() -> None: req = _send_and_capture('{"model": "test", "store": false}') - assert req.store is False + assert req["store"] is False def test_create_response_metadata() -> None: req = _send_and_capture('{"model": "test", "metadata": {"key": "value"}}') - assert req.metadata is not None - assert req.metadata.get("key") == "value" + assert req.get("metadata") is not None + assert req["metadata"].get("key") == "value" def test_create_response_parallel_tool_calls() -> None: req = _send_and_capture('{"model": "test", "parallel_tool_calls": false}') - assert req.parallel_tool_calls is False + assert req["parallel_tool_calls"] is False def test_create_response_truncation() -> None: req = _send_and_capture('{"model": "test", "truncation": "auto"}') - assert req.truncation is not None + assert req.get("truncation") is not None def test_create_response_reasoning() -> None: req = _send_and_capture('{"model": "test", "reasoning": {"effort": "high"}}') - assert req.reasoning is not None + assert req.get("reasoning") is not None def test_create_response_tool_choice_auto() -> None: req = _send_and_capture('{"model": "test", "tool_choice": "auto"}') tc = get_tool_choice_expanded(req) assert tc is not None - assert tc.get("type") == "auto" or tc.get("mode") == "auto" + assert tc == {"type": "allowed_tools", "mode": "auto", "tools": []} def test_create_response_tool_choice_required() -> None: req = _send_and_capture('{"model": "test", "tool_choice": "required"}') tc = get_tool_choice_expanded(req) - assert tc is not None + assert tc == {"type": "allowed_tools", "mode": "required", "tools": []} def test_create_response_tool_choice_none() -> None: @@ -581,27 +581,27 @@ def test_create_response_tools_web_search() -> None: req = _send_and_capture(""" {"model": "test", "tools": [{"type": "web_search_preview"}]} """) - assert req.tools is not None - assert len(req.tools) == 1 - assert req.tools[0].get("type") == "web_search_preview" + assert req.get("tools") is not None + assert len(req["tools"]) == 1 + assert req["tools"][0].get("type") == "web_search_preview" def test_create_response_tools_file_search() -> None: req = _send_and_capture(""" {"model": "test", "tools": [{"type": "file_search", "vector_store_ids": ["vs_abc"]}]} """) - assert req.tools is not None - assert len(req.tools) == 1 - assert req.tools[0].get("type") == "file_search" + assert req.get("tools") is not None + assert len(req["tools"]) == 1 + assert req["tools"][0].get("type") == "file_search" def test_create_response_tools_code_interpreter() -> None: req = _send_and_capture(""" {"model": "test", "tools": [{"type": "code_interpreter"}]} """) - assert req.tools is not None - assert len(req.tools) == 1 - assert req.tools[0].get("type") == "code_interpreter" + assert req.get("tools") is not None + assert len(req["tools"]) == 1 + assert req["tools"][0].get("type") == "code_interpreter" def test_create_response_stream() -> None: @@ -697,11 +697,11 @@ def test_full_payload_all_shorthands_and_minimal_forms() -> None: ] } """) - assert req.model == "gpt-4o" - assert req.instructions == "Be helpful" - assert abs(req.temperature - 0.5) < 0.001 - assert req.max_output_tokens == 500 - assert req.store is True + assert req["model"] == "gpt-4o" + assert req["instructions"] == "Be helpful" + assert abs(req["temperature"] - 0.5) < 0.001 + assert req["max_output_tokens"] == 500 + assert req["store"] is True items = get_input_expanded(req) assert len(items) == 1 @@ -710,8 +710,8 @@ def test_full_payload_all_shorthands_and_minimal_forms() -> None: tc = get_tool_choice_expanded(req) assert tc is not None - assert req.tools is not None - assert len(req.tools) == 1 + assert req.get("tools") is not None + assert len(req["tools"]) == 1 def test_multi_turn_mixed_shorthand_and_full_form() -> None: diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/interop/test_sdk_round_trip.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/interop/test_sdk_round_trip.py index 538ba8b1f972..126599e61615 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/interop/test_sdk_round_trip.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/interop/test_sdk_round_trip.py @@ -91,7 +91,7 @@ def wrapper(request, context, cancellation_signal): def _text_message_handler(text: str = "Hello, world!"): def handler(request, context, cancellation_signal): async def events(): - s = ResponseEventStream(response_id=context.response_id, model=request.model) + s = ResponseEventStream(response_id=context.response_id, model=request.get("model")) yield s.emit_created() for ev in s.output_item_message(text): yield ev @@ -109,7 +109,7 @@ def _function_call_handler( ): def handler(request, context, cancellation_signal): async def events(): - s = ResponseEventStream(response_id=context.response_id, model=request.model) + s = ResponseEventStream(response_id=context.response_id, model=request.get("model")) yield s.emit_created() for ev in s.output_item_function_call(name, call_id, arguments): yield ev @@ -126,7 +126,7 @@ def _function_call_output_handler( ): def handler(request, context, cancellation_signal): async def events(): - s = ResponseEventStream(response_id=context.response_id, model=request.model) + s = ResponseEventStream(response_id=context.response_id, model=request.get("model")) yield s.emit_created() for ev in s.output_item_function_call_output(call_id, output): yield ev @@ -140,7 +140,7 @@ async def events(): def _reasoning_handler(summary: str = "Let me think step by step..."): def handler(request, context, cancellation_signal): async def events(): - s = ResponseEventStream(response_id=context.response_id, model=request.model) + s = ResponseEventStream(response_id=context.response_id, model=request.get("model")) yield s.emit_created() for ev in s.output_item_reasoning_item(summary): yield ev @@ -154,7 +154,7 @@ async def events(): def _file_search_handler(): def handler(request, context, cancellation_signal): async def events(): - s = ResponseEventStream(response_id=context.response_id, model=request.model) + s = ResponseEventStream(response_id=context.response_id, model=request.get("model")) yield s.emit_created() b = s.add_output_item_file_search_call() yield b.emit_added() @@ -179,7 +179,7 @@ def _web_search_handler(): def handler(request, context, cancellation_signal): async def events(): - s = ResponseEventStream(response_id=context.response_id, model=request.model) + s = ResponseEventStream(response_id=context.response_id, model=request.get("model")) yield s.emit_created() b = s.add_output_item_web_search_call() # Override the added item to include a valid action. @@ -203,7 +203,7 @@ async def events(): def _code_interpreter_handler(code: str = "print('hello')"): def handler(request, context, cancellation_signal): async def events(): - s = ResponseEventStream(response_id=context.response_id, model=request.model) + s = ResponseEventStream(response_id=context.response_id, model=request.get("model")) yield s.emit_created() b = s.add_output_item_code_interpreter_call() yield b.emit_added() @@ -221,7 +221,7 @@ async def events(): def _image_gen_handler(): def handler(request, context, cancellation_signal): async def events(): - s = ResponseEventStream(response_id=context.response_id, model=request.model) + s = ResponseEventStream(response_id=context.response_id, model=request.get("model")) yield s.emit_created() b = s.add_output_item_image_gen_call() yield b.emit_added() @@ -241,7 +241,7 @@ def _mcp_call_handler( ): def handler(request, context, cancellation_signal): async def events(): - s = ResponseEventStream(response_id=context.response_id, model=request.model) + s = ResponseEventStream(response_id=context.response_id, model=request.get("model")) yield s.emit_created() b = s.add_output_item_mcp_call(server_label, name) yield b.emit_added() @@ -259,7 +259,7 @@ async def events(): def _mcp_list_tools_handler(server_label: str = "my-server"): def handler(request, context, cancellation_signal): async def events(): - s = ResponseEventStream(response_id=context.response_id, model=request.model) + s = ResponseEventStream(response_id=context.response_id, model=request.get("model")) yield s.emit_created() b = s.add_output_item_mcp_list_tools(server_label) yield b.emit_added() @@ -277,7 +277,7 @@ def _multiple_items_handler(): def handler(request, context, cancellation_signal): async def events(): - s = ResponseEventStream(response_id=context.response_id, model=request.model) + s = ResponseEventStream(response_id=context.response_id, model=request.get("model")) yield s.emit_created() for ev in s.output_item_message("Here is the result."): yield ev @@ -657,19 +657,19 @@ def test_model_in_request(self): handler = _text_message_handler() client = _make_sdk_client(_capturing(handler)) client.responses.create(model="gpt-4o", input="hi") - assert _captured["request"].model == "gpt-4o" + assert _captured["request"]["model"] == "gpt-4o" def test_instructions_in_request(self): handler = _text_message_handler() client = _make_sdk_client(_capturing(handler)) client.responses.create(model="test", input="hi", instructions="Be helpful") - assert _captured["request"].instructions == "Be helpful" + assert _captured["request"]["instructions"] == "Be helpful" def test_temperature_in_request(self): handler = _text_message_handler() client = _make_sdk_client(_capturing(handler)) client.responses.create(model="test", input="hi", temperature=0.7) - assert _captured["request"].temperature == pytest.approx(0.7) + assert _captured["request"]["temperature"] == pytest.approx(0.7) def test_tools_in_request(self): handler = _text_message_handler() @@ -689,8 +689,8 @@ def test_tools_in_request(self): ], ) req = _captured["request"] - assert req.tools is not None - assert len(req.tools) >= 1 + assert req.get("tools") is not None + assert len(req["tools"]) >= 1 def test_max_output_tokens_in_request(self): handler = _text_message_handler() @@ -700,7 +700,7 @@ def test_max_output_tokens_in_request(self): input="hi", max_output_tokens=1024, ) - assert _captured["request"].max_output_tokens == 1024 + assert _captured["request"]["max_output_tokens"] == 1024 # --------------------------------------------------------------------------- diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_builders.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_builders.py index b7b1a510d0b7..89115310aa21 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_builders.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_builders.py @@ -5,11 +5,6 @@ from __future__ import annotations from azure.ai.agentserver.responses._id_generator import IdGenerator -from azure.ai.agentserver.responses.models._generated import ( - OutputItemMessage, - ResponseObject, - ResponseStreamEvent, -) from azure.ai.agentserver.responses.streaming import ( OutputItemFunctionCallBuilder, OutputItemFunctionCallOutputBuilder, @@ -32,9 +27,9 @@ def test_text_content_builder__emits_added_delta_done_events() -> None: done = text.emit_done() assert isinstance(text, TextContentBuilder) - # Every emitted event must be a ResponseStreamEvent subtype, not a plain dict + # Every emitted event must be a ResponseStreamEvent wire dict. for event in (added, delta, text_done, done): - assert isinstance(event, ResponseStreamEvent), f"Expected ResponseStreamEvent, got {type(event)}" + assert isinstance(event, dict), f"Expected ResponseStreamEvent dict, got {type(event)}" assert added["type"] == "response.content_part.added" assert delta["type"] == "response.output_text.delta" assert text_done["type"] == "response.output_text.done" @@ -75,7 +70,7 @@ def test_output_item_message_builder__emits_added_content_done_and_done() -> Non assert isinstance(message, OutputItemMessageBuilder) for event in (added, content_done, done): - assert isinstance(event, ResponseStreamEvent), f"Expected ResponseStreamEvent, got {type(event)}" + assert isinstance(event, dict), f"Expected ResponseStreamEvent dict, got {type(event)}" assert added["type"] == "response.output_item.added" assert content_done["type"] == "response.content_part.done" assert done["type"] == "response.output_item.done" @@ -95,7 +90,7 @@ def test_output_item_function_call_builder__emits_arguments_and_done_events() -> assert isinstance(function_call, OutputItemFunctionCallBuilder) for event in (added, delta, args_done, done): - assert isinstance(event, ResponseStreamEvent), f"Expected ResponseStreamEvent, got {type(event)}" + assert isinstance(event, dict), f"Expected ResponseStreamEvent dict, got {type(event)}" assert added["type"] == "response.output_item.added" assert delta["type"] == "response.function_call_arguments.delta" assert args_done["type"] == "response.function_call_arguments.done" @@ -115,7 +110,7 @@ def test_output_item_function_call_output_builder__emits_added_and_done_events() assert isinstance(function_output, OutputItemFunctionCallOutputBuilder) for event in (added, done): - assert isinstance(event, ResponseStreamEvent), f"Expected ResponseStreamEvent, got {type(event)}" + assert isinstance(event, dict), f"Expected ResponseStreamEvent dict, got {type(event)}" assert added["type"] == "response.output_item.added" assert added["item"]["type"] == "function_call_output" assert added["item"]["call_id"] == "call_1" @@ -305,8 +300,8 @@ def test_output_item_mcp_call_emit_done__includes_output_and_error_when_provided def test_response_event_stream__exposes_mutable_response_snapshot_for_lifecycle_events() -> None: stream = ResponseEventStream(response_id="resp_builder_snapshot", model="gpt-4o-mini") - stream.response.temperature = 1 - stream.response.metadata = {"source": "unit-test"} + stream.response["temperature"] = 1 + stream.response["metadata"] = {"source": "unit-test"} created = stream.emit_created() @@ -331,14 +326,10 @@ def test_response_event_stream__tracks_completed_output_items_into_response_outp done = message.emit_done() assert done["type"] == "response.output_item.done" - # response.output items must be properly typed model instances - assert isinstance(stream.response, ResponseObject) - assert len(stream.response.output) == 1 - output_item_obj = stream.response.output[0] - assert isinstance(output_item_obj, OutputItemMessage), ( - f"Expected OutputItemMessage on response.output, got {type(output_item_obj)}" - ) - output_item = output_item_obj.as_dict() + # response.output items must be dict-native wire payloads. + assert isinstance(stream.response, dict) + assert len(stream.response["output"]) == 1 + output_item = stream.response["output"][0] assert output_item["id"] == message.item_id assert output_item["type"] == "message" assert output_item["content"][0]["text"] == "hello" diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_emit_return_types.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_emit_return_types.py index 3e7b29926222..3c68fff3ca76 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_emit_return_types.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_emit_return_types.py @@ -1,12 +1,10 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. -"""Strongly-typed return type assertions for every public emit_* method. +"""Wire-event return assertions for every public emit_* method. -Every builder ``emit_*`` method must return the specific ``ResponseStreamEvent`` -subtype per spec (e.g. ``emit_added()`` on a message -builder returns ``ResponseOutputItemAddedEvent``, not the base -``ResponseStreamEvent``). These tests assert the ``isinstance`` contract for -every public emit method on every builder class. +Every builder ``emit_*`` method must return a dict-native ``ResponseStreamEvent`` +with the specific wire ``type`` per spec (e.g. ``emit_added()`` on a message +builder returns a payload with ``type == "response.output_item.added"``). Builder classes covered: - ResponseEventStream (lifecycle: queued, created, in_progress, completed, failed, incomplete) @@ -33,53 +31,9 @@ from __future__ import annotations -from azure.ai.agentserver.responses.models._generated import ( - ResponseCodeInterpreterCallCodeDeltaEvent, - ResponseCodeInterpreterCallCodeDoneEvent, - ResponseCodeInterpreterCallCompletedEvent, - ResponseCodeInterpreterCallInProgressEvent, - ResponseCodeInterpreterCallInterpretingEvent, - ResponseCompletedEvent, - ResponseContentPartAddedEvent, - ResponseContentPartDoneEvent, - ResponseCreatedEvent, - ResponseCustomToolCallInputDeltaEvent, - ResponseCustomToolCallInputDoneEvent, - ResponseFailedEvent, - ResponseFileSearchCallCompletedEvent, - ResponseFileSearchCallInProgressEvent, - ResponseFileSearchCallSearchingEvent, - ResponseFunctionCallArgumentsDeltaEvent, - ResponseFunctionCallArgumentsDoneEvent, - ResponseImageGenCallCompletedEvent, - ResponseImageGenCallGeneratingEvent, - ResponseImageGenCallInProgressEvent, - ResponseImageGenCallPartialImageEvent, - ResponseIncompleteEvent, - ResponseInProgressEvent, - ResponseMCPCallArgumentsDeltaEvent, - ResponseMCPCallArgumentsDoneEvent, - ResponseMCPCallCompletedEvent, - ResponseMCPCallFailedEvent, - ResponseMCPCallInProgressEvent, - ResponseMCPListToolsCompletedEvent, - ResponseMCPListToolsFailedEvent, - ResponseMCPListToolsInProgressEvent, - ResponseOutputItemAddedEvent, - ResponseOutputItemDoneEvent, - ResponseOutputTextAnnotationAddedEvent, - ResponseQueuedEvent, - ResponseReasoningSummaryPartAddedEvent, - ResponseReasoningSummaryPartDoneEvent, - ResponseReasoningSummaryTextDeltaEvent, - ResponseReasoningSummaryTextDoneEvent, - ResponseRefusalDeltaEvent, - ResponseRefusalDoneEvent, - ResponseTextDeltaEvent, - ResponseTextDoneEvent, - ResponseWebSearchCallCompletedEvent, - ResponseWebSearchCallInProgressEvent, - ResponseWebSearchCallSearchingEvent, +from typing import Any + +from azure.ai.extensions.openai.responses import ( StructuredOutputsOutputItem, UrlCitationBody, ) @@ -88,6 +42,122 @@ # ---- helper ---- +def _event_type_checker(name: str, event_type: str) -> type: + class _EventTypeMeta(type): + def __instancecheck__(cls, instance: Any) -> bool: # pylint: disable=unused-argument + return isinstance(instance, dict) and instance.get("type") == event_type + + return _EventTypeMeta(name, (), {}) + + +ResponseCodeInterpreterCallCodeDeltaEvent = _event_type_checker( + "ResponseCodeInterpreterCallCodeDeltaEvent", "response.code_interpreter_call_code.delta" +) +ResponseCodeInterpreterCallCodeDoneEvent = _event_type_checker( + "ResponseCodeInterpreterCallCodeDoneEvent", "response.code_interpreter_call_code.done" +) +ResponseCodeInterpreterCallCompletedEvent = _event_type_checker( + "ResponseCodeInterpreterCallCompletedEvent", "response.code_interpreter_call.completed" +) +ResponseCodeInterpreterCallInProgressEvent = _event_type_checker( + "ResponseCodeInterpreterCallInProgressEvent", "response.code_interpreter_call.in_progress" +) +ResponseCodeInterpreterCallInterpretingEvent = _event_type_checker( + "ResponseCodeInterpreterCallInterpretingEvent", "response.code_interpreter_call.interpreting" +) +ResponseCompletedEvent = _event_type_checker("ResponseCompletedEvent", "response.completed") +ResponseContentPartAddedEvent = _event_type_checker("ResponseContentPartAddedEvent", "response.content_part.added") +ResponseContentPartDoneEvent = _event_type_checker("ResponseContentPartDoneEvent", "response.content_part.done") +ResponseCreatedEvent = _event_type_checker("ResponseCreatedEvent", "response.created") +ResponseCustomToolCallInputDeltaEvent = _event_type_checker( + "ResponseCustomToolCallInputDeltaEvent", "response.custom_tool_call_input.delta" +) +ResponseCustomToolCallInputDoneEvent = _event_type_checker( + "ResponseCustomToolCallInputDoneEvent", "response.custom_tool_call_input.done" +) +ResponseFailedEvent = _event_type_checker("ResponseFailedEvent", "response.failed") +ResponseFileSearchCallCompletedEvent = _event_type_checker( + "ResponseFileSearchCallCompletedEvent", "response.file_search_call.completed" +) +ResponseFileSearchCallInProgressEvent = _event_type_checker( + "ResponseFileSearchCallInProgressEvent", "response.file_search_call.in_progress" +) +ResponseFileSearchCallSearchingEvent = _event_type_checker( + "ResponseFileSearchCallSearchingEvent", "response.file_search_call.searching" +) +ResponseFunctionCallArgumentsDeltaEvent = _event_type_checker( + "ResponseFunctionCallArgumentsDeltaEvent", "response.function_call_arguments.delta" +) +ResponseFunctionCallArgumentsDoneEvent = _event_type_checker( + "ResponseFunctionCallArgumentsDoneEvent", "response.function_call_arguments.done" +) +ResponseImageGenCallCompletedEvent = _event_type_checker( + "ResponseImageGenCallCompletedEvent", "response.image_generation_call.completed" +) +ResponseImageGenCallGeneratingEvent = _event_type_checker( + "ResponseImageGenCallGeneratingEvent", "response.image_generation_call.generating" +) +ResponseImageGenCallInProgressEvent = _event_type_checker( + "ResponseImageGenCallInProgressEvent", "response.image_generation_call.in_progress" +) +ResponseImageGenCallPartialImageEvent = _event_type_checker( + "ResponseImageGenCallPartialImageEvent", "response.image_generation_call.partial_image" +) +ResponseIncompleteEvent = _event_type_checker("ResponseIncompleteEvent", "response.incomplete") +ResponseInProgressEvent = _event_type_checker("ResponseInProgressEvent", "response.in_progress") +ResponseMCPCallArgumentsDeltaEvent = _event_type_checker( + "ResponseMCPCallArgumentsDeltaEvent", "response.mcp_call_arguments.delta" +) +ResponseMCPCallArgumentsDoneEvent = _event_type_checker( + "ResponseMCPCallArgumentsDoneEvent", "response.mcp_call_arguments.done" +) +ResponseMCPCallCompletedEvent = _event_type_checker("ResponseMCPCallCompletedEvent", "response.mcp_call.completed") +ResponseMCPCallFailedEvent = _event_type_checker("ResponseMCPCallFailedEvent", "response.mcp_call.failed") +ResponseMCPCallInProgressEvent = _event_type_checker( + "ResponseMCPCallInProgressEvent", "response.mcp_call.in_progress" +) +ResponseMCPListToolsCompletedEvent = _event_type_checker( + "ResponseMCPListToolsCompletedEvent", "response.mcp_list_tools.completed" +) +ResponseMCPListToolsFailedEvent = _event_type_checker( + "ResponseMCPListToolsFailedEvent", "response.mcp_list_tools.failed" +) +ResponseMCPListToolsInProgressEvent = _event_type_checker( + "ResponseMCPListToolsInProgressEvent", "response.mcp_list_tools.in_progress" +) +ResponseOutputItemAddedEvent = _event_type_checker("ResponseOutputItemAddedEvent", "response.output_item.added") +ResponseOutputItemDoneEvent = _event_type_checker("ResponseOutputItemDoneEvent", "response.output_item.done") +ResponseOutputTextAnnotationAddedEvent = _event_type_checker( + "ResponseOutputTextAnnotationAddedEvent", "response.output_text.annotation.added" +) +ResponseQueuedEvent = _event_type_checker("ResponseQueuedEvent", "response.queued") +ResponseReasoningSummaryPartAddedEvent = _event_type_checker( + "ResponseReasoningSummaryPartAddedEvent", "response.reasoning_summary_part.added" +) +ResponseReasoningSummaryPartDoneEvent = _event_type_checker( + "ResponseReasoningSummaryPartDoneEvent", "response.reasoning_summary_part.done" +) +ResponseReasoningSummaryTextDeltaEvent = _event_type_checker( + "ResponseReasoningSummaryTextDeltaEvent", "response.reasoning_summary_text.delta" +) +ResponseReasoningSummaryTextDoneEvent = _event_type_checker( + "ResponseReasoningSummaryTextDoneEvent", "response.reasoning_summary_text.done" +) +ResponseRefusalDeltaEvent = _event_type_checker("ResponseRefusalDeltaEvent", "response.refusal.delta") +ResponseRefusalDoneEvent = _event_type_checker("ResponseRefusalDoneEvent", "response.refusal.done") +ResponseTextDeltaEvent = _event_type_checker("ResponseTextDeltaEvent", "response.output_text.delta") +ResponseTextDoneEvent = _event_type_checker("ResponseTextDoneEvent", "response.output_text.done") +ResponseWebSearchCallCompletedEvent = _event_type_checker( + "ResponseWebSearchCallCompletedEvent", "response.web_search_call.completed" +) +ResponseWebSearchCallInProgressEvent = _event_type_checker( + "ResponseWebSearchCallInProgressEvent", "response.web_search_call.in_progress" +) +ResponseWebSearchCallSearchingEvent = _event_type_checker( + "ResponseWebSearchCallSearchingEvent", "response.web_search_call.searching" +) + + def _stream() -> ResponseEventStream: return ResponseEventStream(response_id="resp_emit_types") diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_event_stream_generators.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_event_stream_generators.py index 179dfe720bdb..bc54e2eec3de 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_event_stream_generators.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_event_stream_generators.py @@ -6,7 +6,6 @@ import pytest -from azure.ai.agentserver.responses.models._generated import ResponseStreamEvent from azure.ai.agentserver.responses.streaming._event_stream import ResponseEventStream RESPONSE_ID = "resp_gen_test_12345" @@ -32,9 +31,9 @@ def test_output_item_message_yields_full_lifecycle() -> None: events = list(stream.output_item_message("Hello world")) assert len(events) == 6 - # Every yielded event must be a ResponseStreamEvent model, not a plain dict + # Every yielded event must be a ResponseStreamEvent wire dict. for event in events: - assert isinstance(event, ResponseStreamEvent), f"Expected ResponseStreamEvent, got {type(event)}" + assert isinstance(event, dict), f"Expected ResponseStreamEvent dict, got {type(event)}" types = [e["type"] for e in events] assert types == [ "response.output_item.added", @@ -63,7 +62,7 @@ def test_output_item_function_call_yields_full_lifecycle() -> None: assert len(events) == 4 for event in events: - assert isinstance(event, ResponseStreamEvent), f"Expected ResponseStreamEvent, got {type(event)}" + assert isinstance(event, dict), f"Expected ResponseStreamEvent dict, got {type(event)}" types = [e["type"] for e in events] assert types == [ "response.output_item.added", @@ -93,7 +92,7 @@ def test_output_item_function_call_output_yields_added_and_done() -> None: assert len(events) == 2 for event in events: - assert isinstance(event, ResponseStreamEvent), f"Expected ResponseStreamEvent, got {type(event)}" + assert isinstance(event, dict), f"Expected ResponseStreamEvent dict, got {type(event)}" types = [e["type"] for e in events] assert types == [ "response.output_item.added", @@ -115,7 +114,7 @@ def test_output_item_reasoning_item_yields_full_lifecycle() -> None: assert len(events) == 6 for event in events: - assert isinstance(event, ResponseStreamEvent), f"Expected ResponseStreamEvent, got {type(event)}" + assert isinstance(event, dict), f"Expected ResponseStreamEvent dict, got {type(event)}" types = [e["type"] for e in events] assert types == [ "response.output_item.added", diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_foundry_storage_provider.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_foundry_storage_provider.py index 0ef99fb9b2b5..a506c4a4853c 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_foundry_storage_provider.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_foundry_storage_provider.py @@ -110,7 +110,7 @@ def settings() -> FoundryStorageSettings: @pytest.mark.asyncio async def test_create_response__posts_to_responses_endpoint(credential: Any, settings: FoundryStorageSettings) -> None: provider = _make_provider(credential, settings, _make_response(200, {})) - from azure.ai.agentserver.responses.models._generated import ResponseObject + from azure.ai.extensions.openai.responses import ResponseObject response = ResponseObject(_RESPONSE_DICT) await provider.create_response(response, None, None) @@ -124,10 +124,10 @@ async def test_create_response__posts_to_responses_endpoint(credential: Any, set @pytest.mark.asyncio async def test_create_response__sends_correct_envelope(credential: Any, settings: FoundryStorageSettings) -> None: provider = _make_provider(credential, settings, _make_response(200, {})) - from azure.ai.agentserver.responses.models._generated import ResponseObject + from azure.ai.extensions.openai.responses import ResponseObject response = ResponseObject(_RESPONSE_DICT) - await provider.create_response(response, [MagicMock(as_dict=lambda: _INPUT_ITEM_DICT)], ["prev_item_1"]) + await provider.create_response(response, [_INPUT_ITEM_DICT], ["prev_item_1"]) request = provider._client.send_request.call_args[0][0] payload = json.loads(request.content.decode("utf-8")) @@ -141,7 +141,7 @@ async def test_create_response__raises_foundry_api_error_on_500( credential: Any, settings: FoundryStorageSettings ) -> None: provider = _make_provider(credential, settings, _make_response(500, {"error": {"message": "server fault"}})) - from azure.ai.agentserver.responses.models._generated import ResponseObject + from azure.ai.extensions.openai.responses import ResponseObject with pytest.raises(FoundryApiError) as exc_info: await provider.create_response(ResponseObject(_RESPONSE_DICT), None, None) @@ -205,7 +205,7 @@ async def test_get_response__url_encodes_special_characters(credential: Any, set @pytest.mark.asyncio async def test_update_response__posts_to_response_id_url(credential: Any, settings: FoundryStorageSettings) -> None: provider = _make_provider(credential, settings, _make_response(200, {})) - from azure.ai.agentserver.responses.models._generated import ResponseObject + from azure.ai.extensions.openai.responses import ResponseObject response = ResponseObject(_RESPONSE_DICT) await provider.update_response(response) @@ -220,7 +220,7 @@ async def test_update_response__sends_serialized_response_body( credential: Any, settings: FoundryStorageSettings ) -> None: provider = _make_provider(credential, settings, _make_response(200, {})) - from azure.ai.agentserver.responses.models._generated import ResponseObject + from azure.ai.extensions.openai.responses import ResponseObject response = ResponseObject(_RESPONSE_DICT) await provider.update_response(response) @@ -233,7 +233,7 @@ async def test_update_response__sends_serialized_response_body( @pytest.mark.asyncio async def test_update_response__raises_bad_request_on_409(credential: Any, settings: FoundryStorageSettings) -> None: provider = _make_provider(credential, settings, _make_response(409, {"error": {"message": "conflict"}})) - from azure.ai.agentserver.responses.models._generated import ResponseObject + from azure.ai.extensions.openai.responses import ResponseObject with pytest.raises(FoundryBadRequestError) as exc_info: await provider.update_response(ResponseObject(_RESPONSE_DICT)) @@ -466,7 +466,7 @@ async def test_get_history_item_ids__omits_optional_params_when_none( @pytest.mark.asyncio async def test_create_response__sends_platform_headers(credential: Any, settings: FoundryStorageSettings) -> None: provider = _make_provider(credential, settings, _make_response(200, {})) - from azure.ai.agentserver.responses.models._generated import ResponseObject + from azure.ai.extensions.openai.responses import ResponseObject isolation = PlatformContext(user_id_key="u_key_1", call_id="c_key_1") await provider.create_response(ResponseObject(_RESPONSE_DICT), None, None, context=isolation) @@ -491,7 +491,7 @@ async def test_get_response__sends_platform_headers(credential: Any, settings: F @pytest.mark.asyncio async def test_update_response__sends_platform_headers(credential: Any, settings: FoundryStorageSettings) -> None: provider = _make_provider(credential, settings, _make_response(200, {})) - from azure.ai.agentserver.responses.models._generated import ResponseObject + from azure.ai.extensions.openai.responses import ResponseObject isolation = PlatformContext(user_id_key="u_key_3", call_id="c_key_3") await provider.update_response(ResponseObject(_RESPONSE_DICT), context=isolation) diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_generated_payload_validation.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_generated_payload_validation.py index 2de5b2219130..55c479799c4b 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_generated_payload_validation.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_generated_payload_validation.py @@ -28,7 +28,7 @@ def test_parse_create_response_rejects_invalid_payload() -> None: def test_parse_create_response_allows_valid_payload() -> None: parsed = parse_create_response({"model": "gpt-4o"}) - assert parsed.model == "gpt-4o" + assert parsed["model"] == "gpt-4o" def test_parse_create_response_rejects_non_object_body() -> None: diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_id_generator.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_id_generator.py index f0b47d97d537..ec6bae4b9d9a 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_id_generator.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_id_generator.py @@ -9,7 +9,6 @@ import pytest from azure.ai.agentserver.responses._id_generator import IdGenerator -from azure.ai.agentserver.responses.models import _generated as generated_models def test_id_generator__new_id_uses_new_format_shape() -> None: @@ -98,13 +97,17 @@ def test_id_generator__convenience_method_uses_caresp_prefix() -> None: assert len(created_id.split("_", maxsplit=1)[1]) == 50 -def test_id_generator__new_item_id_dispatches_by_generated_model_type() -> None: - item_message = object.__new__(generated_models.ItemMessage) - item_reference = object.__new__(generated_models.ItemReferenceParam) +def test_id_generator__new_item_id_dispatches_by_wire_type() -> None: + item_message = {"type": "message"} + item_compaction = {"type": "compaction"} + item_reference = {"type": "item_reference", "id": "item_1"} generated_id = IdGenerator.new_item_id(item_message) + compaction_id = IdGenerator.new_item_id(item_compaction) assert generated_id is not None assert generated_id.startswith("msg_") + assert compaction_id is not None + assert compaction_id.startswith("cmp_") assert IdGenerator.new_item_id(item_reference) is None assert IdGenerator.new_item_id(object()) is None diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_in_memory_provider_crud.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_in_memory_provider_crud.py index 3aa249cc0675..7f0e1987e2c8 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_in_memory_provider_crud.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_in_memory_provider_crud.py @@ -14,7 +14,7 @@ import pytest -from azure.ai.agentserver.responses.models import _generated as generated_models +from azure.ai.extensions.openai.responses import ResponseObject from azure.ai.agentserver.responses.store._memory import InMemoryResponseProvider # --------------------------------------------------------------------------- @@ -28,7 +28,7 @@ def _response( status: str = "completed", output: list[dict[str, Any]] | None = None, conversation_id: str | None = None, -) -> generated_models.ResponseObject: +) -> ResponseObject: payload: dict[str, Any] = { "id": response_id, "object": "response", @@ -38,7 +38,7 @@ def _response( } if conversation_id is not None: payload["conversation"] = {"id": conversation_id} - return generated_models.ResponseObject(payload) + return ResponseObject(payload) def _input_item(item_id: str, text: str) -> dict[str, Any]: @@ -70,7 +70,7 @@ def test_create__stores_response_envelope() -> None: asyncio.run(provider.create_response(_response("resp_1"), None, None)) result = asyncio.run(provider.get_response("resp_1")) - assert str(getattr(result, "id")) == "resp_1" + assert result["id"] == "resp_1" def test_create__duplicate_raises_value_error() -> None: @@ -115,7 +115,7 @@ def test_create__returns_defensive_copy() -> None: r1["status"] = "failed" r2 = asyncio.run(provider.get_response("resp_copy")) - assert str(getattr(r2, "status")) == "completed" + assert r2["status"] == "completed" # =========================================================================== @@ -157,7 +157,7 @@ def test_update__replaces_envelope() -> None: asyncio.run(provider.update_response(updated)) result = asyncio.run(provider.get_response("resp_upd")) - assert str(getattr(result, "status")) == "completed" + assert result["status"] == "completed" def test_update__stores_new_output_items() -> None: diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_input_items_provider_behavior.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_input_items_provider_behavior.py index d5e027594438..a706740cc830 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_input_items_provider_behavior.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_input_items_provider_behavior.py @@ -8,12 +8,12 @@ import pytest -from azure.ai.agentserver.responses.models import _generated as generated_models +from azure.ai.extensions.openai.responses import ResponseObject from azure.ai.agentserver.responses.store._memory import InMemoryResponseProvider -def _response(response_id: str, *, store: bool = True) -> generated_models.ResponseObject: - return generated_models.ResponseObject( +def _response(response_id: str, *, store: bool = True) -> ResponseObject: + return ResponseObject( { "id": response_id, "object": "response", diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_public_contract_types.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_public_contract_types.py index 5bfaacf1da9d..f225a0a86468 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_public_contract_types.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_public_contract_types.py @@ -1,20 +1,19 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. -"""Contract type assertions for every public handler/consumer surface. +"""Contract shape assertions for every public handler/consumer surface. -Every public API that returns model objects MUST return proper discriminated -subtypes — never base classes, never plain dicts. These tests assert the -``isinstance`` contract so regressions are caught immediately. +Public APIs now return dict-native wire payloads. These tests assert the +discriminator and field-shape contract so regressions are caught immediately. Surfaces covered: 1. context.request → CreateResponse - 2. context.get_input_items() → Sequence[Item] with subtype fidelity + 2. context.get_input_items() → Sequence[Item] wire dicts 3. context.get_input_text() → str - 4. context.get_history() → Sequence[OutputItem] with subtype fidelity - 5. stream.response → ResponseObject - 6. stream.response.output → list of OutputItem subtypes - 7. Builder emit_* returns → ResponseStreamEvent subtypes - 8. Generator convenience → ResponseStreamEvent subtypes + 4. context.get_history() → Sequence[OutputItem] wire dicts + 5. stream.response → ResponseObject wire dict + 6. stream.response.output → list of OutputItem wire dicts + 7. Builder emit_* returns → ResponseStreamEvent wire dicts + 8. Generator convenience → ResponseStreamEvent wire dicts """ from __future__ import annotations @@ -26,7 +25,7 @@ import pytest from azure.ai.agentserver.responses._response_context import ResponseContext -from azure.ai.agentserver.responses.models._generated import ( +from azure.ai.extensions.openai.responses import ( CreateResponse, Item, ItemMessage, @@ -71,13 +70,23 @@ def _mock_provider(**overrides: Any) -> Any: return provider +def _field(payload: Any, name: str) -> Any: + return payload.get(name) if isinstance(payload, dict) else None + + +def _content_text(item: Any, index: int = 0) -> str: + content = _field(item, "content") + part = content[index] + return _field(part, "text") + + # ===================================================================== # 1. context.request → CreateResponse # ===================================================================== class TestContextRequestType: - """context.request must be a CreateResponse model instance.""" + """context.request must be a CreateResponse wire payload.""" @pytest.mark.asyncio async def test_request_is_create_response_model(self) -> None: @@ -88,9 +97,8 @@ async def test_request_is_create_response_model(self) -> None: request=request, ) - assert isinstance(ctx.request, CreateResponse) - # Attribute access works (not a dict) - assert ctx.request.model == "test-model" + assert isinstance(ctx.request, dict) + assert ctx.request["model"] == "test-model" # ===================================================================== @@ -103,16 +111,18 @@ class TestInputItemsContractTypes: @pytest.mark.asyncio async def test_inline_message_returns_item_message_subtype(self) -> None: - msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(text="hi")]) - request = CreateResponse(model="m", input=[msg.as_dict()]) + msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(type="input_text", text="hi")]) + request = CreateResponse(model="m", input=[msg]) ctx = ResponseContext(response_id="resp_type_2a", mode_flags=_mode_flags(), request=request) items = await ctx.get_input_items() assert isinstance(items, Sequence) assert len(items) == 1 - assert isinstance(items[0], Item), f"Expected Item, got {type(items[0])}" - assert isinstance(items[0], ItemMessage), f"Expected ItemMessage, got {type(items[0])}" + assert isinstance(items[0], dict), f"Expected Item wire dict, got {type(items[0])}" + assert items[0]["type"] == "message" + assert items[0]["role"] == "user" + assert _content_text(items[0]) == "hi" @pytest.mark.asyncio async def test_resolved_reference_returns_typed_item(self) -> None: @@ -138,8 +148,10 @@ async def test_resolved_reference_returns_typed_item(self) -> None: items = await ctx.get_input_items() assert len(items) == 1 - assert isinstance(items[0], Item), f"Expected Item subtype, got {type(items[0])}" - assert isinstance(items[0], ItemMessage), f"Expected ItemMessage, got {type(items[0])}" + assert isinstance(items[0], dict), f"Expected Item wire dict, got {type(items[0])}" + assert items[0]["type"] == "message" + assert items[0]["id"] == "msg_ref_01" + assert _content_text(items[0]) == "resolved" # ===================================================================== @@ -226,18 +238,10 @@ async def test_returns_typed_output_item_subtypes(self) -> None: assert isinstance(history, Sequence) assert len(history) == 2 - # First item must be OutputItemMessage, not base OutputItem - assert isinstance(history[0], OutputItem), f"Expected OutputItem, got {type(history[0])}" - assert isinstance(history[0], OutputItemMessage), f"Expected OutputItemMessage, got {type(history[0])}" - # Attribute access must work (not just dict access) - assert history[0].content[0].text == "previous reply" - - # Second item must be OutputItemFunctionToolCall - assert isinstance(history[1], OutputItem), f"Expected OutputItem, got {type(history[1])}" - assert isinstance(history[1], OutputItemFunctionToolCall), ( - f"Expected OutputItemFunctionToolCall, got {type(history[1])}" - ) - assert history[1].name == "get_weather" + assert _field(history[0], "type") == "message" + assert _content_text(history[0]) == "previous reply" + assert _field(history[1], "type") == "function_call" + assert _field(history[1], "name") == "get_weather" @pytest.mark.asyncio async def test_caches_result_on_second_call(self) -> None: @@ -267,7 +271,7 @@ async def test_caches_result_on_second_call(self) -> None: second = await ctx.get_history() assert first is second # cached tuple - assert isinstance(first[0], OutputItemMessage) + assert _field(first[0], "type") == "message" # ===================================================================== @@ -276,21 +280,21 @@ async def test_caches_result_on_second_call(self) -> None: class TestStreamResponseType: - """stream.response must be a ResponseObject, not a dict.""" + """stream.response must be a ResponseObject wire dict.""" def test_response_is_response_object_model(self) -> None: stream = ResponseEventStream(response_id="resp_type_5a", model="gpt-4o") - assert isinstance(stream.response, ResponseObject) - assert stream.response.id == "resp_type_5a" - assert stream.response.model == "gpt-4o" + assert isinstance(stream.response, dict) + assert stream.response["id"] == "resp_type_5a" + assert stream.response["model"] == "gpt-4o" def test_seed_response_preserves_type(self) -> None: seed = ResponseObject({"id": "resp_type_5b", "object": "response", "output": [], "model": "gpt-4o"}) stream = ResponseEventStream(response=seed) - assert isinstance(stream.response, ResponseObject) - assert stream.response.id == "resp_type_5b" + assert isinstance(stream.response, dict) + assert stream.response["id"] == "resp_type_5b" # ===================================================================== @@ -299,7 +303,7 @@ def test_seed_response_preserves_type(self) -> None: class TestResponseOutputItemTypes: - """After output_item.done, response.output items must be proper subtypes.""" + """After output_item.done, response.output items must have proper wire discriminators.""" def test_message_output_item_is_output_item_message(self) -> None: stream = ResponseEventStream(response_id="resp_type_6a") @@ -313,12 +317,10 @@ def test_message_output_item_is_output_item_message(self) -> None: text.emit_done() message.emit_done() - assert len(stream.response.output) == 1 - item = stream.response.output[0] - assert isinstance(item, OutputItem), f"Expected OutputItem, got {type(item)}" - assert isinstance(item, OutputItemMessage), f"Expected OutputItemMessage, got {type(item)}" - # Subtype-specific attribute access must work - assert item.content[0].text == "hello" + assert len(stream.response["output"]) == 1 + item = stream.response["output"][0] + assert item["type"] == "message" + assert item["content"][0]["text"] == "hello" def test_function_call_output_item_is_function_tool_call(self) -> None: stream = ResponseEventStream(response_id="resp_type_6b") @@ -329,12 +331,11 @@ def test_function_call_output_item_is_function_tool_call(self) -> None: fc.emit_arguments_done('{"city":"Seattle"}') fc.emit_done() - assert len(stream.response.output) == 1 - item = stream.response.output[0] - assert isinstance(item, OutputItem), f"Expected OutputItem, got {type(item)}" - assert isinstance(item, OutputItemFunctionToolCall), f"Expected OutputItemFunctionToolCall, got {type(item)}" - assert item.name == "get_weather" - assert item.arguments == '{"city":"Seattle"}' + assert len(stream.response["output"]) == 1 + item = stream.response["output"][0] + assert item["type"] == "function_call" + assert item["name"] == "get_weather" + assert item["arguments"] == '{"city":"Seattle"}' def test_reasoning_output_item_is_reasoning_item(self) -> None: stream = ResponseEventStream(response_id="resp_type_6c") @@ -347,10 +348,9 @@ def test_reasoning_output_item_is_reasoning_item(self) -> None: summary.emit_done() reasoning.emit_done() - assert len(stream.response.output) == 1 - item = stream.response.output[0] - assert isinstance(item, OutputItem), f"Expected OutputItem, got {type(item)}" - assert isinstance(item, OutputItemReasoningItem), f"Expected OutputItemReasoningItem, got {type(item)}" + assert len(stream.response["output"]) == 1 + item = stream.response["output"][0] + assert item["type"] == "reasoning" def test_multiple_output_items_all_typed(self) -> None: """Mixed output items must all be proper subtypes.""" @@ -373,9 +373,9 @@ def test_multiple_output_items_all_typed(self) -> None: fc.emit_arguments_done("{}") fc.emit_done() - assert len(stream.response.output) == 2 - assert isinstance(stream.response.output[0], OutputItemMessage) - assert isinstance(stream.response.output[1], OutputItemFunctionToolCall) + assert len(stream.response["output"]) == 2 + assert stream.response["output"][0]["type"] == "message" + assert stream.response["output"][1]["type"] == "function_call" # ===================================================================== @@ -384,18 +384,18 @@ def test_multiple_output_items_all_typed(self) -> None: class TestBuilderEventTypes: - """Every builder emit_* method must return a typed ResponseStreamEvent subtype.""" + """Every builder emit_* method must return a typed ResponseStreamEvent wire dict.""" def test_lifecycle_events_are_typed(self) -> None: stream = ResponseEventStream(response_id="resp_type_7a") created = stream.emit_created() - assert isinstance(created, ResponseStreamEvent) - assert isinstance(created, ResponseCreatedEvent), f"Expected ResponseCreatedEvent, got {type(created)}" + assert isinstance(created, dict) + assert created["type"] == "response.created" in_progress = stream.emit_in_progress() - assert isinstance(in_progress, ResponseStreamEvent) - assert isinstance(in_progress, ResponseInProgressEvent) + assert isinstance(in_progress, dict) + assert in_progress["type"] == "response.in_progress" msg = stream.add_output_item_message() msg.emit_added() @@ -407,8 +407,8 @@ def test_lifecycle_events_are_typed(self) -> None: msg.emit_done() completed = stream.emit_completed() - assert isinstance(completed, ResponseStreamEvent) - assert isinstance(completed, ResponseCompletedEvent) + assert isinstance(completed, dict) + assert completed["type"] == "response.completed" def test_message_builder_events_are_typed(self) -> None: stream = ResponseEventStream(response_id="resp_type_7b") @@ -416,29 +416,29 @@ def test_message_builder_events_are_typed(self) -> None: message = stream.add_output_item_message() added = message.emit_added() - assert isinstance(added, ResponseStreamEvent) - assert isinstance(added, ResponseOutputItemAddedEvent) + assert isinstance(added, dict) + assert added["type"] == "response.output_item.added" text = message.add_text_content() content_added = text.emit_added() - assert isinstance(content_added, ResponseStreamEvent) - assert isinstance(content_added, ResponseContentPartAddedEvent) + assert isinstance(content_added, dict) + assert content_added["type"] == "response.content_part.added" delta = text.emit_delta("hello") - assert isinstance(delta, ResponseStreamEvent) - assert isinstance(delta, ResponseTextDeltaEvent) + assert isinstance(delta, dict) + assert delta["type"] == "response.output_text.delta" text_done = text.emit_text_done() - assert isinstance(text_done, ResponseStreamEvent) - assert isinstance(text_done, ResponseTextDoneEvent) + assert isinstance(text_done, dict) + assert text_done["type"] == "response.output_text.done" content_done = text.emit_done() - assert isinstance(content_done, ResponseStreamEvent) - assert isinstance(content_done, ResponseContentPartDoneEvent) + assert isinstance(content_done, dict) + assert content_done["type"] == "response.content_part.done" item_done = message.emit_done() - assert isinstance(item_done, ResponseStreamEvent) - assert isinstance(item_done, ResponseOutputItemDoneEvent) + assert isinstance(item_done, dict) + assert item_done["type"] == "response.output_item.done" def test_function_call_builder_events_are_typed(self) -> None: stream = ResponseEventStream(response_id="resp_type_7c") @@ -446,16 +446,16 @@ def test_function_call_builder_events_are_typed(self) -> None: fc = stream.add_output_item_function_call("fn", "call_1") added = fc.emit_added() - assert isinstance(added, ResponseOutputItemAddedEvent) + assert added["type"] == "response.output_item.added" delta = fc.emit_arguments_delta('{"k":') - assert isinstance(delta, ResponseFunctionCallArgumentsDeltaEvent) + assert delta["type"] == "response.function_call_arguments.delta" args_done = fc.emit_arguments_done('{"k":"v"}') - assert isinstance(args_done, ResponseFunctionCallArgumentsDoneEvent) + assert args_done["type"] == "response.function_call_arguments.done" done = fc.emit_done() - assert isinstance(done, ResponseOutputItemDoneEvent) + assert done["type"] == "response.output_item.done" # ===================================================================== @@ -464,7 +464,7 @@ def test_function_call_builder_events_are_typed(self) -> None: class TestGeneratorConvenienceTypes: - """Generator convenience methods must yield typed ResponseStreamEvent subtypes.""" + """Generator convenience methods must yield ResponseStreamEvent wire dicts.""" def test_output_item_message_events_are_typed(self) -> None: stream = ResponseEventStream(response_id="resp_type_8a") @@ -474,15 +474,16 @@ def test_output_item_message_events_are_typed(self) -> None: events = list(stream.output_item_message("Hi there")) for event in events: - assert isinstance(event, ResponseStreamEvent), f"Expected ResponseStreamEvent, got {type(event)}" + assert isinstance(event, dict), f"Expected ResponseStreamEvent dict, got {type(event)}" - # Verify specific subtypes for key events - assert isinstance(events[0], ResponseOutputItemAddedEvent) # output_item.added - assert isinstance(events[1], ResponseContentPartAddedEvent) # content_part.added - assert isinstance(events[2], ResponseTextDeltaEvent) # output_text.delta - assert isinstance(events[3], ResponseTextDoneEvent) # output_text.done - assert isinstance(events[4], ResponseContentPartDoneEvent) # content_part.done - assert isinstance(events[5], ResponseOutputItemDoneEvent) # output_item.done + assert [event["type"] for event in events] == [ + "response.output_item.added", + "response.content_part.added", + "response.output_text.delta", + "response.output_text.done", + "response.content_part.done", + "response.output_item.done", + ] def test_output_item_function_call_events_are_typed(self) -> None: stream = ResponseEventStream(response_id="resp_type_8b") @@ -492,10 +493,10 @@ def test_output_item_function_call_events_are_typed(self) -> None: events = list(stream.output_item_function_call("fn", "call_1", "{}")) for event in events: - assert isinstance(event, ResponseStreamEvent) + assert isinstance(event, dict) - assert isinstance(events[0], ResponseOutputItemAddedEvent) - assert isinstance(events[-1], ResponseOutputItemDoneEvent) + assert events[0]["type"] == "response.output_item.added" + assert events[-1]["type"] == "response.output_item.done" def test_output_item_reasoning_events_are_typed(self) -> None: stream = ResponseEventStream(response_id="resp_type_8c") @@ -505,10 +506,10 @@ def test_output_item_reasoning_events_are_typed(self) -> None: events = list(stream.output_item_reasoning_item("thinking")) for event in events: - assert isinstance(event, ResponseStreamEvent) + assert isinstance(event, dict) - assert isinstance(events[0], ResponseOutputItemAddedEvent) - assert isinstance(events[-1], ResponseOutputItemDoneEvent) + assert events[0]["type"] == "response.output_item.added" + assert events[-1]["type"] == "response.output_item.done" # ===================================================================== @@ -517,8 +518,7 @@ def test_output_item_reasoning_events_are_typed(self) -> None: class TestInMemoryProviderTypePreservation: - """Items stored and retrieved through InMemoryResponseProvider must - retain their discriminated subtype identity.""" + """Items stored and retrieved through InMemoryResponseProvider retain wire discriminators.""" @pytest.mark.asyncio async def test_stored_output_items_retrieved_as_subtypes(self) -> None: @@ -527,7 +527,7 @@ async def test_stored_output_items_retrieved_as_subtypes(self) -> None: provider = InMemoryResponseProvider() - # Build a response with typed output items on response.output + # Build a response with typed output item wire payloads on response.output response = ResponseObject( { "id": "resp_mem_1", @@ -562,15 +562,11 @@ async def test_stored_output_items_retrieved_as_subtypes(self) -> None: assert len(items) == 2 assert items[0] is not None assert items[1] is not None - assert isinstance(items[0], OutputItem) - assert isinstance(items[0], OutputItemMessage), f"Expected OutputItemMessage, got {type(items[0])}" - assert items[0].content[0].text == "stored text" + assert _field(items[0], "type") == "message" + assert _content_text(items[0]) == "stored text" - assert isinstance(items[1], OutputItem) - assert isinstance(items[1], OutputItemFunctionToolCall), ( - f"Expected OutputItemFunctionToolCall, got {type(items[1])}" - ) - assert items[1].name == "lookup" + assert _field(items[1], "type") == "function_call" + assert _field(items[1], "name") == "lookup" @pytest.mark.asyncio async def test_history_round_trip_preserves_subtypes(self) -> None: @@ -612,10 +608,10 @@ async def test_history_round_trip_preserves_subtypes(self) -> None: assert len(history) >= 1 # The message from turn 1 must be a proper OutputItemMessage - msg_item = next((h for h in history if getattr(h, "id", None) == "msg_rt_1"), None) + msg_item = next((h for h in history if _field(h, "id") == "msg_rt_1"), None) assert msg_item is not None, "Expected msg_rt_1 in history" - assert isinstance(msg_item, OutputItemMessage), f"Expected OutputItemMessage, got {type(msg_item)}" - assert msg_item.content[0].text == "turn 1 reply" + assert _field(msg_item, "type") == "message" + assert _content_text(msg_item) == "turn 1 reply" # ===================================================================== @@ -625,7 +621,7 @@ async def test_history_round_trip_preserves_subtypes(self) -> None: class TestStreamLifecycleOutputTypes: """After a full create→in_progress→items→completed stream, response.output - must contain properly typed OutputItem subtypes (not base OutputItem).""" + must contain proper OutputItem wire discriminators.""" def test_full_stream_lifecycle_output_types(self) -> None: stream = ResponseEventStream(response_id="resp_type_10a", model="gpt-4o") @@ -642,16 +638,12 @@ def test_full_stream_lifecycle_output_types(self) -> None: stream.emit_completed() - output = stream.response.output + output = stream.response["output"] assert len(output) == 2 - assert isinstance(output[0], OutputItemMessage), ( - f"After full lifecycle, output[0] should be OutputItemMessage, got {type(output[0])}" - ) - assert output[0].content[0].text == "Hello" + assert output[0]["type"] == "message" + assert output[0]["content"][0]["text"] == "Hello" - assert isinstance(output[1], OutputItemFunctionToolCall), ( - f"After full lifecycle, output[1] should be OutputItemFunctionToolCall, got {type(output[1])}" - ) - assert output[1].name == "get_temp" - assert output[1].arguments == '{"unit":"C"}' + assert output[1]["type"] == "function_call" + assert output[1]["name"] == "get_temp" + assert output[1]["arguments"] == '{"unit":"C"}' diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_resolve_input_items_for_persistence.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_resolve_input_items_for_persistence.py index 5e35b1ad53c5..229dfe9e855b 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_resolve_input_items_for_persistence.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_resolve_input_items_for_persistence.py @@ -11,7 +11,7 @@ from azure.ai.agentserver.responses._response_context import ResponseContext from azure.ai.agentserver.responses.hosting._orchestrator import _resolve_input_items_for_persistence -from azure.ai.agentserver.responses.models._generated import ( +from azure.ai.extensions.openai.responses import ( CreateResponse, ItemMessage, ItemReferenceParam, @@ -45,7 +45,7 @@ def _make_request(inp: Any) -> CreateResponse: @pytest.mark.asyncio async def test_resolves_references_via_context() -> None: """item_reference entries are resolved to concrete OutputItem for persistence.""" - inline_msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(text="hi")]) + inline_msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(type="input_text", text="hi")]) ref = ItemReferenceParam(id="item_ref1") resolved = OutputItemMessage(id="item_ref1", role="assistant", content=[], status="completed") provider = _mock_provider(get_items_return=[resolved]) @@ -68,7 +68,7 @@ async def test_resolves_references_via_context() -> None: # Should have BOTH items: resolved reference + inline message assert result is not None assert len(result) == 2 - assert all(isinstance(item, OutputItemMessage) for item in result) + assert all(isinstance(item, dict) and item.get("type") == "message" for item in result) # ------------------------------------------------------------------ @@ -79,7 +79,7 @@ async def test_resolves_references_via_context() -> None: @pytest.mark.asyncio async def test_fallback_when_no_context() -> None: """When context is None, returns the fallback items.""" - msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(text="hi")]) + msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(type="input_text", text="hi")]) fallback = [out for item in [msg] if (out := to_output_item(item, "resp_002")) is not None] result = await _resolve_input_items_for_persistence(None, fallback) @@ -96,7 +96,7 @@ async def test_fallback_when_no_context() -> None: @pytest.mark.asyncio async def test_fallback_on_resolution_error() -> None: """When context._get_input_items_for_persistence raises, falls back.""" - msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(text="hi")]) + msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(type="input_text", text="hi")]) ref = ItemReferenceParam(id="item_bad") provider = _mock_provider() provider.get_items = AsyncMock(side_effect=RuntimeError("provider down")) diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_response_context_input_items.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_response_context_input_items.py index bc878b06b8b7..9b0d28e39bfe 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_response_context_input_items.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_response_context_input_items.py @@ -10,7 +10,7 @@ import pytest from azure.ai.agentserver.responses._response_context import PlatformContext, ResponseContext -from azure.ai.agentserver.responses.models._generated import ( +from azure.ai.extensions.openai.responses import ( CreateResponse, Item, ItemMessage, @@ -39,6 +39,19 @@ def _make_request(inp: Any) -> CreateResponse: return CreateResponse(model="test-model", input=inp) +def _assert_message(item: Any, role: str | MessageRole | None = None) -> None: + assert isinstance(item, dict) + assert item.get("type") == "message" + if role is not None: + assert item.get("role") == role + + +def _assert_output_message(item: Any) -> None: + _assert_message(item) + assert str(item.get("id", "")).startswith("msg_") or str(item.get("id", "")).startswith("item_") + assert item.get("status") == "completed" + + # ------------------------------------------------------------------ # Basic: no references — items pass through as-is # ------------------------------------------------------------------ @@ -47,7 +60,7 @@ def _make_request(inp: Any) -> CreateResponse: @pytest.mark.asyncio async def test_get_input_items__no_references_passes_through() -> None: """Inline items are returned as Item subtypes (ItemMessage).""" - msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(text="hello")]) + msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(type="input_text", text="hello")]) request = _make_request([msg]) ctx = ResponseContext( response_id="resp_001", @@ -59,9 +72,7 @@ async def test_get_input_items__no_references_passes_through() -> None: items = await ctx.get_input_items() assert len(items) == 1 - assert isinstance(items[0], ItemMessage) - assert isinstance(items[0], Item) - assert items[0].role == MessageRole.USER + _assert_message(items[0], MessageRole.USER) # ------------------------------------------------------------------ @@ -88,9 +99,8 @@ async def test_get_input_items__resolves_single_reference() -> None: items = await ctx.get_input_items() assert len(items) == 1 - # Resolved via to_item(): OutputItemMessage → ItemMessage - assert isinstance(items[0], ItemMessage) - assert items[0].role == "assistant" + # Resolved via to_item(): OutputItemMessage -> Item wire payload + _assert_message(items[0], "assistant") provider.get_items.assert_awaited_once_with(["item_abc"], context=ctx.platform_context) @@ -102,7 +112,7 @@ async def test_get_input_items__resolves_single_reference() -> None: @pytest.mark.asyncio async def test_get_input_items__mixed_inline_and_references() -> None: """Inline items and references are interleaved; references are resolved in-place.""" - inline_msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(text="hi")]) + inline_msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(type="input_text", text="hi")]) ref1 = ItemReferenceParam(id="item_111") ref2 = ItemReferenceParam(id="item_222") resolved1 = OutputItemMessage(id="item_111", role="assistant", content=[], status="completed") @@ -120,13 +130,11 @@ async def test_get_input_items__mixed_inline_and_references() -> None: items = await ctx.get_input_items() - # inline passed through as Item, references resolved via to_item() + # inline passed through as Item wire payload, references resolved via to_item() assert len(items) == 3 - assert isinstance(items[0], ItemMessage) - assert isinstance(items[1], ItemMessage) # resolved from OutputItemMessage - assert items[1].role == "assistant" - assert isinstance(items[2], ItemMessage) # resolved from OutputItemMessage - assert items[2].role == "user" + _assert_message(items[0], MessageRole.USER) + _assert_message(items[1], "assistant") # resolved from OutputItemMessage + _assert_message(items[2], "user") # resolved from OutputItemMessage # ------------------------------------------------------------------ @@ -154,7 +162,7 @@ async def test_get_input_items__unresolvable_references_dropped() -> None: items = await ctx.get_input_items() assert len(items) == 1 - assert isinstance(items[0], ItemMessage) # resolved via to_item() + _assert_message(items[0]) # resolved via to_item() # ------------------------------------------------------------------ @@ -165,7 +173,7 @@ async def test_get_input_items__unresolvable_references_dropped() -> None: @pytest.mark.asyncio async def test_get_input_items__no_provider_no_resolution() -> None: """Without a provider, ItemReferenceParam entries are silently dropped (unresolvable).""" - inline_msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(text="hi")]) + inline_msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(type="input_text", text="hi")]) ref = ItemReferenceParam(id="item_xyz") request = _make_request([inline_msg, ref]) @@ -179,9 +187,9 @@ async def test_get_input_items__no_provider_no_resolution() -> None: items = await ctx.get_input_items() - # inline item returned as Item subtype; reference placeholder is dropped + # inline item returned as Item wire payload; reference placeholder is dropped assert len(items) == 1 - assert isinstance(items[0], ItemMessage) + _assert_message(items[0], MessageRole.USER) # ------------------------------------------------------------------ @@ -232,8 +240,7 @@ async def test_get_input_items__string_input_expanded() -> None: items = await ctx.get_input_items() assert len(items) == 1 - assert isinstance(items[0], ItemMessage) - assert items[0].role == MessageRole.USER + _assert_message(items[0], MessageRole.USER) # ------------------------------------------------------------------ @@ -283,7 +290,7 @@ async def test_get_input_items__forwards_platform_context() -> None: items = await ctx.get_input_items() assert len(items) == 1 - assert isinstance(items[0], ItemMessage) # resolved via to_item() + _assert_message(items[0]) # resolved via to_item() provider.get_items.assert_awaited_once_with(["item_iso"], context=isolation) @@ -321,9 +328,9 @@ async def test_get_input_items__all_references_unresolvable() -> None: @pytest.mark.asyncio async def test_get_input_items__preserves_order() -> None: """Order of inline items and resolved references matches input order.""" - msg1 = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(text="first")]) + msg1 = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(type="input_text", text="first")]) ref = ItemReferenceParam(id="item_mid") - msg2 = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(text="last")]) + msg2 = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(type="input_text", text="last")]) resolved = OutputItemMessage(id="item_mid", role="assistant", content=[], status="completed") provider = _mock_provider(get_items_return=[resolved]) @@ -339,10 +346,9 @@ async def test_get_input_items__preserves_order() -> None: items = await ctx.get_input_items() assert len(items) == 3 - assert isinstance(items[0], ItemMessage) - assert isinstance(items[1], ItemMessage) # resolved via to_item() - assert items[1].role == "assistant" - assert isinstance(items[2], ItemMessage) + _assert_message(items[0], MessageRole.USER) + _assert_message(items[1], "assistant") # resolved via to_item() + _assert_message(items[2], MessageRole.USER) # ------------------------------------------------------------------ @@ -352,13 +358,11 @@ async def test_get_input_items__preserves_order() -> None: def test_to_output_item__converts_item_message() -> None: """ItemMessage is converted to OutputItemMessage with generated ID.""" - msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(text="hello")]) + msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(type="input_text", text="hello")]) result = to_output_item(msg, "resp_123") assert result is not None - assert isinstance(result, OutputItemMessage) - assert result.id.startswith("msg_") - assert result.status == "completed" - assert result.role == MessageRole.USER + _assert_output_message(result) + assert result["role"] == MessageRole.USER def test_to_output_item__returns_none_for_reference() -> None: @@ -376,7 +380,7 @@ def test_to_output_item__returns_none_for_reference() -> None: @pytest.mark.asyncio async def test_get_input_items_for_persistence__resolves_references() -> None: """_get_input_items_for_persistence resolves item_reference entries to OutputItem.""" - inline_msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(text="hi")]) + inline_msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(type="input_text", text="hi")]) ref = ItemReferenceParam(id="item_ref1") resolved = OutputItemMessage(id="item_ref1", role="assistant", content=[], status="completed") provider = _mock_provider(get_items_return=[resolved]) @@ -394,13 +398,13 @@ async def test_get_input_items_for_persistence__resolves_references() -> None: # Both items should be converted to OutputItem — including the resolved reference assert len(output_items) == 2 - assert all(isinstance(item, OutputItemMessage) for item in output_items) + assert all(isinstance(item, dict) and item.get("type") == "message" for item in output_items) @pytest.mark.asyncio async def test_get_input_items_for_persistence__no_references_passes_through() -> None: """When no references exist, all inline items are returned as OutputItem.""" - msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(text="hello")]) + msg = ItemMessage(role=MessageRole.USER, content=[MessageContentInputTextContent(type="input_text", text="hello")]) request = _make_request([msg]) ctx = ResponseContext( response_id="resp_persist_002", @@ -412,7 +416,7 @@ async def test_get_input_items_for_persistence__no_references_passes_through() - output_items = await ctx._get_input_items_for_persistence() assert len(output_items) == 1 - assert isinstance(output_items[0], OutputItemMessage) + _assert_output_message(output_items[0]) @pytest.mark.asyncio diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_response_event_stream_builder.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_response_event_stream_builder.py index 8a6cbec03e56..dfcb3e17ff04 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_response_event_stream_builder.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_response_event_stream_builder.py @@ -7,19 +7,9 @@ import pytest from azure.ai.agentserver.responses._id_generator import IdGenerator -from azure.ai.agentserver.responses.models import _generated as generated_models -from azure.ai.agentserver.responses.models._generated import ( +from azure.ai.extensions.openai.responses import ( AgentReference, - OutputItemComputerToolCallOutputResource, - ResponseCompletedEvent, - ResponseCreatedEvent, - ResponseFailedEvent, - ResponseIncompleteEvent, - ResponseInProgressEvent, - ResponseObject, - ResponseOutputItemAddedEvent, - ResponseOutputItemDoneEvent, - ResponseStreamEvent, + CreateResponse, ResponseUsage, ) from azure.ai.agentserver.responses.streaming._event_stream import ResponseEventStream @@ -38,12 +28,9 @@ def test_event_stream_builder__builds_lifecycle_events() -> None: stream.emit_completed(), ] - # All events must be typed ResponseStreamEvent subtypes + # All events must be dict-native ResponseStreamEvent wire payloads. for event in events: - assert isinstance(event, ResponseStreamEvent), f"Expected ResponseStreamEvent, got {type(event)}" - assert isinstance(events[0], ResponseCreatedEvent) - assert isinstance(events[1], ResponseInProgressEvent) - assert isinstance(events[2], ResponseCompletedEvent) + assert isinstance(event, dict), f"Expected ResponseStreamEvent dict, got {type(event)}" assert [event["type"] for event in events] == [ "response.created", @@ -73,7 +60,7 @@ def test_event_stream_builder__builds_output_item_events() -> None: ] for event in events: - assert isinstance(event, ResponseStreamEvent), f"Expected ResponseStreamEvent, got {type(event)}" + assert isinstance(event, dict), f"Expected ResponseStreamEvent dict, got {type(event)}" event_types = [event["type"] for event in events] assert "response.output_item.added" in event_types @@ -93,8 +80,7 @@ def test_event_stream_builder__output_item_added_returns_event_immediately() -> emitted = message.emit_added() - assert isinstance(emitted, ResponseStreamEvent) - assert isinstance(emitted, ResponseOutputItemAddedEvent) + assert isinstance(emitted, dict) assert emitted["type"] == "response.output_item.added" assert emitted["output_index"] == 0 assert emitted["item"]["id"] == message.item_id @@ -153,12 +139,11 @@ def test_event_stream_builder__emit_completed_accepts_usage_and_sets_terminal_fi completed = stream.emit_completed(usage=usage) - assert isinstance(completed, ResponseStreamEvent) - assert isinstance(completed, ResponseCompletedEvent) + assert isinstance(completed, dict) assert completed["type"] == "response.completed" assert completed["response"]["status"] == "completed" assert completed["response"]["usage"]["total_tokens"] == 3 - assert isinstance(completed["response"]["completed_at"], int) + assert completed["response"]["completed_at"] is not None def test_event_stream_builder__emit_failed_accepts_error_and_usage() -> None: @@ -175,8 +160,7 @@ def test_event_stream_builder__emit_failed_accepts_error_and_usage() -> None: failed = stream.emit_failed(code="server_error", message="boom", usage=usage) - assert isinstance(failed, ResponseStreamEvent) - assert isinstance(failed, ResponseFailedEvent) + assert isinstance(failed, dict) assert failed["type"] == "response.failed" assert failed["response"]["status"] == "failed" assert failed["response"]["error"]["code"] == "server_error" @@ -199,8 +183,7 @@ def test_event_stream_builder__emit_incomplete_accepts_reason_and_usage() -> Non incomplete = stream.emit_incomplete(reason="max_output_tokens", usage=usage) - assert isinstance(incomplete, ResponseStreamEvent) - assert isinstance(incomplete, ResponseIncompleteEvent) + assert isinstance(incomplete, dict) assert incomplete["type"] == "response.incomplete" assert incomplete["response"]["status"] == "incomplete" assert incomplete["response"]["incomplete_details"]["reason"] == "max_output_tokens" @@ -214,32 +197,26 @@ def test_event_stream_builder__add_output_item_generic_emits_added_and_done() -> item_id = IdGenerator.new_computer_call_output_item_id("resp_builder_generic_item") builder = stream.add_output_item(item_id) - added_item = OutputItemComputerToolCallOutputResource( - { - "id": item_id, - "type": "computer_call_output", - "call_id": "call_1", - "output": {"type": "computer_screenshot", "image_url": "https://example.com/1.png"}, - "status": "in_progress", - } - ) - done_item = OutputItemComputerToolCallOutputResource( - { - "id": item_id, - "type": "computer_call_output", - "call_id": "call_1", - "output": {"type": "computer_screenshot", "image_url": "https://example.com/2.png"}, - "status": "completed", - } - ) + added_item = { + "id": item_id, + "type": "computer_call_output", + "call_id": "call_1", + "output": {"type": "computer_screenshot", "image_url": "https://example.com/1.png"}, + "status": "in_progress", + } + done_item = { + "id": item_id, + "type": "computer_call_output", + "call_id": "call_1", + "output": {"type": "computer_screenshot", "image_url": "https://example.com/2.png"}, + "status": "completed", + } added = builder.emit_added(added_item) done = builder.emit_done(done_item) - assert isinstance(added, ResponseStreamEvent) - assert isinstance(added, ResponseOutputItemAddedEvent) - assert isinstance(done, ResponseStreamEvent) - assert isinstance(done, ResponseOutputItemDoneEvent) + assert isinstance(added, dict) + assert isinstance(done, dict) assert added["type"] == "response.output_item.added" assert added["output_index"] == 0 assert done["type"] == "response.output_item.done" @@ -247,28 +224,26 @@ def test_event_stream_builder__add_output_item_generic_emits_added_and_done() -> def test_event_stream_builder__constructor_accepts_seed_response() -> None: - seed_response = generated_models.ResponseObject( - { - "id": "resp_builder_seed_response", - "object": "response", - "output": [], - "model": "gpt-4o-mini", - "metadata": {"source": "seed"}, - } - ) + seed_response = { + "id": "resp_builder_seed_response", + "object": "response", + "output": [], + "model": "gpt-4o-mini", + "metadata": {"source": "seed"}, + } stream = ResponseEventStream(response=seed_response) created = stream.emit_created() - assert isinstance(stream.response, ResponseObject) - assert isinstance(created, ResponseCreatedEvent) + assert isinstance(stream.response, dict) + assert created["type"] == "response.created" assert created["response"]["id"] == "resp_builder_seed_response" assert created["response"]["model"] == "gpt-4o-mini" assert created["response"]["metadata"] == {"source": "seed"} def test_event_stream_builder__constructor_accepts_request_seed_fields() -> None: - request = generated_models.CreateResponse( + request = CreateResponse( { "model": "gpt-4o-mini", "background": True, diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_response_execution.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_response_execution.py index 5f8bfcaf9952..a360e2503443 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_response_execution.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_response_execution.py @@ -188,7 +188,7 @@ def test_apply_event_cancelled_is_noop() -> None: def test_apply_event_output_item_added() -> None: - from azure.ai.agentserver.responses.models._generated import ResponseObject + from azure.ai.extensions.openai.responses import ResponseObject execution = _make_execution(status="in_progress") execution.response = ResponseObject( diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_runtime_state.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_runtime_state.py index 57ff645d1fd8..16190dd1f735 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_runtime_state.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_runtime_state.py @@ -7,7 +7,7 @@ import pytest from azure.ai.agentserver.responses.hosting._runtime_state import _RuntimeState -from azure.ai.agentserver.responses.models._generated import ResponseObject +from azure.ai.extensions.openai.responses import ResponseObject from azure.ai.agentserver.responses.models.runtime import ResponseExecution, ResponseModeFlags # --------------------------------------------------------------------------- diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_session_and_response_id_resolution.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_session_and_response_id_resolution.py index b0d8ec5ef71e..d9783017bdb5 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_session_and_response_id_resolution.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_session_and_response_id_resolution.py @@ -25,25 +25,8 @@ # --------------------------------------------------------------------------- -class _FakeParsed: - """Minimal stub matching the CreateResponse model interface.""" - - def __init__(self, **kwargs): - for key, value in kwargs.items(): - setattr(self, key, value) - if not hasattr(self, "agent_reference"): - self.agent_reference = None - if not hasattr(self, "conversation"): - self.conversation = None - if not hasattr(self, "previous_response_id"): - self.previous_response_id = None - - def as_dict(self): - d = {} - for key in ("response_id", "agent_reference", "conversation", "previous_response_id", "agent_session_id"): - if hasattr(self, key): - d[key] = getattr(self, key) - return d +class _FakeParsed(dict): + """Minimal dict-native parsed CreateResponse payload.""" # =================================================================== diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_sse_writer.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_sse_writer.py index 259063f82960..a70a2cdc98a6 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_sse_writer.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_sse_writer.py @@ -7,15 +7,8 @@ from azure.ai.agentserver.responses.streaming import _sse -class _FakeEvent: - def __init__(self, type: str, sequence_number: int, text: str) -> None: - self.type = type - self.sequence_number = sequence_number - self.text = text - - def test_sse_writer__encodes_event_and_data_lines_with_separator() -> None: - event = _FakeEvent(type="response.created", sequence_number=0, text="hello") + event = {"type": "response.created", "sequence_number": 0, "text": "hello"} encoded = _sse.encode_sse_event(event) # type: ignore[arg-type] assert encoded.startswith("event: response.created\n") @@ -24,7 +17,7 @@ def test_sse_writer__encodes_event_and_data_lines_with_separator() -> None: def test_sse_writer__encodes_multiline_text_as_single_data_line() -> None: - event = _FakeEvent(type="response.output_text.delta", sequence_number=1, text="line1\nline2") + event = {"type": "response.output_text.delta", "sequence_number": 1, "text": "line1\nline2"} encoded = _sse.encode_sse_event(event) # type: ignore[arg-type] # Spec requires a single data: line with JSON payload — no extra data: lines @@ -43,8 +36,8 @@ def test_sse_writer__injects_monotonic_sequence_numbers() -> None: _sse.new_stream_counter() - first_event = _FakeEvent(type="response.created", sequence_number=-1, text="a") - second_event = _FakeEvent(type="response.in_progress", sequence_number=-1, text="b") + first_event = {"type": "response.created", "sequence_number": -1, "text": "a"} + second_event = {"type": "response.in_progress", "sequence_number": -1, "text": "b"} encoded_first = _sse.encode_sse_event(first_event) # type: ignore[arg-type] encoded_second = _sse.encode_sse_event(second_event) # type: ignore[arg-type] diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_string_content_expansion.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_string_content_expansion.py index ea491c95c2b5..af695e11678a 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_string_content_expansion.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_string_content_expansion.py @@ -11,7 +11,7 @@ import pytest -from azure.ai.agentserver.responses.models._generated import ( +from azure.ai.extensions.openai.responses import ( CreateResponse, ItemMessage, MessageContentInputTextContent, @@ -35,8 +35,8 @@ def test_get_content_expanded__string_content_wraps_as_input_text() -> None: parts = get_content_expanded(msg) assert len(parts) == 1 - assert isinstance(parts[0], MessageContentInputTextContent) - assert parts[0].text == "Hello world" + assert parts[0]["type"] == "input_text" + assert parts[0]["text"] == "Hello world" def test_get_content_expanded__empty_string_returns_empty_list() -> None: @@ -51,12 +51,12 @@ def test_get_content_expanded__list_content_passes_through() -> None: """A list[MessageContent] should pass through unchanged.""" msg = ItemMessage( role=MessageRole.USER, - content=[MessageContentInputTextContent(text="part1")], + content=[MessageContentInputTextContent(type="input_text", text="part1")], ) parts = get_content_expanded(msg) assert len(parts) == 1 - assert parts[0].text == "part1" + assert parts[0]["text"] == "part1" def test_get_content_expanded__none_content_returns_empty() -> None: @@ -78,8 +78,8 @@ def test_get_content_expanded__dict_with_string_content() -> None: parts = get_content_expanded(msg) assert len(parts) == 1 - assert isinstance(parts[0], MessageContentInputTextContent) - assert parts[0].text == "dict string content" + assert parts[0]["type"] == "input_text" + assert parts[0]["text"] == "dict string content" # --------------------------------------------------------------------------- @@ -107,7 +107,7 @@ def test_get_input_text__mixed_string_and_list_content() -> None: ItemMessage(role=MessageRole.USER, content="First message"), ItemMessage( role=MessageRole.USER, - content=[MessageContentInputTextContent(text="Second message")], + content=[MessageContentInputTextContent(type="input_text", text="Second message")], ), ], ) @@ -164,12 +164,11 @@ def test_get_input_expanded__normalizes_string_content_to_list() -> None: assert len(items) == 1 msg = items[0] - assert isinstance(msg, ItemMessage) # content should now be a list, not a string - assert isinstance(msg.content, list) - assert len(msg.content) == 1 - assert isinstance(msg.content[0], MessageContentInputTextContent) - assert msg.content[0].text == "expanded text" + assert isinstance(msg["content"], list) + assert len(msg["content"]) == 1 + assert msg["content"][0]["type"] == "input_text" + assert msg["content"][0]["text"] == "expanded text" def test_get_input_expanded__list_content_unchanged() -> None: @@ -179,15 +178,15 @@ def test_get_input_expanded__list_content_unchanged() -> None: input=[ ItemMessage( role=MessageRole.USER, - content=[MessageContentInputTextContent(text="already a list")], + content=[MessageContentInputTextContent(type="input_text", text="already a list")], ), ], ) items = get_input_expanded(request) msg = items[0] - assert isinstance(msg.content, list) - assert msg.content[0].text == "already a list" + assert isinstance(msg["content"], list) + assert msg["content"][0]["text"] == "already a list" def test_get_input_expanded__string_input_shorthand_already_list() -> None: @@ -196,6 +195,6 @@ def test_get_input_expanded__string_input_shorthand_already_list() -> None: items = get_input_expanded(request) msg = items[0] - assert isinstance(msg, ItemMessage) - assert isinstance(msg.content, list) - assert msg.content[0].text == "plain string input" + assert msg["type"] == "message" + assert isinstance(msg["content"], list) + assert msg["content"][0]["text"] == "plain string input" diff --git a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_validation.py b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_validation.py index 3a62ff1cc23e..02403acf9a25 100644 --- a/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_validation.py +++ b/sdk/agentserver/azure-ai-agentserver-responses/tests/unit/test_validation.py @@ -14,7 +14,7 @@ from azure.ai.agentserver.responses.models.errors import RequestValidationError -class _FakeCreateRequest: +class _FakeCreateRequest(dict): def __init__( self, store: bool | None = True, @@ -23,11 +23,13 @@ def __init__( stream_options: object | None = None, model: str | None = "gpt-4o-mini", ) -> None: - self.store = store - self.background = background - self.stream = stream - self.stream_options = stream_options - self.model = model + super().__init__( + store=store, + background=background, + stream=stream, + stream_options=stream_options, + model=model, + ) def test_validation__non_object_payload_returns_invalid_request() -> None: @@ -50,4 +52,4 @@ def test_validation__unexpected_exception_maps_to_bad_request_category() -> None error = ValueError("bad payload") envelope = to_api_error_response(error) - assert envelope.error.type == "invalid_request_error" + assert envelope["error"]["type"] == "invalid_request_error"