diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index f40d6a7cc215..e05e76e605ad 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -223,6 +223,13 @@ # PRLabel: %Digital Twins /sdk/digitaltwins/ @Aashish93-stack @johngallardo @Satya-Kolluri @sjiherzig +# AzureSdkOwners: @ahall-msft +# ServiceLabel: %Discovery +# ServiceOwners: @ahall-msft + +# PRLabel: %Discovery +/sdk/discovery/ @ahall-msft + # PRLabel: %Document Intelligence /sdk/documentintelligence/ @bojunehsu @yungshinlintw diff --git a/.vscode/cspell.json b/.vscode/cspell.json index 42501f5938ff..82ca0b271c71 100644 --- a/.vscode/cspell.json +++ b/.vscode/cspell.json @@ -1855,6 +1855,12 @@ "oeverify" ] }, + { + "filename": "sdk/discovery/azure-ai-discovery/**", + "words": [ + "deser" + ] + }, { "filename": "sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_operations/*.py", "words": [ diff --git a/sdk/discovery/azure-ai-discovery/CHANGELOG.md b/sdk/discovery/azure-ai-discovery/CHANGELOG.md index 9775dc81b7ff..72550b819f09 100644 --- a/sdk/discovery/azure-ai-discovery/CHANGELOG.md +++ b/sdk/discovery/azure-ai-discovery/CHANGELOG.md @@ -1,5 +1,38 @@ # Release History +## 1.0.0 (2026-07-25) + +General availability release of `azure-ai-discovery`. API version `2026-06-01` is now the default for both `WorkspaceClient` and `BookshelfClient`. + +### Features Added + +- **Workspace**: + - New paged list response models: `PagedConversation`, `PagedInvestigation`. + - New `StorageMountProtocol` enum for controlling storage mount protocols. + - New `tools.cancel_run_lro` long-running cancellation flow (in addition to the existing immediate `cancel_run`). + - Investigation `update` is now exposed via a documented sample. +- **Bookshelf**: knowledge-base surface is significantly redesigned around a single `KnowledgeBasesOperations` group that exposes the full lifecycle in one place: + - **Lifecycle**: `create_or_update`, `get`, `delete`, plus `get_operation_status` for polling long-running operations. + - **Indexing**: `start_indexing` and `cancel_indexing`, with results modeled via `KnowledgeBaseIndexingOperationResponse`, `IndexingOperationResult`, `IndexingMetrics`, and `LastIndexingRun`. + - **Search**: new `search` operation taking `SearchRequest` and returning `SearchResponse`, including `SearchResultItem` with `Citation` and `CitationType` for citation-aware results. + - **LRO results**: status responses now use `KnowledgeBaseOperationResponse` / `KnowledgeBaseSearchOperationResponse`; create/update returns the `KnowledgeBase` resource. + - New enum `KnowledgeBaseOperationType`. + +### Breaking Changes + +> Note: these are breaking changes only relative to the `1.0.0b1` preview release. As a first stable (GA) release, `1.0.0` is the new compatibility baseline going forward. + +- **Bookshelf**: the `KnowledgeBaseVersionsOperations` operation group is removed. Knowledge-base versioning has been folded into the unified `KnowledgeBasesOperations` group; callers using `client.knowledge_base_versions.` must migrate to the equivalent method on `client.knowledge_bases`. +- **Bookshelf**: the models `KnowledgeBaseOperationStatus` and `KnowledgeBaseVersion` are removed. Operation-status payloads are now typed as `KnowledgeBaseOperationResponse`, `KnowledgeBaseIndexingOperationResponse`, or `KnowledgeBaseSearchOperationResponse` depending on the operation; create/update returns the `KnowledgeBase` resource. +- The preview API version `2026-02-01-preview` is no longer listed as a supported value for the `api_version` kwarg. Both `WorkspaceClient` and `BookshelfClient` now default to `2026-06-01`. Pinning to the removed preview value is not supported in the GA SDK. +- **Workspace**: the investigations long-running operation status model, previously generated as `ResourceOperationStatusInvestigationInvestigationError`, has been renamed to `InvestigationOperationStatus`. The payload is unchanged; only the model name differs. + +### Other Changes + +- Regenerated against [Azure/azure-rest-api-specs PR #42884](https://github.com/Azure/azure-rest-api-specs/pull/42884) (commit `fbe3c49c541a2932f4a4cb348fb0798988f4aca4`). +- `Development Status` classifier flipped from `4 - Beta` to `5 - Production/Stable`. +- Emitter `@azure-tools/typespec-python` at `0.63.3`; the four hand-written client `_patch.py` overrides that expose `transport` and `api_version` as explicit keyword-only parameters remain in place pending future emitter support. + ## 1.0.0b1 (2026-05-16) Initial beta release of the Azure AI Discovery client library for Python. diff --git a/sdk/discovery/azure-ai-discovery/README.md b/sdk/discovery/azure-ai-discovery/README.md index 51e3335012e4..61f68a495e95 100644 --- a/sdk/discovery/azure-ai-discovery/README.md +++ b/sdk/discovery/azure-ai-discovery/README.md @@ -3,7 +3,7 @@ The Azure AI Discovery client library for Python provides two clients for interacting with Azure AI Discovery services: - **WorkspaceClient** — manage investigations, conversations, tasks, and tools in a Discovery workspace. -- **BookshelfClient** — manage knowledge bases and knowledge base versions. +- **BookshelfClient** — manage knowledge bases, including indexing and search. [Source code][source_code] | [Package (PyPI)][pypi] | [Samples][samples] @@ -59,8 +59,7 @@ The `WorkspaceClient` provides access to Discovery workspace operations, organiz The `BookshelfClient` provides access to knowledge base management: -- **Knowledge Bases** — list available knowledge bases. -- **Knowledge Base Versions** — create, update, index, and manage versions of knowledge bases backed by storage assets. +- **Knowledge Bases** — create, update, get, list, and delete knowledge bases backed by storage assets, run indexing as a long-running operation, and execute long-running search queries. ## Examples @@ -161,7 +160,7 @@ print(f"Run completed: {result.status}") ```python from azure.ai.discovery import BookshelfClient -from azure.ai.discovery.models import KnowledgeBaseVersion, StorageAssetReference +from azure.ai.discovery.models import KnowledgeBase, SearchRequest, StorageAssetReference from azure.identity import DefaultAzureCredential client = BookshelfClient( @@ -169,15 +168,14 @@ client = BookshelfClient( credential=DefaultAzureCredential(), ) -# List knowledge bases +# List knowledge bases (ItemPaged — transparent paging) for kb in client.knowledge_bases.list(): print(f"Knowledge base: {kb.name}") -# Create a knowledge base version -version = client.knowledge_base_versions.create_or_update( +# Create or update a knowledge base (long-running) +poller = client.knowledge_bases.begin_create_or_update( knowledge_base_name="my-kb", - version_name="v1", - resource=KnowledgeBaseVersion( + resource=KnowledgeBase( description="Research data for compound analysis", copilot_instruction="Use this to query information about compound interactions.", storage_asset_references=[ @@ -188,7 +186,21 @@ version = client.knowledge_base_versions.create_or_update( ], ), ) -print(f"Created version: {version.name}") +kb = poller.result() +print(f"Created knowledge base: {kb.name}") + +# Run indexing (long-running) +client.knowledge_bases.begin_start_indexing( + knowledge_base_name="my-kb", + node_pool_id="/subscriptions/.../nodePools/my-pool", + project_id="/subscriptions/.../projects/my-project", +).result() + +# Search the knowledge base (long-running) +client.knowledge_bases.begin_search( + knowledge_base_name="my-kb", + body=SearchRequest(query="What are common drug interactions?"), +).result() ``` ## Troubleshooting diff --git a/sdk/discovery/azure-ai-discovery/_metadata.json b/sdk/discovery/azure-ai-discovery/_metadata.json new file mode 100644 index 000000000000..92b6ba1a90f6 --- /dev/null +++ b/sdk/discovery/azure-ai-discovery/_metadata.json @@ -0,0 +1,6 @@ +{ + "apiVersions": { + "Microsoft.Discovery.Bookshelf": "2026-06-01", + "Microsoft.Discovery.Workspace": "2026-06-01" + } +} \ No newline at end of file diff --git a/sdk/discovery/azure-ai-discovery/api.md b/sdk/discovery/azure-ai-discovery/api.md new file mode 100644 index 000000000000..2fa02ce5091b --- /dev/null +++ b/sdk/discovery/azure-ai-discovery/api.md @@ -0,0 +1,2763 @@ +```py +namespace azure.ai.discovery + + class azure.ai.discovery.BookshelfClient(_GeneratedBookshelfClient): implements ContextManager + + def __init__( + self, + endpoint: str, + credential: TokenCredential, + *, + api_version: Optional[str] = ..., + transport: Optional[HttpTransport] = ..., + **kwargs: Any + ) -> None: ... + + def close(self) -> None: ... + + def send_request( + self, + request: HttpRequest, + *, + stream: bool = False, + **kwargs: Any + ) -> HttpResponse: ... + + + class azure.ai.discovery.WorkspaceClient(_GeneratedWorkspaceClient): implements ContextManager + + def __init__( + self, + endpoint: str, + credential: TokenCredential, + *, + api_version: Optional[str] = ..., + transport: Optional[HttpTransport] = ..., + **kwargs: Any + ) -> None: ... + + def close(self) -> None: ... + + def send_request( + self, + request: HttpRequest, + *, + stream: bool = False, + **kwargs: Any + ) -> HttpResponse: ... + + +namespace azure.ai.discovery.aio + + class azure.ai.discovery.aio.BookshelfClient(_GeneratedBookshelfClient): implements AsyncContextManager + + def __init__( + self, + endpoint: str, + credential: AsyncTokenCredential, + *, + api_version: Optional[str] = ..., + transport: Optional[AsyncHttpTransport] = ..., + **kwargs: Any + ) -> None: ... + + async def close(self) -> None: ... + + def send_request( + self, + request: HttpRequest, + *, + stream: bool = False, + **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: ... + + + class azure.ai.discovery.aio.WorkspaceClient(_GeneratedWorkspaceClient): implements AsyncContextManager + + def __init__( + self, + endpoint: str, + credential: AsyncTokenCredential, + *, + api_version: Optional[str] = ..., + transport: Optional[AsyncHttpTransport] = ..., + **kwargs: Any + ) -> None: ... + + async def close(self) -> None: ... + + def send_request( + self, + request: HttpRequest, + *, + stream: bool = False, + **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: ... + + +namespace azure.ai.discovery.aio.operations + + class azure.ai.discovery.aio.operations.ConversationsOperations: + + def __init__( + self, + *args, + **kwargs + ) -> None: ... + + @overload + async def create( + self, + *, + content_type: str = "application/json", + display_name: Optional[str] = ..., + investigation_name: Optional[str] = ..., + project_name: str, + **kwargs: Any + ) -> Conversation: ... + + @overload + async def create( + self, + body: CreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Conversation: ... + + @overload + async def create( + self, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Conversation: ... + + @distributed_trace_async + async def delete( + self, + conversation_name: str, + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def get( + self, + conversation_name: str, + **kwargs: Any + ) -> Conversation: ... + + @distributed_trace_async + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'investigation_name', 'project_name', 'created_since', 'top', 'skip', 'maxpagesize', 'accept']}, api_versions_list=['2026-06-01']) + async def list( + self, + *, + created_since: Optional[datetime] = ..., + investigation_name: Optional[str] = ..., + project_name: Optional[str] = ..., + skip: Optional[int] = ..., + top: Optional[int] = ..., + **kwargs: Any + ) -> PagedConversation: ... + + @overload + async def stable_update( + self, + conversation_name: str, + resource: Conversation, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> Conversation: ... + + @overload + async def stable_update( + self, + conversation_name: str, + resource: Conversation, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> Conversation: ... + + @overload + async def stable_update( + self, + conversation_name: str, + resource: IO[bytes], + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> Conversation: ... + + + class azure.ai.discovery.aio.operations.InvestigationsOperations: + + def __init__( + self, + *args, + **kwargs + ) -> None: ... + + @distributed_trace_async + async def begin_delete( + self, + project_name: str, + investigation_name: str, + **kwargs: Any + ) -> AsyncLROPoller[Investigation]: ... + + @overload + async def create_or_replace( + self, + project_name: str, + investigation_name: str, + resource: Investigation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Investigation: ... + + @overload + async def create_or_replace( + self, + project_name: str, + investigation_name: str, + resource: Investigation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Investigation: ... + + @overload + async def create_or_replace( + self, + project_name: str, + investigation_name: str, + resource: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Investigation: ... + + @distributed_trace_async + async def get( + self, + project_name: str, + investigation_name: str, + **kwargs: Any + ) -> Investigation: ... + + @distributed_trace_async + async def get_discovery_engine( + self, + project_name: str, + investigation_name: str, + **kwargs: Any + ) -> DiscoveryEngine: ... + + @distributed_trace_async + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'project_name', 'investigation_name', 'top', 'skip', 'maxpagesize', 'accept']}, api_versions_list=['2026-06-01']) + async def get_discovery_engine_memory( + self, + project_name: str, + investigation_name: str, + *, + skip: Optional[int] = ..., + top: Optional[int] = ..., + **kwargs: Any + ) -> PagedWorkingMemoryEntry: ... + + @distributed_trace_async + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'project_name', 'investigation_name', 'operation_id', 'accept']}, api_versions_list=['2026-06-01']) + async def get_operation_status( + self, + project_name: str, + investigation_name: str, + operation_id: str, + **kwargs: Any + ) -> InvestigationOperationStatus: ... + + @distributed_trace_async + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'project_name', 'created_since', 'top', 'skip', 'maxpagesize', 'accept']}, api_versions_list=['2026-06-01']) + async def list( + self, + project_name: str, + *, + created_since: Optional[datetime] = ..., + skip: Optional[int] = ..., + top: Optional[int] = ..., + **kwargs: Any + ) -> PagedInvestigation: ... + + @distributed_trace_async + async def start_discovery_engine( + self, + project_name: str, + investigation_name: str, + **kwargs: Any + ) -> DiscoveryEngine: ... + + @distributed_trace_async + async def stop_discovery_engine( + self, + project_name: str, + investigation_name: str, + **kwargs: Any + ) -> DiscoveryEngine: ... + + @overload + async def update( + self, + project_name: str, + investigation_name: str, + resource: Investigation, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> Investigation: ... + + @overload + async def update( + self, + project_name: str, + investigation_name: str, + resource: Investigation, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> Investigation: ... + + @overload + async def update( + self, + project_name: str, + investigation_name: str, + resource: IO[bytes], + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> Investigation: ... + + @overload + async def update_discovery_engine( + self, + project_name: str, + investigation_name: str, + body: DiscoveryEngineUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> DiscoveryEngine: ... + + @overload + async def update_discovery_engine( + self, + project_name: str, + investigation_name: str, + body: DiscoveryEngineUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> DiscoveryEngine: ... + + @overload + async def update_discovery_engine( + self, + project_name: str, + investigation_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> DiscoveryEngine: ... + + + class azure.ai.discovery.aio.operations.KnowledgeBasesOperations(_GeneratedKnowledgeBasesOperations): + + def __init__( + self, + *args, + **kwargs + ) -> None: ... + + @distributed_trace_async + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'knowledge_base_name', 'repeatability_request_id', 'repeatability_first_sent', 'client_request_id', 'accept']}, api_versions_list=['2026-06-01']) + async def begin_cancel_indexing( + self, + knowledge_base_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: ... + + async def begin_create_or_update( + self, + knowledge_base_name: str, + resource: Union[KnowledgeBase, dict[str, Any], IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[KnowledgeBase]: ... + + @distributed_trace_async + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'knowledge_base_name', 'accept']}, api_versions_list=['2026-06-01']) + async def begin_delete( + self, + knowledge_base_name: str, + **kwargs: Any + ) -> AsyncLROPoller[None]: ... + + @overload + async def begin_search( + self, + knowledge_base_name: str, + body: SearchRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: ... + + @overload + async def begin_search( + self, + knowledge_base_name: str, + body: SearchRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: ... + + @overload + async def begin_search( + self, + knowledge_base_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: ... + + @overload + async def begin_start_indexing( + self, + knowledge_base_name: str, + *, + content_type: str = "application/json", + node_pool_id: Optional[str] = ..., + project_id: Optional[str] = ..., + **kwargs: Any + ) -> AsyncLROPoller[None]: ... + + @overload + async def begin_start_indexing( + self, + knowledge_base_name: str, + body: StartIndexingRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: ... + + @overload + async def begin_start_indexing( + self, + knowledge_base_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: ... + + @distributed_trace_async + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'knowledge_base_name', 'accept']}, api_versions_list=['2026-06-01']) + async def get( + self, + knowledge_base_name: str, + **kwargs: Any + ) -> KnowledgeBase: ... + + @distributed_trace_async + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'knowledge_base_name', 'operation_id', 'accept']}, api_versions_list=['2026-06-01']) + async def get_operation_status( + self, + knowledge_base_name: str, + operation_id: str, + **kwargs: Any + ) -> KnowledgeBaseOperationResponse: ... + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncItemPaged[KnowledgeBase]: ... + + + class azure.ai.discovery.aio.operations.TasksOperations: + + def __init__( + self, + *args, + **kwargs + ) -> None: ... + + @overload + async def add_comment( + self, + project_name: str, + investigation_name: str, + task_name: str, + body: TaskComment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + async def add_comment( + self, + project_name: str, + investigation_name: str, + task_name: str, + body: TaskComment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + async def add_comment( + self, + project_name: str, + investigation_name: str, + task_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + async def add_execution_history( + self, + project_name: str, + investigation_name: str, + task_name: str, + body: ExecutionHistoryEntry, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + async def add_execution_history( + self, + project_name: str, + investigation_name: str, + task_name: str, + body: ExecutionHistoryEntry, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + async def add_execution_history( + self, + project_name: str, + investigation_name: str, + task_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + async def create( + self, + project_name: str, + investigation_name: str, + body: Task, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + async def create( + self, + project_name: str, + investigation_name: str, + body: Task, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + async def create( + self, + project_name: str, + investigation_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @distributed_trace_async + async def delete( + self, + project_name: str, + investigation_name: str, + task_name: str, + **kwargs: Any + ) -> None: ... + + @distributed_trace_async + async def get( + self, + project_name: str, + investigation_name: str, + task_name: str, + **kwargs: Any + ) -> Task: ... + + @distributed_trace + def list( + self, + project_name: str, + investigation_name: str, + *, + filter: Optional[str] = ..., + **kwargs: Any + ) -> AsyncItemPaged[Task]: ... + + @overload + async def stable_update( + self, + project_name: str, + investigation_name: str, + task_name: str, + resource: Task, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> Task: ... + + @overload + async def stable_update( + self, + project_name: str, + investigation_name: str, + task_name: str, + resource: Task, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> Task: ... + + @overload + async def stable_update( + self, + project_name: str, + investigation_name: str, + task_name: str, + resource: IO[bytes], + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> Task: ... + + @overload + async def start( + self, + project_name: str, + investigation_name: str, + task_name: str, + body: Optional[StartTaskRequest] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + async def start( + self, + project_name: str, + investigation_name: str, + task_name: str, + body: Optional[StartTaskRequest] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + async def start( + self, + project_name: str, + investigation_name: str, + task_name: str, + body: Optional[IO[bytes]] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + + class azure.ai.discovery.aio.operations.ToolsOperations: + + def __init__( + self, + *args, + **kwargs + ) -> None: ... + + @distributed_trace_async + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'project_name', 'operation_id', 'accept']}, api_versions_list=['2026-06-01']) + async def begin_cancel_run_lro( + self, + project_name: str, + operation_id: str, + **kwargs: Any + ) -> AsyncLROPoller[RunResult]: ... + + @overload + async def begin_run( + self, + project_name: str, + *, + command: Optional[str] = ..., + content_type: str = "application/json", + environment_variables: Optional[List[RunRequestEnvironmentVariable]] = ..., + infra_overrides: Optional[InfraOverrides] = ..., + inline_files: Optional[List[InlineFile]] = ..., + input_data: Optional[List[InputDataMount]] = ..., + node_pool_ids: List[str], + output_data: Optional[List[OutputDataMount]] = ..., + tool_id: str, + **kwargs: Any + ) -> AsyncLROPoller[RunResult]: ... + + @overload + async def begin_run( + self, + project_name: str, + body: RunRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[RunResult]: ... + + @overload + async def begin_run( + self, + project_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[RunResult]: ... + + @distributed_trace_async + async def get_compute_usage( + self, + project_name: str, + **kwargs: Any + ) -> ComputeUsage: ... + + @distributed_trace_async + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'project_name', 'top', 'skip', 'maxpagesize', 'accept']}, api_versions_list=['2026-06-01']) + async def get_operations( + self, + project_name: str, + *, + skip: Optional[int] = ..., + top: Optional[int] = ..., + **kwargs: Any + ) -> PagedOperation: ... + + @distributed_trace_async + async def get_run_status( + self, + project_name: str, + operation_id: str, + *, + log_count: Optional[int] = ..., + **kwargs: Any + ) -> OperationStatusRunResultError: ... + + +namespace azure.ai.discovery.models + + class azure.ai.discovery.models.ByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + APPLICATION = "Application" + SYSTEM = "System" + USER = "User" + + + class azure.ai.discovery.models.Citation(_Model): + end_offset: Optional[int] + file_name: str + index: Optional[int] + start_offset: Optional[int] + type: Union[str, CitationType] + + @overload + def __init__( + self, + *, + end_offset: Optional[int] = ..., + file_name: str, + index: Optional[int] = ..., + start_offset: Optional[int] = ..., + type: Union[str, CitationType] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.CitationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + FILE_CITATION = "file_citation" + + + class azure.ai.discovery.models.ComputeUsage(_Model): + supercomputers: dict[str, SupercomputerUsage] + + @overload + def __init__( + self, + *, + supercomputers: dict[str, SupercomputerUsage] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.Conversation(_Model): + created_at: Optional[datetime] + created_by: Optional[str] + created_by_type: Optional[Union[str, ByType]] + display_name: Optional[str] + investigation_name: Optional[str] + last_modified_at: Optional[datetime] + last_modified_by: Optional[str] + last_modified_by_type: Optional[Union[str, ByType]] + name: str + project_name: Optional[str] + + @overload + def __init__( + self, + *, + created_at: Optional[datetime] = ..., + created_by: Optional[str] = ..., + created_by_type: Optional[Union[str, ByType]] = ..., + display_name: Optional[str] = ..., + investigation_name: Optional[str] = ..., + last_modified_at: Optional[datetime] = ..., + last_modified_by: Optional[str] = ..., + last_modified_by_type: Optional[Union[str, ByType]] = ..., + project_name: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.DiscoveryEngine(_Model): + configuration: Optional[dict[str, Any]] + created_at: Optional[datetime] + created_by: Optional[str] + created_by_type: Optional[Union[str, ByType]] + discovery_engine_status: Union[str, DiscoveryEngineStatus] + last_modified_at: Optional[datetime] + last_modified_by: Optional[str] + last_modified_by_type: Optional[Union[str, ByType]] + system_prompt: Optional[str] + + @overload + def __init__( + self, + *, + configuration: Optional[dict[str, Any]] = ..., + created_at: Optional[datetime] = ..., + created_by: Optional[str] = ..., + created_by_type: Optional[Union[str, ByType]] = ..., + discovery_engine_status: Union[str, DiscoveryEngineStatus], + last_modified_at: Optional[datetime] = ..., + last_modified_by: Optional[str] = ..., + last_modified_by_type: Optional[Union[str, ByType]] = ..., + system_prompt: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.DiscoveryEngineStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + ACTIVE = "Active" + INACTIVE = "Inactive" + + + class azure.ai.discovery.models.DiscoveryEngineUpdate(_Model): + configuration: Optional[dict[str, Any]] + system_prompt: Optional[str] + + @overload + def __init__( + self, + *, + configuration: Optional[dict[str, Any]] = ..., + system_prompt: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.ExecutionHistoryEntry(_Model): + action: str + additional_details: Optional[dict[str, Any]] + created_at: datetime + created_by: str + created_by_type: Union[str, ByType] + response_message_id: Optional[str] + response_message_text: Optional[str] + summary: Optional[str] + + @overload + def __init__( + self, + *, + action: str, + additional_details: Optional[dict[str, Any]] = ..., + created_at: datetime, + created_by: str, + created_by_type: Union[str, ByType], + response_message_id: Optional[str] = ..., + response_message_text: Optional[str] = ..., + summary: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.IndexingMetrics(_Model): + documents_failed: int + documents_processed: int + documents_total: int + enrichment_end_time_utc: Optional[datetime] + enrichment_start_time_utc: Optional[datetime] + indexing_end_time_utc: Optional[datetime] + indexing_percentage_complete: int + indexing_start_time_utc: Optional[datetime] + + @overload + def __init__( + self, + *, + documents_failed: int, + documents_processed: int, + documents_total: int, + enrichment_end_time_utc: Optional[datetime] = ..., + enrichment_start_time_utc: Optional[datetime] = ..., + indexing_end_time_utc: Optional[datetime] = ..., + indexing_percentage_complete: int, + indexing_start_time_utc: Optional[datetime] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.IndexingOperationResult(_Model): + metrics: Optional[IndexingMetrics] + run_id: str + + @overload + def __init__( + self, + *, + metrics: Optional[IndexingMetrics] = ..., + run_id: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.IndexingStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + CANCELED = "Canceled" + FAILED = "Failed" + NOT_STARTED = "NotStarted" + RUNNING = "Running" + SUCCEEDED = "Succeeded" + + + class azure.ai.discovery.models.InfraOverrides(_Model): + cpu: Optional[str] + gpu: Optional[str] + image_uri: Optional[str] + max_cpu: Optional[str] + max_gpu: Optional[str] + max_ram: Optional[str] + ram: Optional[str] + replica_count: Optional[int] + + @overload + def __init__( + self, + *, + cpu: Optional[str] = ..., + gpu: Optional[str] = ..., + image_uri: Optional[str] = ..., + max_cpu: Optional[str] = ..., + max_gpu: Optional[str] = ..., + max_ram: Optional[str] = ..., + ram: Optional[str] = ..., + replica_count: Optional[int] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.InlineFile(_Model): + encoded_file: str + mount_path: str + + @overload + def __init__( + self, + *, + encoded_file: str, + mount_path: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.InputDataMount(_Model): + mount_path: str + mount_protocol: Optional[Union[str, StorageMountProtocol]] + storage_uri: str + + @overload + def __init__( + self, + *, + mount_path: str, + mount_protocol: Optional[Union[str, StorageMountProtocol]] = ..., + storage_uri: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.Investigation(_Model): + created_at: Optional[datetime] + created_by: Optional[str] + created_by_type: Optional[Union[str, ByType]] + description: Optional[str] + display_name: Optional[str] + last_modified_at: Optional[datetime] + last_modified_by: Optional[str] + last_modified_by_type: Optional[Union[str, ByType]] + name: str + project_name: str + status: Optional[Union[str, InvestigationStatus]] + tags: Optional[list[Tag]] + + @overload + def __init__( + self, + *, + description: Optional[str] = ..., + display_name: Optional[str] = ..., + tags: Optional[list[Tag]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.InvestigationOperationStatus(_Model): + error: Optional[ODataV4Format] + id: str + result: Optional[Investigation] + status: Union[str, OperationState] + + @overload + def __init__( + self, + *, + error: Optional[ODataV4Format] = ..., + id: str, + result: Optional[Investigation] = ..., + status: Union[str, OperationState] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.InvestigationStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + CREATED = "Created" + FAILED = "Failed" + VALIDATED = "Validated" + + + class azure.ai.discovery.models.KnowledgeBase(_Model): + bookshelf_name: str + copilot_instruction: str + created_at: Optional[datetime] + created_by: Optional[str] + created_by_api_version: Optional[str] + created_by_type: Optional[Union[str, ByType]] + description: str + error: Optional[ODataV4Format] + id: Optional[str] + knowledge_base_url: Optional[str] + last_indexing_run: Optional[LastIndexingRun] + last_modified_at: Optional[datetime] + last_modified_by: Optional[str] + last_modified_by_type: Optional[Union[str, ByType]] + name: str + provisioning_state: Optional[Union[str, ProvisioningState]] + status: Optional[Union[str, IndexingStatus]] + storage_asset_references: Optional[list[StorageAssetReference]] + tags: Optional[list[Tag]] + + @overload + def __init__( + self, + *, + copilot_instruction: str, + description: str, + storage_asset_references: Optional[list[StorageAssetReference]] = ..., + tags: Optional[list[Tag]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.KnowledgeBaseIndexingOperationResponse(KnowledgeBaseOperationResponse, discriminator='Indexing'): + error: ODataV4Format + id: str + indexing_result: Optional[IndexingOperationResult] + operation_type: Literal[KnowledgeBaseOperationType.INDEXING] + status: Union[str, OperationState] + + @overload + def __init__( + self, + *, + error: Optional[ODataV4Format] = ..., + id: str, + indexing_result: Optional[IndexingOperationResult] = ..., + status: Union[str, OperationState] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.KnowledgeBaseOperationResponse(_Model): + error: Optional[ODataV4Format] + id: str + operation_type: str + status: Union[str, OperationState] + + @overload + def __init__( + self, + *, + error: Optional[ODataV4Format] = ..., + id: str, + operation_type: str, + status: Union[str, OperationState] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.KnowledgeBaseOperationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + CANCEL_INDEXING = "CancelIndexing" + DELETE = "Delete" + INDEXING = "Indexing" + SEARCH = "Search" + + + class azure.ai.discovery.models.KnowledgeBaseSearchOperationResponse(KnowledgeBaseOperationResponse, discriminator='Search'): + error: ODataV4Format + id: str + operation_type: Literal[KnowledgeBaseOperationType.SEARCH] + search_result: Optional[SearchResponse] + status: Union[str, OperationState] + + @overload + def __init__( + self, + *, + error: Optional[ODataV4Format] = ..., + id: str, + search_result: Optional[SearchResponse] = ..., + status: Union[str, OperationState] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.LastIndexingRun(_Model): + error: Optional[ODataV4Format] + indexing_metrics: Optional[IndexingMetrics] + run_id: Optional[str] + status: Optional[Union[str, IndexingStatus]] + + @overload + def __init__( + self, + *, + error: Optional[ODataV4Format] = ..., + indexing_metrics: Optional[IndexingMetrics] = ..., + run_id: Optional[str] = ..., + status: Optional[Union[str, IndexingStatus]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.NodepoolUsage(_Model): + allocatable_cp_us: str + allocatable_gp_us: str + allocatable_memory: str + reserved_cp_us: str + reserved_gp_us: str + reserved_memory: str + + @overload + def __init__( + self, + *, + allocatable_cp_us: str, + allocatable_gp_us: str, + allocatable_memory: str, + reserved_cp_us: str, + reserved_gp_us: str, + reserved_memory: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.Operation(_Model): + completed_at: Optional[datetime] + created_at: datetime + created_by: Optional[str] + id: str + nodepool_id: str + runtime_details: str + status: Union[str, RunStatus] + + @overload + def __init__( + self, + *, + completed_at: Optional[datetime] = ..., + created_at: datetime, + created_by: Optional[str] = ..., + id: str, + nodepool_id: str, + runtime_details: str, + status: Union[str, RunStatus] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.OperationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + CANCELED = "Canceled" + FAILED = "Failed" + NOT_STARTED = "NotStarted" + RUNNING = "Running" + SUCCEEDED = "Succeeded" + + + class azure.ai.discovery.models.OperationStatusRunResultError(_Model): + error: Optional[ODataV4Format] + id: str + result: Optional[RunResult] + status: Union[str, OperationState] + + @overload + def __init__( + self, + *, + error: Optional[ODataV4Format] = ..., + id: str, + result: Optional[RunResult] = ..., + status: Union[str, OperationState] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.OutputDataMount(_Model): + mount_path: str + mount_protocol: Optional[Union[str, StorageMountProtocol]] + storage_uri: str + + @overload + def __init__( + self, + *, + mount_path: str, + mount_protocol: Optional[Union[str, StorageMountProtocol]] = ..., + storage_uri: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.OutputDataUri(_Model): + mount_path: str + storage_uri: str + + @overload + def __init__( + self, + *, + mount_path: str, + storage_uri: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.PagedConversation(_Model): + next_link: Optional[str] + value: list[Conversation] + + @overload + def __init__( + self, + *, + next_link: Optional[str] = ..., + value: list[Conversation] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.PagedInvestigation(_Model): + next_link: Optional[str] + value: list[Investigation] + + @overload + def __init__( + self, + *, + next_link: Optional[str] = ..., + value: list[Investigation] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.PagedOperation(_Model): + next_link: Optional[str] + value: list[Operation] + + @overload + def __init__( + self, + *, + next_link: Optional[str] = ..., + value: list[Operation] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.PagedWorkingMemoryEntry(_Model): + next_link: Optional[str] + value: list[WorkingMemoryEntry] + + @overload + def __init__( + self, + *, + next_link: Optional[str] = ..., + value: list[WorkingMemoryEntry] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + ACCEPTED = "Accepted" + CANCELED = "Canceled" + DELETING = "Deleting" + FAILED = "Failed" + PROVISIONING = "Provisioning" + SUCCEEDED = "Succeeded" + UPDATING = "Updating" + + + class azure.ai.discovery.models.RepeatabilityResult(str, Enum, metaclass=CaseInsensitiveEnumMeta): + ACCEPTED = "accepted" + REJECTED = "rejected" + + + class azure.ai.discovery.models.RunRequestEnvironmentVariable(_Model): + name: str + value: Optional[str] + + @overload + def __init__( + self, + *, + name: str, + value: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.RunResult(_Model): + completed_at: Optional[datetime] + created_at: Optional[datetime] + created_by: Optional[str] + debug_info: str + output_data: list[OutputDataUri] + runtime_details: str + status: Optional[str] + tool_report: Optional[RunResultToolReport] + + @overload + def __init__( + self, + *, + created_by: Optional[str] = ..., + debug_info: str, + output_data: list[OutputDataUri], + runtime_details: str, + status: Optional[str] = ..., + tool_report: Optional[RunResultToolReport] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.RunResultToolReport(_Model): + logs: Optional[str] + percentage_complete: int + status_information: Optional[Any] + + @overload + def __init__( + self, + *, + logs: Optional[str] = ..., + percentage_complete: int, + status_information: Optional[Any] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.RunStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + CANCELED = "Canceled" + FAILED = "Failed" + NOT_STARTED = "NotStarted" + RUNNING = "Running" + SUCCEEDED = "Succeeded" + + + class azure.ai.discovery.models.SearchRequest(_Model): + query: str + + @overload + def __init__( + self, + *, + query: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.SearchResponse(_Model): + search_results: list[SearchResultItem] + + @overload + def __init__( + self, + *, + search_results: list[SearchResultItem] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.SearchResultItem(_Model): + citations: Optional[list[Citation]] + text: str + + @overload + def __init__( + self, + *, + citations: Optional[list[Citation]] = ..., + text: str + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.StartTaskRequest(_Model): + assignee: Optional[TaskAssignee] + + @overload + def __init__( + self, + *, + assignee: Optional[TaskAssignee] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.StorageAssetReference(_Model): + id: str + user_assigned_identity: Optional[str] + + @overload + def __init__( + self, + *, + id: str, + user_assigned_identity: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.StorageMountProtocol(str, Enum, metaclass=CaseInsensitiveEnumMeta): + BLOBFUSE_CACHING = "BlobfuseCaching" + NFS = "NFS" + + + class azure.ai.discovery.models.SupercomputerUsage(_Model): + active_jobs: int + nodepools: dict[str, NodepoolUsage] + pending_jobs: int + + @overload + def __init__( + self, + *, + active_jobs: int, + nodepools: dict[str, NodepoolUsage], + pending_jobs: int + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.Tag(_Model): + key: Optional[str] + value: Optional[str] + + @overload + def __init__( + self, + *, + key: Optional[str] = ..., + value: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.Task(_Model): + assigned_to: Optional[TaskAssignee] + comments: Optional[list[TaskComment]] + created_at: Optional[datetime] + created_by: Optional[str] + created_by_type: Optional[Union[str, ByType]] + depends_on: Optional[list[str]] + description: Optional[str] + execution_history: Optional[list[ExecutionHistoryEntry]] + investigation_id: Optional[str] + last_modified_at: Optional[datetime] + last_modified_by: Optional[str] + last_modified_by_type: Optional[Union[str, ByType]] + name: str + parent_id: Optional[str] + priority: Optional[Union[str, TaskPriority]] + related_to: Optional[list[str]] + status: Optional[Union[str, TaskStatus]] + storage_asset_ids: Optional[list[str]] + task_result: Optional[TaskResult] + title: Optional[str] + validation_requirements: Optional[list[str]] + + @overload + def __init__( + self, + *, + assigned_to: Optional[TaskAssignee] = ..., + comments: Optional[list[TaskComment]] = ..., + created_by_type: Optional[Union[str, ByType]] = ..., + depends_on: Optional[list[str]] = ..., + description: Optional[str] = ..., + investigation_id: Optional[str] = ..., + parent_id: Optional[str] = ..., + priority: Optional[Union[str, TaskPriority]] = ..., + related_to: Optional[list[str]] = ..., + status: Optional[Union[str, TaskStatus]] = ..., + storage_asset_ids: Optional[list[str]] = ..., + task_result: Optional[TaskResult] = ..., + title: Optional[str] = ..., + validation_requirements: Optional[list[str]] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.TaskAssignee(_Model): + id: str + type: Union[str, ByType] + + @overload + def __init__( + self, + *, + id: str, + type: Union[str, ByType] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.TaskComment(_Model): + created_by: str + created_by_type: Union[str, ByType] + text: str + timestamp: Optional[datetime] + + @overload + def __init__( + self, + *, + created_by: str, + created_by_type: Union[str, ByType], + text: str, + timestamp: Optional[datetime] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.TaskPriority(str, Enum, metaclass=CaseInsensitiveEnumMeta): + HIGH = "High" + LOW = "Low" + MEDIUM = "Medium" + + + class azure.ai.discovery.models.TaskResult(_Model): + storage_asset_ids: Optional[list[str]] + text: Optional[str] + + @overload + def __init__( + self, + *, + storage_asset_ids: Optional[list[str]] = ..., + text: Optional[str] = ... + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.TaskStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + COMPLETE = "Complete" + EXECUTING = "Executing" + EXECUTION_DONE = "ExecutionDone" + FAILED = "Failed" + FLAGGED_AI = "FlaggedAi" + FLAGGED_HUMAN = "FlaggedHuman" + INCOMPLETE = "Incomplete" + NEW = "New" + ON_HOLD = "OnHold" + REMOVED = "Removed" + STALE = "Stale" + + + class azure.ai.discovery.models.WorkingMemoryEntry(_Model): + content: str + created_at: Optional[datetime] + type: Union[str, WorkingMemoryEntryType] + + @overload + def __init__( + self, + *, + content: str, + created_at: Optional[datetime] = ..., + type: Union[str, WorkingMemoryEntryType] + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: ... + + + class azure.ai.discovery.models.WorkingMemoryEntryType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + THOUGHT = "Thought" + + +namespace azure.ai.discovery.operations + + class azure.ai.discovery.operations.ConversationsOperations: + + def __init__( + self, + *args, + **kwargs + ) -> None: ... + + @overload + def create( + self, + *, + content_type: str = "application/json", + display_name: Optional[str] = ..., + investigation_name: Optional[str] = ..., + project_name: str, + **kwargs: Any + ) -> Conversation: ... + + @overload + def create( + self, + body: CreateRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Conversation: ... + + @overload + def create( + self, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Conversation: ... + + @distributed_trace + def delete( + self, + conversation_name: str, + **kwargs: Any + ) -> None: ... + + @distributed_trace + def get( + self, + conversation_name: str, + **kwargs: Any + ) -> Conversation: ... + + @distributed_trace + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'investigation_name', 'project_name', 'created_since', 'top', 'skip', 'maxpagesize', 'accept']}, api_versions_list=['2026-06-01']) + def list( + self, + *, + created_since: Optional[datetime] = ..., + investigation_name: Optional[str] = ..., + project_name: Optional[str] = ..., + skip: Optional[int] = ..., + top: Optional[int] = ..., + **kwargs: Any + ) -> PagedConversation: ... + + @overload + def stable_update( + self, + conversation_name: str, + resource: Conversation, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> Conversation: ... + + @overload + def stable_update( + self, + conversation_name: str, + resource: Conversation, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> Conversation: ... + + @overload + def stable_update( + self, + conversation_name: str, + resource: IO[bytes], + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> Conversation: ... + + + class azure.ai.discovery.operations.InvestigationsOperations: + + def __init__( + self, + *args, + **kwargs + ) -> None: ... + + @distributed_trace + def begin_delete( + self, + project_name: str, + investigation_name: str, + **kwargs: Any + ) -> LROPoller[Investigation]: ... + + @overload + def create_or_replace( + self, + project_name: str, + investigation_name: str, + resource: Investigation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Investigation: ... + + @overload + def create_or_replace( + self, + project_name: str, + investigation_name: str, + resource: Investigation, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Investigation: ... + + @overload + def create_or_replace( + self, + project_name: str, + investigation_name: str, + resource: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Investigation: ... + + @distributed_trace + def get( + self, + project_name: str, + investigation_name: str, + **kwargs: Any + ) -> Investigation: ... + + @distributed_trace + def get_discovery_engine( + self, + project_name: str, + investigation_name: str, + **kwargs: Any + ) -> DiscoveryEngine: ... + + @distributed_trace + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'project_name', 'investigation_name', 'top', 'skip', 'maxpagesize', 'accept']}, api_versions_list=['2026-06-01']) + def get_discovery_engine_memory( + self, + project_name: str, + investigation_name: str, + *, + skip: Optional[int] = ..., + top: Optional[int] = ..., + **kwargs: Any + ) -> PagedWorkingMemoryEntry: ... + + @distributed_trace + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'project_name', 'investigation_name', 'operation_id', 'accept']}, api_versions_list=['2026-06-01']) + def get_operation_status( + self, + project_name: str, + investigation_name: str, + operation_id: str, + **kwargs: Any + ) -> InvestigationOperationStatus: ... + + @distributed_trace + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'project_name', 'created_since', 'top', 'skip', 'maxpagesize', 'accept']}, api_versions_list=['2026-06-01']) + def list( + self, + project_name: str, + *, + created_since: Optional[datetime] = ..., + skip: Optional[int] = ..., + top: Optional[int] = ..., + **kwargs: Any + ) -> PagedInvestigation: ... + + @distributed_trace + def start_discovery_engine( + self, + project_name: str, + investigation_name: str, + **kwargs: Any + ) -> DiscoveryEngine: ... + + @distributed_trace + def stop_discovery_engine( + self, + project_name: str, + investigation_name: str, + **kwargs: Any + ) -> DiscoveryEngine: ... + + @overload + def update( + self, + project_name: str, + investigation_name: str, + resource: Investigation, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> Investigation: ... + + @overload + def update( + self, + project_name: str, + investigation_name: str, + resource: Investigation, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> Investigation: ... + + @overload + def update( + self, + project_name: str, + investigation_name: str, + resource: IO[bytes], + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> Investigation: ... + + @overload + def update_discovery_engine( + self, + project_name: str, + investigation_name: str, + body: DiscoveryEngineUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> DiscoveryEngine: ... + + @overload + def update_discovery_engine( + self, + project_name: str, + investigation_name: str, + body: DiscoveryEngineUpdate, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> DiscoveryEngine: ... + + @overload + def update_discovery_engine( + self, + project_name: str, + investigation_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> DiscoveryEngine: ... + + + class azure.ai.discovery.operations.KnowledgeBasesOperations(_GeneratedKnowledgeBasesOperations): + + def __init__( + self, + *args, + **kwargs + ) -> None: ... + + @distributed_trace + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'knowledge_base_name', 'repeatability_request_id', 'repeatability_first_sent', 'client_request_id', 'accept']}, api_versions_list=['2026-06-01']) + def begin_cancel_indexing( + self, + knowledge_base_name: str, + **kwargs: Any + ) -> LROPoller[None]: ... + + def begin_create_or_update( + self, + knowledge_base_name: str, + resource: Union[KnowledgeBase, dict[str, Any], IO[bytes]], + **kwargs: Any + ) -> LROPoller[KnowledgeBase]: ... + + @distributed_trace + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'knowledge_base_name', 'accept']}, api_versions_list=['2026-06-01']) + def begin_delete( + self, + knowledge_base_name: str, + **kwargs: Any + ) -> LROPoller[None]: ... + + @overload + def begin_search( + self, + knowledge_base_name: str, + body: SearchRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: ... + + @overload + def begin_search( + self, + knowledge_base_name: str, + body: SearchRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: ... + + @overload + def begin_search( + self, + knowledge_base_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: ... + + @overload + def begin_start_indexing( + self, + knowledge_base_name: str, + *, + content_type: str = "application/json", + node_pool_id: Optional[str] = ..., + project_id: Optional[str] = ..., + **kwargs: Any + ) -> LROPoller[None]: ... + + @overload + def begin_start_indexing( + self, + knowledge_base_name: str, + body: StartIndexingRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: ... + + @overload + def begin_start_indexing( + self, + knowledge_base_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: ... + + @distributed_trace + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'knowledge_base_name', 'accept']}, api_versions_list=['2026-06-01']) + def get( + self, + knowledge_base_name: str, + **kwargs: Any + ) -> KnowledgeBase: ... + + @distributed_trace + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'knowledge_base_name', 'operation_id', 'accept']}, api_versions_list=['2026-06-01']) + def get_operation_status( + self, + knowledge_base_name: str, + operation_id: str, + **kwargs: Any + ) -> KnowledgeBaseOperationResponse: ... + + @distributed_trace + def list(self, **kwargs: Any) -> ItemPaged[KnowledgeBase]: ... + + + class azure.ai.discovery.operations.TasksOperations: + + def __init__( + self, + *args, + **kwargs + ) -> None: ... + + @overload + def add_comment( + self, + project_name: str, + investigation_name: str, + task_name: str, + body: TaskComment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + def add_comment( + self, + project_name: str, + investigation_name: str, + task_name: str, + body: TaskComment, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + def add_comment( + self, + project_name: str, + investigation_name: str, + task_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + def add_execution_history( + self, + project_name: str, + investigation_name: str, + task_name: str, + body: ExecutionHistoryEntry, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + def add_execution_history( + self, + project_name: str, + investigation_name: str, + task_name: str, + body: ExecutionHistoryEntry, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + def add_execution_history( + self, + project_name: str, + investigation_name: str, + task_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + def create( + self, + project_name: str, + investigation_name: str, + body: Task, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + def create( + self, + project_name: str, + investigation_name: str, + body: Task, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + def create( + self, + project_name: str, + investigation_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @distributed_trace + def delete( + self, + project_name: str, + investigation_name: str, + task_name: str, + **kwargs: Any + ) -> None: ... + + @distributed_trace + def get( + self, + project_name: str, + investigation_name: str, + task_name: str, + **kwargs: Any + ) -> Task: ... + + @distributed_trace + def list( + self, + project_name: str, + investigation_name: str, + *, + filter: Optional[str] = ..., + **kwargs: Any + ) -> ItemPaged[Task]: ... + + @overload + def stable_update( + self, + project_name: str, + investigation_name: str, + task_name: str, + resource: Task, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> Task: ... + + @overload + def stable_update( + self, + project_name: str, + investigation_name: str, + task_name: str, + resource: Task, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> Task: ... + + @overload + def stable_update( + self, + project_name: str, + investigation_name: str, + task_name: str, + resource: IO[bytes], + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> Task: ... + + @overload + def start( + self, + project_name: str, + investigation_name: str, + task_name: str, + body: Optional[StartTaskRequest] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + def start( + self, + project_name: str, + investigation_name: str, + task_name: str, + body: Optional[StartTaskRequest] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + @overload + def start( + self, + project_name: str, + investigation_name: str, + task_name: str, + body: Optional[IO[bytes]] = None, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Task: ... + + + class azure.ai.discovery.operations.ToolsOperations: + + def __init__( + self, + *args, + **kwargs + ) -> None: ... + + @distributed_trace + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'project_name', 'operation_id', 'accept']}, api_versions_list=['2026-06-01']) + def begin_cancel_run_lro( + self, + project_name: str, + operation_id: str, + **kwargs: Any + ) -> LROPoller[RunResult]: ... + + @overload + def begin_run( + self, + project_name: str, + *, + command: Optional[str] = ..., + content_type: str = "application/json", + environment_variables: Optional[List[RunRequestEnvironmentVariable]] = ..., + infra_overrides: Optional[InfraOverrides] = ..., + inline_files: Optional[List[InlineFile]] = ..., + input_data: Optional[List[InputDataMount]] = ..., + node_pool_ids: List[str], + output_data: Optional[List[OutputDataMount]] = ..., + tool_id: str, + **kwargs: Any + ) -> LROPoller[RunResult]: ... + + @overload + def begin_run( + self, + project_name: str, + body: RunRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[RunResult]: ... + + @overload + def begin_run( + self, + project_name: str, + body: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[RunResult]: ... + + @distributed_trace + def get_compute_usage( + self, + project_name: str, + **kwargs: Any + ) -> ComputeUsage: ... + + @distributed_trace + @api_version_validation(method_added_on='2026-06-01', params_added_on={'2026-06-01': ['api_version', 'project_name', 'top', 'skip', 'maxpagesize', 'accept']}, api_versions_list=['2026-06-01']) + def get_operations( + self, + project_name: str, + *, + skip: Optional[int] = ..., + top: Optional[int] = ..., + **kwargs: Any + ) -> PagedOperation: ... + + @distributed_trace + def get_run_status( + self, + project_name: str, + operation_id: str, + *, + log_count: Optional[int] = ..., + **kwargs: Any + ) -> OperationStatusRunResultError: ... + + +namespace azure.ai.discovery.types + + class azure.ai.discovery.types.Conversation(TypedDict, total=False): + key "createdAt": str + key "createdBy": str + key "createdByType": Union[str, ByType] + key "displayName": str + key "investigationName": str + key "lastModifiedAt": str + key "lastModifiedBy": str + key "lastModifiedByType": Union[str, ByType] + key "name": Required[str] + key "projectName": str + created_at: str + created_by: str + created_by_type: Union[str, ByType] + display_name: str + investigation_name: str + last_modified_at: str + last_modified_by: str + last_modified_by_type: Union[str, ByType] + name: str + project_name: str + + + class azure.ai.discovery.types.CreateRequest(TypedDict, total=False): + key "displayName": str + key "investigationName": str + key "projectName": Required[str] + display_name: str + investigation_name: str + project_name: str + + + class azure.ai.discovery.types.DiscoveryEngineUpdate(TypedDict, total=False): + key "systemPrompt": str + configuration: dict[str, Any] + system_prompt: str + + + class azure.ai.discovery.types.ExecutionHistoryEntry(TypedDict, total=False): + key "action": Required[str] + key "createdAt": Required[str] + key "createdBy": Required[str] + key "createdByType": Required[Union[str, ByType]] + key "responseMessageId": str + key "responseMessageText": str + key "summary": str + action: str + additionalDetails: dict[str, Any] + additional_details: dict[str, Any] + created_at: str + created_by: str + created_by_type: Union[str, ByType] + response_message_id: str + response_message_text: str + summary: str + + + class azure.ai.discovery.types.IndexingMetrics(TypedDict, total=False): + key "documentsFailed": Required[int] + key "documentsProcessed": Required[int] + key "documentsTotal": Required[int] + key "enrichmentEndTimeUtc": str + key "enrichmentStartTimeUtc": str + key "indexingEndTimeUtc": str + key "indexingPercentageComplete": Required[int] + key "indexingStartTimeUtc": str + documents_failed: int + documents_processed: int + documents_total: int + enrichment_end_time_utc: str + enrichment_start_time_utc: str + indexing_end_time_utc: str + indexing_percentage_complete: int + indexing_start_time_utc: str + + + class azure.ai.discovery.types.InfraOverrides(TypedDict, total=False): + key "cpu": str + key "gpu": str + key "imageUri": str + key "maxCpu": str + key "maxGpu": str + key "maxRam": str + key "ram": str + key "replicaCount": int + cpu: str + gpu: str + image_uri: str + max_cpu: str + max_gpu: str + max_ram: str + ram: str + replica_count: int + + + class azure.ai.discovery.types.InlineFile(TypedDict, total=False): + key "encodedFile": Required[str] + key "mountPath": Required[str] + encoded_file: str + mount_path: str + + + class azure.ai.discovery.types.InputDataMount(TypedDict, total=False): + key "mountPath": Required[str] + key "mountProtocol": Union[str, StorageMountProtocol] + key "storageUri": Required[str] + mount_path: str + mount_protocol: Union[str, StorageMountProtocol] + storage_uri: str + + + class azure.ai.discovery.types.Investigation(TypedDict, total=False): + key "createdAt": str + key "createdBy": str + key "createdByType": Union[str, ByType] + key "description": str + key "displayName": str + key "lastModifiedAt": str + key "lastModifiedBy": str + key "lastModifiedByType": Union[str, ByType] + key "name": Required[str] + key "projectName": Required[str] + key "status": Union[str, InvestigationStatus] + created_at: str + created_by: str + created_by_type: Union[str, ByType] + description: str + display_name: str + last_modified_at: str + last_modified_by: str + last_modified_by_type: Union[str, ByType] + name: str + project_name: str + status: Union[str, InvestigationStatus] + tags: list[Tag] + + + class azure.ai.discovery.types.KnowledgeBase(TypedDict, total=False): + key "bookshelfName": Required[str] + key "copilotInstruction": Required[str] + key "createdAt": str + key "createdBy": str + key "createdByApiVersion": str + key "createdByType": Union[str, ByType] + key "description": Required[str] + key "error": ODataV4Format + key "id": str + key "knowledgeBaseUrl": str + key "lastIndexingRun": ForwardRef('LastIndexingRun', module='types') + key "lastModifiedAt": str + key "lastModifiedBy": str + key "lastModifiedByType": Union[str, ByType] + key "name": Required[str] + key "provisioningState": Union[str, ProvisioningState] + key "status": Union[str, IndexingStatus] + bookshelf_name: str + copilot_instruction: str + created_at: str + created_by: str + created_by_api_version: str + created_by_type: Union[str, ByType] + description: str + error: ODataV4Format + id: str + knowledge_base_url: str + last_indexing_run: LastIndexingRun + last_modified_at: str + last_modified_by: str + last_modified_by_type: Union[str, ByType] + name: str + provisioning_state: Union[str, ProvisioningState] + status: Union[str, IndexingStatus] + storageAssetReferences: list[StorageAssetReference] + storage_asset_references: list[StorageAssetReference] + tags: list[Tag] + + + class azure.ai.discovery.types.LastIndexingRun(TypedDict, total=False): + key "error": ODataV4Format + key "indexingMetrics": ForwardRef('IndexingMetrics', module='types') + key "runId": str + key "status": Union[str, IndexingStatus] + error: ODataV4Format + indexing_metrics: IndexingMetrics + run_id: str + status: Union[str, IndexingStatus] + + + class azure.ai.discovery.types.OutputDataMount(TypedDict, total=False): + key "mountPath": Required[str] + key "mountProtocol": Union[str, StorageMountProtocol] + key "storageUri": Required[str] + mount_path: str + mount_protocol: Union[str, StorageMountProtocol] + storage_uri: str + + + class azure.ai.discovery.types.RunRequest(TypedDict, total=False): + key "command": str + key "infraOverrides": ForwardRef('InfraOverrides', module='types') + key "nodePoolIds": Required[list[str]] + key "toolId": Required[str] + command: str + environmentVariables: list[RunRequestEnvironmentVariable] + environment_variables: list[RunRequestEnvironmentVariable] + infra_overrides: InfraOverrides + inlineFiles: list[InlineFile] + inline_files: list[InlineFile] + inputData: list[InputDataMount] + input_data: list[InputDataMount] + node_pool_ids: list[str] + outputData: list[OutputDataMount] + output_data: list[OutputDataMount] + tool_id: str + + + class azure.ai.discovery.types.RunRequestEnvironmentVariable(TypedDict, total=False): + key "name": Required[str] + key "value": str + name: str + value: str + + + class azure.ai.discovery.types.SearchRequest(TypedDict, total=False): + key "query": Required[str] + query: str + + + class azure.ai.discovery.types.StartIndexingRequest(TypedDict, total=False): + key "nodePoolId": str + key "projectId": str + node_pool_id: str + project_id: str + + + class azure.ai.discovery.types.StartTaskRequest(TypedDict, total=False): + key "assignee": ForwardRef('TaskAssignee', module='types') + assignee: TaskAssignee + + + class azure.ai.discovery.types.StorageAssetReference(TypedDict, total=False): + key "id": Required[str] + key "userAssignedIdentity": str + id: str + user_assigned_identity: str + + + class azure.ai.discovery.types.Tag(TypedDict, total=False): + key "key": str + key "value": str + key: str + value: str + + + class azure.ai.discovery.types.Task(TypedDict, total=False): + key "assignedTo": ForwardRef('TaskAssignee', module='types') + key "createdAt": str + key "createdBy": str + key "createdByType": Union[str, ByType] + key "description": str + key "investigationId": str + key "lastModifiedAt": str + key "lastModifiedBy": str + key "lastModifiedByType": Union[str, ByType] + key "name": Required[str] + key "parentId": str + key "priority": Union[str, TaskPriority] + key "status": Union[str, TaskStatus] + key "taskResult": ForwardRef('TaskResult', module='types') + key "title": str + assigned_to: TaskAssignee + comments: list[TaskComment] + created_at: str + created_by: str + created_by_type: Union[str, ByType] + dependsOn: list[str] + depends_on: list[str] + description: str + executionHistory: list[ExecutionHistoryEntry] + execution_history: list[ExecutionHistoryEntry] + investigation_id: str + last_modified_at: str + last_modified_by: str + last_modified_by_type: Union[str, ByType] + name: str + parent_id: str + priority: Union[str, TaskPriority] + relatedTo: list[str] + related_to: list[str] + status: Union[str, TaskStatus] + storageAssetIds: list[str] + storage_asset_ids: list[str] + task_result: TaskResult + title: str + validationRequirements: list[str] + validation_requirements: list[str] + + + class azure.ai.discovery.types.TaskAssignee(TypedDict, total=False): + key "id": Required[str] + key "type": Required[Union[str, ByType]] + id: str + type: Union[str, ByType] + + + class azure.ai.discovery.types.TaskComment(TypedDict, total=False): + key "createdBy": Required[str] + key "createdByType": Required[Union[str, ByType]] + key "text": Required[str] + key "timestamp": str + created_by: str + created_by_type: Union[str, ByType] + text: str + timestamp: str + + + class azure.ai.discovery.types.TaskResult(TypedDict, total=False): + key "text": str + storageAssetIds: list[str] + storage_asset_ids: list[str] + text: str + + +``` \ No newline at end of file diff --git a/sdk/discovery/azure-ai-discovery/api.metadata.yml b/sdk/discovery/azure-ai-discovery/api.metadata.yml new file mode 100644 index 000000000000..9d14c66b2dc5 --- /dev/null +++ b/sdk/discovery/azure-ai-discovery/api.metadata.yml @@ -0,0 +1,3 @@ +apiMdSha256: d71abaa9198ad604a8d8f15fbea1df8b31b1c41b27c7982c9cc4c0775c9f461a +parserVersion: 0.3.30 +pythonVersion: 3.12.3 diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/apiview-properties.json b/sdk/discovery/azure-ai-discovery/apiview-properties.json similarity index 65% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/apiview-properties.json rename to sdk/discovery/azure-ai-discovery/apiview-properties.json index f74e1938c089..5745666f3406 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/apiview-properties.json +++ b/sdk/discovery/azure-ai-discovery/apiview-properties.json @@ -1,27 +1,41 @@ { "CrossLanguagePackageId": "Microsoft.Discovery.Workspace", "CrossLanguageDefinitionId": { + "azure.ai.discovery.models.Citation": "Microsoft.Discovery.Bookshelf.Citation", "azure.ai.discovery.models.ComputeUsage": "Microsoft.Discovery.Workspace.ComputeUsage", "azure.ai.discovery.models.Conversation": "Microsoft.Discovery.Workspace.Conversation", "azure.ai.discovery.models.DiscoveryEngine": "Microsoft.Discovery.Workspace.DiscoveryEngine", "azure.ai.discovery.models.DiscoveryEngineUpdate": "Microsoft.Discovery.Workspace.DiscoveryEngineUpdate", "azure.ai.discovery.models.ExecutionHistoryEntry": "Microsoft.Discovery.Workspace.ExecutionHistoryEntry", + "azure.ai.discovery.models.IndexingMetrics": "Microsoft.Discovery.Bookshelf.IndexingMetrics", + "azure.ai.discovery.models.IndexingOperationResult": "Microsoft.Discovery.Bookshelf.IndexingOperationResult", "azure.ai.discovery.models.InfraOverrides": "Microsoft.Discovery.Workspace.InfraOverrides", "azure.ai.discovery.models.InlineFile": "Microsoft.Discovery.Workspace.InlineFile", "azure.ai.discovery.models.InputDataMount": "Microsoft.Discovery.Workspace.InputDataMount", "azure.ai.discovery.models.Investigation": "Microsoft.Discovery.Workspace.Investigation", + "azure.ai.discovery.models.InvestigationOperationStatus": "Microsoft.Discovery.Workspace.InvestigationOperationStatus", + "azure.ai.discovery.models.KnowledgeBase": "Microsoft.Discovery.Bookshelf.KnowledgeBase", + "azure.ai.discovery.models.KnowledgeBaseOperationResponse": "Microsoft.Discovery.Bookshelf.KnowledgeBaseOperationResponse", + "azure.ai.discovery.models.KnowledgeBaseIndexingOperationResponse": "Microsoft.Discovery.Bookshelf.KnowledgeBaseIndexingOperationResponse", + "azure.ai.discovery.models.KnowledgeBaseSearchOperationResponse": "Microsoft.Discovery.Bookshelf.KnowledgeBaseSearchOperationResponse", + "azure.ai.discovery.models.LastIndexingRun": "Microsoft.Discovery.Bookshelf.LastIndexingRun", "azure.ai.discovery.models.NodepoolUsage": "Microsoft.Discovery.Workspace.NodepoolUsage", "azure.ai.discovery.models.Operation": "Microsoft.Discovery.Workspace.Operation", "azure.ai.discovery.models.OperationStatusRunResultError": "Azure.Core.Foundations.OperationStatus", "azure.ai.discovery.models.OutputDataMount": "Microsoft.Discovery.Workspace.OutputDataMount", "azure.ai.discovery.models.OutputDataUri": "Microsoft.Discovery.Workspace.OutputDataUri", + "azure.ai.discovery.models.PagedConversation": "Azure.Core.Foundations.CustomPage", + "azure.ai.discovery.models.PagedInvestigation": "Azure.Core.Foundations.CustomPage", "azure.ai.discovery.models.PagedOperation": "Azure.Core.Foundations.CustomPage", "azure.ai.discovery.models.PagedWorkingMemoryEntry": "Azure.Core.Foundations.CustomPage", - "azure.ai.discovery.models.ResourceOperationStatusInvestigationInvestigationError": "Azure.Core.ResourceOperationStatus", "azure.ai.discovery.models.RunRequestEnvironmentVariable": "Microsoft.Discovery.Workspace.run.Request.environmentVariable.anonymous", "azure.ai.discovery.models.RunResult": "Microsoft.Discovery.Workspace.RunResult", "azure.ai.discovery.models.RunResultToolReport": "Microsoft.Discovery.Workspace.RunResult.toolReport.anonymous", + "azure.ai.discovery.models.SearchRequest": "Microsoft.Discovery.Bookshelf.SearchRequest", + "azure.ai.discovery.models.SearchResponse": "Microsoft.Discovery.Bookshelf.SearchResponse", + "azure.ai.discovery.models.SearchResultItem": "Microsoft.Discovery.Bookshelf.SearchResultItem", "azure.ai.discovery.models.StartTaskRequest": "Microsoft.Discovery.Workspace.StartTaskRequest", + "azure.ai.discovery.models.StorageAssetReference": "Microsoft.Discovery.Bookshelf.StorageAssetReference", "azure.ai.discovery.models.SupercomputerUsage": "Microsoft.Discovery.Workspace.SupercomputerUsage", "azure.ai.discovery.models.Tag": "Microsoft.Discovery.Common.Tag", "azure.ai.discovery.models.Task": "Microsoft.Discovery.Workspace.Task", @@ -34,17 +48,23 @@ "azure.ai.discovery.models.OperationState": "Azure.Core.Foundations.OperationState", "azure.ai.discovery.models.DiscoveryEngineStatus": "Microsoft.Discovery.Workspace.DiscoveryEngineStatus", "azure.ai.discovery.models.WorkingMemoryEntryType": "Microsoft.Discovery.Workspace.WorkingMemoryEntryType", + "azure.ai.discovery.models.StorageMountProtocol": "Microsoft.Discovery.Workspace.StorageMountProtocol", "azure.ai.discovery.models.RunStatus": "Microsoft.Discovery.Workspace.RunStatus", "azure.ai.discovery.models.TaskPriority": "Microsoft.Discovery.Workspace.TaskPriority", "azure.ai.discovery.models.TaskStatus": "Microsoft.Discovery.Workspace.TaskStatus", + "azure.ai.discovery.models.ProvisioningState": "Microsoft.Discovery.Common.ProvisioningState", + "azure.ai.discovery.models.IndexingStatus": "Microsoft.Discovery.Bookshelf.IndexingStatus", + "azure.ai.discovery.models.KnowledgeBaseOperationType": "Microsoft.Discovery.Bookshelf.KnowledgeBaseOperationType", + "azure.ai.discovery.models.CitationType": "Microsoft.Discovery.Bookshelf.CitationType", + "azure.ai.discovery.models.RepeatabilityResult": "Azure.Core.RepeatabilityResult", "azure.ai.discovery.operations.InvestigationsOperations.get": "Microsoft.Discovery.Workspace.Investigations.get", "azure.ai.discovery.aio.operations.InvestigationsOperations.get": "Microsoft.Discovery.Workspace.Investigations.get", "azure.ai.discovery.operations.InvestigationsOperations.get_operation_status": "Microsoft.Discovery.Workspace.Investigations.getOperationStatus", "azure.ai.discovery.aio.operations.InvestigationsOperations.get_operation_status": "Microsoft.Discovery.Workspace.Investigations.getOperationStatus", "azure.ai.discovery.operations.InvestigationsOperations.create_or_replace": "Microsoft.Discovery.Workspace.Investigations.createOrReplace", "azure.ai.discovery.aio.operations.InvestigationsOperations.create_or_replace": "Microsoft.Discovery.Workspace.Investigations.createOrReplace", - "azure.ai.discovery.operations.InvestigationsOperations.create_or_update": "Microsoft.Discovery.Workspace.Investigations.createOrUpdate", - "azure.ai.discovery.aio.operations.InvestigationsOperations.create_or_update": "Microsoft.Discovery.Workspace.Investigations.createOrUpdate", + "azure.ai.discovery.operations.InvestigationsOperations.update": "Microsoft.Discovery.Workspace.Investigations.update", + "azure.ai.discovery.aio.operations.InvestigationsOperations.update": "Microsoft.Discovery.Workspace.Investigations.update", "azure.ai.discovery.operations.InvestigationsOperations.begin_delete": "Microsoft.Discovery.Workspace.Investigations.delete", "azure.ai.discovery.aio.operations.InvestigationsOperations.begin_delete": "Microsoft.Discovery.Workspace.Investigations.delete", "azure.ai.discovery.operations.InvestigationsOperations.list": "Microsoft.Discovery.Workspace.Investigations.list", @@ -63,8 +83,8 @@ "azure.ai.discovery.aio.operations.ConversationsOperations.get": "Microsoft.Discovery.Workspace.Conversations.get", "azure.ai.discovery.operations.ConversationsOperations.create": "Microsoft.Discovery.Workspace.Conversations.create", "azure.ai.discovery.aio.operations.ConversationsOperations.create": "Microsoft.Discovery.Workspace.Conversations.create", - "azure.ai.discovery.operations.ConversationsOperations.update": "Microsoft.Discovery.Workspace.Conversations.update", - "azure.ai.discovery.aio.operations.ConversationsOperations.update": "Microsoft.Discovery.Workspace.Conversations.update", + "azure.ai.discovery.operations.ConversationsOperations.stable_update": "Microsoft.Discovery.Workspace.Conversations.stableUpdate", + "azure.ai.discovery.aio.operations.ConversationsOperations.stable_update": "Microsoft.Discovery.Workspace.Conversations.stableUpdate", "azure.ai.discovery.operations.ConversationsOperations.delete": "Microsoft.Discovery.Workspace.Conversations.delete", "azure.ai.discovery.aio.operations.ConversationsOperations.delete": "Microsoft.Discovery.Workspace.Conversations.delete", "azure.ai.discovery.operations.ConversationsOperations.list": "Microsoft.Discovery.Workspace.Conversations.list", @@ -73,8 +93,8 @@ "azure.ai.discovery.aio.operations.ToolsOperations.get_run_status": "Microsoft.Discovery.Workspace.Tools.getRunStatus", "azure.ai.discovery.operations.ToolsOperations.begin_run": "Microsoft.Discovery.Workspace.Tools.run", "azure.ai.discovery.aio.operations.ToolsOperations.begin_run": "Microsoft.Discovery.Workspace.Tools.run", - "azure.ai.discovery.operations.ToolsOperations.cancel_run": "Microsoft.Discovery.Workspace.Tools.cancelRun", - "azure.ai.discovery.aio.operations.ToolsOperations.cancel_run": "Microsoft.Discovery.Workspace.Tools.cancelRun", + "azure.ai.discovery.operations.ToolsOperations.begin_cancel_run_lro": "Microsoft.Discovery.Workspace.Tools.cancelRunLro", + "azure.ai.discovery.aio.operations.ToolsOperations.begin_cancel_run_lro": "Microsoft.Discovery.Workspace.Tools.cancelRunLro", "azure.ai.discovery.operations.ToolsOperations.get_operations": "Microsoft.Discovery.Workspace.Tools.getOperations", "azure.ai.discovery.aio.operations.ToolsOperations.get_operations": "Microsoft.Discovery.Workspace.Tools.getOperations", "azure.ai.discovery.operations.ToolsOperations.get_compute_usage": "Microsoft.Discovery.Workspace.Tools.getComputeUsage", @@ -85,8 +105,8 @@ "azure.ai.discovery.aio.operations.TasksOperations.list": "Microsoft.Discovery.Workspace.Tasks.list", "azure.ai.discovery.operations.TasksOperations.create": "Microsoft.Discovery.Workspace.Tasks.create", "azure.ai.discovery.aio.operations.TasksOperations.create": "Microsoft.Discovery.Workspace.Tasks.create", - "azure.ai.discovery.operations.TasksOperations.update": "Microsoft.Discovery.Workspace.Tasks.update", - "azure.ai.discovery.aio.operations.TasksOperations.update": "Microsoft.Discovery.Workspace.Tasks.update", + "azure.ai.discovery.operations.TasksOperations.stable_update": "Microsoft.Discovery.Workspace.Tasks.stableUpdate", + "azure.ai.discovery.aio.operations.TasksOperations.stable_update": "Microsoft.Discovery.Workspace.Tasks.stableUpdate", "azure.ai.discovery.operations.TasksOperations.delete": "Microsoft.Discovery.Workspace.Tasks.delete", "azure.ai.discovery.aio.operations.TasksOperations.delete": "Microsoft.Discovery.Workspace.Tasks.delete", "azure.ai.discovery.operations.TasksOperations.start": "Microsoft.Discovery.Workspace.Tasks.start", @@ -94,6 +114,23 @@ "azure.ai.discovery.operations.TasksOperations.add_comment": "Microsoft.Discovery.Workspace.Tasks.addComment", "azure.ai.discovery.aio.operations.TasksOperations.add_comment": "Microsoft.Discovery.Workspace.Tasks.addComment", "azure.ai.discovery.operations.TasksOperations.add_execution_history": "Microsoft.Discovery.Workspace.Tasks.addExecutionHistory", - "azure.ai.discovery.aio.operations.TasksOperations.add_execution_history": "Microsoft.Discovery.Workspace.Tasks.addExecutionHistory" - } + "azure.ai.discovery.aio.operations.TasksOperations.add_execution_history": "Microsoft.Discovery.Workspace.Tasks.addExecutionHistory", + "azure.ai.discovery.operations.KnowledgeBasesOperations.begin_create_or_update": "Microsoft.Discovery.Bookshelf.KnowledgeBases.createOrUpdate", + "azure.ai.discovery.aio.operations.KnowledgeBasesOperations.begin_create_or_update": "Microsoft.Discovery.Bookshelf.KnowledgeBases.createOrUpdate", + "azure.ai.discovery.operations.KnowledgeBasesOperations.get": "Microsoft.Discovery.Bookshelf.KnowledgeBases.get", + "azure.ai.discovery.aio.operations.KnowledgeBasesOperations.get": "Microsoft.Discovery.Bookshelf.KnowledgeBases.get", + "azure.ai.discovery.operations.KnowledgeBasesOperations.list": "Microsoft.Discovery.Bookshelf.KnowledgeBases.list", + "azure.ai.discovery.aio.operations.KnowledgeBasesOperations.list": "Microsoft.Discovery.Bookshelf.KnowledgeBases.list", + "azure.ai.discovery.operations.KnowledgeBasesOperations.get_operation_status": "Microsoft.Discovery.Bookshelf.KnowledgeBases.getOperationStatus", + "azure.ai.discovery.aio.operations.KnowledgeBasesOperations.get_operation_status": "Microsoft.Discovery.Bookshelf.KnowledgeBases.getOperationStatus", + "azure.ai.discovery.operations.KnowledgeBasesOperations.begin_start_indexing": "Microsoft.Discovery.Bookshelf.KnowledgeBases.startIndexing", + "azure.ai.discovery.aio.operations.KnowledgeBasesOperations.begin_start_indexing": "Microsoft.Discovery.Bookshelf.KnowledgeBases.startIndexing", + "azure.ai.discovery.operations.KnowledgeBasesOperations.begin_cancel_indexing": "Microsoft.Discovery.Bookshelf.KnowledgeBases.cancelIndexing", + "azure.ai.discovery.aio.operations.KnowledgeBasesOperations.begin_cancel_indexing": "Microsoft.Discovery.Bookshelf.KnowledgeBases.cancelIndexing", + "azure.ai.discovery.operations.KnowledgeBasesOperations.begin_search": "Microsoft.Discovery.Bookshelf.KnowledgeBases.search", + "azure.ai.discovery.aio.operations.KnowledgeBasesOperations.begin_search": "Microsoft.Discovery.Bookshelf.KnowledgeBases.search", + "azure.ai.discovery.operations.KnowledgeBasesOperations.begin_delete": "Microsoft.Discovery.Bookshelf.KnowledgeBases.delete", + "azure.ai.discovery.aio.operations.KnowledgeBasesOperations.begin_delete": "Microsoft.Discovery.Bookshelf.KnowledgeBases.delete" + }, + "CrossLanguageVersion": "ba4f11bf0408" } \ No newline at end of file diff --git a/sdk/discovery/azure-ai-discovery/assets.json b/sdk/discovery/azure-ai-discovery/assets.json new file mode 100644 index 000000000000..18ed1e10f327 --- /dev/null +++ b/sdk/discovery/azure-ai-discovery/assets.json @@ -0,0 +1,6 @@ +{ + "AssetsRepo": "Azure/azure-sdk-assets", + "AssetsRepoPrefixPath": "python", + "TagPrefix": "python/discovery/azure-ai-discovery", + "Tag": "python/discovery/azure-ai-discovery_68acf7fbe6" +} diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/__init__.py index 83108ffd9183..d8258a4b2813 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/__init__.py +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/__init__.py @@ -2,21 +2,33 @@ # -------------------------------------------------------------------------- # 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 -"""Azure AI Discovery client library for Python. +from typing import TYPE_CHECKING -This package exposes both the WorkspaceClient and BookshelfClient from a single -unified ``azure-ai-discovery`` package. -""" +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import -from ._workspace import WorkspaceClient # type: ignore -from ._bookshelf import BookshelfClient # type: ignore +from ._client import WorkspaceClient # type: ignore +from ._client import BookshelfClient # type: ignore from ._version import VERSION __version__ = VERSION +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + __all__ = [ - "BookshelfClient", "WorkspaceClient", + "BookshelfClient", ] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/CHANGELOG.md b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/CHANGELOG.md deleted file mode 100644 index b957b2575b48..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/CHANGELOG.md +++ /dev/null @@ -1,7 +0,0 @@ -# Release History - -## 1.0.0b1 (1970-01-01) - -### Other Changes - - - Initial version \ No newline at end of file diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/LICENSE b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/LICENSE deleted file mode 100644 index 63447fd8bbbf..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) Microsoft Corporation. - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/MANIFEST.in b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/MANIFEST.in deleted file mode 100644 index 64845ff3f4fc..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/MANIFEST.in +++ /dev/null @@ -1,7 +0,0 @@ -include *.md -include LICENSE -include azure/ai/discovery/py.typed -recursive-include tests *.py -recursive-include samples *.py *.md -include azure/__init__.py -include azure/ai/__init__.py diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/__init__.py deleted file mode 100644 index f49656e92a59..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -# Re-export BookshelfClient from the generated sub-client -from .azure.ai.discovery import BookshelfClient # type: ignore - -__all__ = ["BookshelfClient"] diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/_metadata.json b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/_metadata.json deleted file mode 100644 index eeb8889ab7c1..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/_metadata.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "apiVersion": "2026-02-01-preview", - "apiVersions": { - "Microsoft.Discovery.Bookshelf": "2026-02-01-preview" - } -} \ No newline at end of file diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/apiview-properties.json b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/apiview-properties.json deleted file mode 100644 index a179671a166f..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/apiview-properties.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "CrossLanguagePackageId": "Microsoft.Discovery.Bookshelf", - "CrossLanguageDefinitionId": { - "azure.ai.discovery.models.KnowledgeBase": "Microsoft.Discovery.Bookshelf.KnowledgeBase", - "azure.ai.discovery.models.KnowledgeBaseOperationStatus": "Microsoft.Discovery.Bookshelf.KnowledgeBaseOperationStatus", - "azure.ai.discovery.models.KnowledgeBaseVersion": "Microsoft.Discovery.Bookshelf.KnowledgeBaseVersion", - "azure.ai.discovery.models.StorageAssetReference": "Microsoft.Discovery.Bookshelf.StorageAssetReference", - "azure.ai.discovery.models.Tag": "Microsoft.Discovery.Common.Tag", - "azure.ai.discovery.models.ProvisioningState": "Microsoft.Discovery.Common.ProvisioningState", - "azure.ai.discovery.models.ByType": "Microsoft.Discovery.Common.ByType", - "azure.ai.discovery.models.IndexingStatus": "Microsoft.Discovery.Bookshelf.IndexingStatus", - "azure.ai.discovery.models.OperationState": "Azure.Core.Foundations.OperationState", - "azure.ai.discovery.models.RepeatabilityResult": "Azure.Core.RepeatabilityResult", - "azure.ai.discovery.operations.KnowledgeBasesOperations.list": "Microsoft.Discovery.Bookshelf.KnowledgeBases.list", - "azure.ai.discovery.aio.operations.KnowledgeBasesOperations.list": "Microsoft.Discovery.Bookshelf.KnowledgeBases.list", - "azure.ai.discovery.operations.KnowledgeBaseVersionsOperations.create_or_update": "Microsoft.Discovery.Bookshelf.KnowledgeBaseVersions.createOrUpdate", - "azure.ai.discovery.aio.operations.KnowledgeBaseVersionsOperations.create_or_update": "Microsoft.Discovery.Bookshelf.KnowledgeBaseVersions.createOrUpdate", - "azure.ai.discovery.operations.KnowledgeBaseVersionsOperations.get": "Microsoft.Discovery.Bookshelf.KnowledgeBaseVersions.get", - "azure.ai.discovery.aio.operations.KnowledgeBaseVersionsOperations.get": "Microsoft.Discovery.Bookshelf.KnowledgeBaseVersions.get", - "azure.ai.discovery.operations.KnowledgeBaseVersionsOperations.get_latest_version": "Microsoft.Discovery.Bookshelf.KnowledgeBaseVersions.getLatestVersion", - "azure.ai.discovery.aio.operations.KnowledgeBaseVersionsOperations.get_latest_version": "Microsoft.Discovery.Bookshelf.KnowledgeBaseVersions.getLatestVersion", - "azure.ai.discovery.operations.KnowledgeBaseVersionsOperations.list": "Microsoft.Discovery.Bookshelf.KnowledgeBaseVersions.list", - "azure.ai.discovery.aio.operations.KnowledgeBaseVersionsOperations.list": "Microsoft.Discovery.Bookshelf.KnowledgeBaseVersions.list", - "azure.ai.discovery.operations.KnowledgeBaseVersionsOperations.get_operation_status": "Microsoft.Discovery.Bookshelf.KnowledgeBaseVersions.getOperationStatus", - "azure.ai.discovery.aio.operations.KnowledgeBaseVersionsOperations.get_operation_status": "Microsoft.Discovery.Bookshelf.KnowledgeBaseVersions.getOperationStatus", - "azure.ai.discovery.operations.KnowledgeBaseVersionsOperations.begin_start_indexing": "Microsoft.Discovery.Bookshelf.KnowledgeBaseVersions.startIndexing", - "azure.ai.discovery.aio.operations.KnowledgeBaseVersionsOperations.begin_start_indexing": "Microsoft.Discovery.Bookshelf.KnowledgeBaseVersions.startIndexing", - "azure.ai.discovery.operations.KnowledgeBaseVersionsOperations.begin_cancel_indexing": "Microsoft.Discovery.Bookshelf.KnowledgeBaseVersions.cancelIndexing", - "azure.ai.discovery.aio.operations.KnowledgeBaseVersionsOperations.begin_cancel_indexing": "Microsoft.Discovery.Bookshelf.KnowledgeBaseVersions.cancelIndexing", - "azure.ai.discovery.operations.KnowledgeBaseVersionsOperations.begin_delete": "Microsoft.Discovery.Bookshelf.KnowledgeBaseVersions.delete", - "azure.ai.discovery.aio.operations.KnowledgeBaseVersionsOperations.begin_delete": "Microsoft.Discovery.Bookshelf.KnowledgeBaseVersions.delete", - "azure.ai.discovery.operations.KnowledgeBaseVersionsOperations.begin_delete_latest_version": "Microsoft.Discovery.Bookshelf.KnowledgeBaseVersions.deleteLatestVersion", - "azure.ai.discovery.aio.operations.KnowledgeBaseVersionsOperations.begin_delete_latest_version": "Microsoft.Discovery.Bookshelf.KnowledgeBaseVersions.deleteLatestVersion" - } -} \ No newline at end of file diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/__init__.py deleted file mode 100644 index d55ccad1f573..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/__init__.py deleted file mode 100644 index d55ccad1f573..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/__init__.py deleted file mode 100644 index a22f54af5a41..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/__init__.py +++ /dev/null @@ -1,32 +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 ._client import BookshelfClient # type: ignore -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "BookshelfClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_client.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_client.py deleted file mode 100644 index ddd938724f17..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_client.py +++ /dev/null @@ -1,110 +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 copy import deepcopy -from typing import Any, TYPE_CHECKING -from typing_extensions import Self - -from azure.core import PipelineClient -from azure.core.pipeline import policies -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import BookshelfClientConfiguration -from ._utils.serialization import Deserializer, Serializer -from .operations import KnowledgeBaseVersionsOperations, KnowledgeBasesOperations - -if TYPE_CHECKING: - from azure.core.credentials import TokenCredential - - -class BookshelfClient: - """BookshelfClient. - - :ivar knowledge_bases: KnowledgeBasesOperations operations - :vartype knowledge_bases: azure.ai.discovery.operations.KnowledgeBasesOperations - :ivar knowledge_base_versions: KnowledgeBaseVersionsOperations operations - :vartype knowledge_base_versions: azure.ai.discovery.operations.KnowledgeBaseVersionsOperations - :param endpoint: Supported Microsoft Bookshelf Services endpoints (protocol and hostname, for - example: https://{bookshelfName}.discovery.azure.com). Required. - :type endpoint: str - :param credential: Credential used to authenticate requests to the service. Required. - :type credential: ~azure.core.credentials.TokenCredential - :keyword api_version: The API version to use for this operation. Known values are - "2026-02-01-preview" and None. Default value is "2026-02-01-preview". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - """ - - def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: - _endpoint = "{endpoint}" - self._config = BookshelfClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - self.knowledge_bases = KnowledgeBasesOperations(self._client, self._config, self._serialize, self._deserialize) - self.knowledge_base_versions = KnowledgeBaseVersionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - - def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - def close(self) -> None: - self._client.close() - - def __enter__(self) -> Self: - self._client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client.__exit__(*exc_details) diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_configuration.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_configuration.py deleted file mode 100644 index c29d50640d9f..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_configuration.py +++ /dev/null @@ -1,65 +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 - -from azure.core.pipeline import policies - -from ._version import VERSION - -if TYPE_CHECKING: - from azure.core.credentials import TokenCredential - - -class BookshelfClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for BookshelfClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param endpoint: Supported Microsoft Bookshelf Services endpoints (protocol and hostname, for - example: https://{bookshelfName}.discovery.azure.com). Required. - :type endpoint: str - :param credential: Credential used to authenticate requests to the service. Required. - :type credential: ~azure.core.credentials.TokenCredential - :keyword api_version: The API version to use for this operation. Known values are - "2026-02-01-preview" and None. Default value is "2026-02-01-preview". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2026-02-01-preview") - - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - - self.endpoint = endpoint - self.credential = credential - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://discovery.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "ai-discovery/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = policies.BearerTokenCredentialPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_version.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_version.py deleted file mode 100644 index be71c81bd282..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_version.py +++ /dev/null @@ -1,9 +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. -# -------------------------------------------------------------------------- - -VERSION = "1.0.0b1" diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/__init__.py deleted file mode 100644 index 38b779e554c2..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/__init__.py +++ /dev/null @@ -1,29 +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 ._client import BookshelfClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "BookshelfClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/_client.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/_client.py deleted file mode 100644 index 2d344d7800d1..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/_client.py +++ /dev/null @@ -1,113 +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 copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING -from typing_extensions import Self - -from azure.core import AsyncPipelineClient -from azure.core.pipeline import policies -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._utils.serialization import Deserializer, Serializer -from ._configuration import BookshelfClientConfiguration -from .operations import KnowledgeBaseVersionsOperations, KnowledgeBasesOperations - -if TYPE_CHECKING: - from azure.core.credentials_async import AsyncTokenCredential - - -class BookshelfClient: - """BookshelfClient. - - :ivar knowledge_bases: KnowledgeBasesOperations operations - :vartype knowledge_bases: azure.ai.discovery.aio.operations.KnowledgeBasesOperations - :ivar knowledge_base_versions: KnowledgeBaseVersionsOperations operations - :vartype knowledge_base_versions: - azure.ai.discovery.aio.operations.KnowledgeBaseVersionsOperations - :param endpoint: Supported Microsoft Bookshelf Services endpoints (protocol and hostname, for - example: https://{bookshelfName}.discovery.azure.com). Required. - :type endpoint: str - :param credential: Credential used to authenticate requests to the service. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: The API version to use for this operation. Known values are - "2026-02-01-preview" and None. Default value is "2026-02-01-preview". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - :keyword int polling_interval: Default waiting time between two polls for LRO operations if no - Retry-After header is present. - """ - - def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - _endpoint = "{endpoint}" - self._config = BookshelfClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) - - _policies = kwargs.pop("policies", None) - if _policies is None: - _policies = [ - policies.RequestIdPolicy(**kwargs), - self._config.headers_policy, - self._config.user_agent_policy, - self._config.proxy_policy, - policies.ContentDecodePolicy(**kwargs), - self._config.redirect_policy, - self._config.retry_policy, - self._config.authentication_policy, - self._config.custom_hook_policy, - self._config.logging_policy, - policies.DistributedTracingPolicy(**kwargs), - policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, - self._config.http_logging_policy, - ] - self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - self.knowledge_bases = KnowledgeBasesOperations(self._client, self._config, self._serialize, self._deserialize) - self.knowledge_base_versions = KnowledgeBaseVersionsOperations( - self._client, self._config, self._serialize, self._deserialize - ) - - def send_request( - self, request: HttpRequest, *, stream: bool = False, **kwargs: Any - ) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - >>> from azure.core.rest import HttpRequest - >>> request = HttpRequest("GET", "https://www.example.org/") - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> Self: - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client.__aexit__(*exc_details) diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/operations/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/operations/__init__.py deleted file mode 100644 index fe6367b60ed1..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/operations/__init__.py +++ /dev/null @@ -1,27 +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 ._operations import KnowledgeBasesOperations # type: ignore -from ._operations import KnowledgeBaseVersionsOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "KnowledgeBasesOperations", - "KnowledgeBaseVersionsOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/operations/_operations.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/operations/_operations.py deleted file mode 100644 index 2db98be1e17f..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/operations/_operations.py +++ /dev/null @@ -1,1409 +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 collections.abc import MutableMapping -import datetime -from io import IOBase -import json -from typing import Any, AsyncIterator, Callable, IO, Optional, TypeVar, Union, cast, overload -import urllib.parse - -from azure.core import AsyncPipelineClient -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.pipeline import PipelineResponse -from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod -from azure.core.polling.async_base_polling import AsyncLROBasePolling -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.core.tracing.decorator import distributed_trace -from azure.core.tracing.decorator_async import distributed_trace_async -from azure.core.utils import case_insensitive_dict - -from ... import models as _models -from ..._utils.model_base import SdkJSONEncoder, _deserialize -from ..._utils.serialization import Deserializer, Serializer -from ..._validation import api_version_validation -from ...operations._operations import ( - build_knowledge_base_versions_cancel_indexing_request, - build_knowledge_base_versions_create_or_update_request, - build_knowledge_base_versions_delete_latest_version_request, - build_knowledge_base_versions_delete_request, - build_knowledge_base_versions_get_latest_version_request, - build_knowledge_base_versions_get_operation_status_request, - build_knowledge_base_versions_get_request, - build_knowledge_base_versions_list_request, - build_knowledge_base_versions_start_indexing_request, - build_knowledge_bases_list_request, -) -from .._configuration import BookshelfClientConfiguration - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] -JSON = MutableMapping[str, Any] -_Unset: Any = object() -List = list - - -class KnowledgeBasesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.ai.discovery.aio.BookshelfClient`'s - :attr:`knowledge_bases` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: BookshelfClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, **kwargs: Any) -> AsyncItemPaged["_models.KnowledgeBase"]: - """List KnowledgeBase resources. - - :return: An iterator like instance of KnowledgeBase - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.discovery.models.KnowledgeBase] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.KnowledgeBase]] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_knowledge_bases_list_request( - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - async def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize( - List[_models.KnowledgeBase], - deserialized.get("value", []), - ) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("nextLink") or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - -class KnowledgeBaseVersionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.ai.discovery.aio.BookshelfClient`'s - :attr:`knowledge_base_versions` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: BookshelfClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - async def create_or_update( - self, - knowledge_base_name: str, - version_name: str, - resource: _models.KnowledgeBaseVersion, - *, - content_type: str = "application/merge-patch+json", - **kwargs: Any - ) -> _models.KnowledgeBaseVersion: - """Creates or updates a KnowledgeBaseVersion. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param resource: The resource instance. Required. - :type resource: ~azure.ai.discovery.models.KnowledgeBaseVersion - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :return: KnowledgeBaseVersion. The KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.ai.discovery.models.KnowledgeBaseVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - knowledge_base_name: str, - version_name: str, - resource: JSON, - *, - content_type: str = "application/merge-patch+json", - **kwargs: Any - ) -> _models.KnowledgeBaseVersion: - """Creates or updates a KnowledgeBaseVersion. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param resource: The resource instance. Required. - :type resource: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :return: KnowledgeBaseVersion. The KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.ai.discovery.models.KnowledgeBaseVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_or_update( - self, - knowledge_base_name: str, - version_name: str, - resource: IO[bytes], - *, - content_type: str = "application/merge-patch+json", - **kwargs: Any - ) -> _models.KnowledgeBaseVersion: - """Creates or updates a KnowledgeBaseVersion. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param resource: The resource instance. Required. - :type resource: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :return: KnowledgeBaseVersion. The KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.ai.discovery.models.KnowledgeBaseVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_or_update( - self, - knowledge_base_name: str, - version_name: str, - resource: Union[_models.KnowledgeBaseVersion, JSON, IO[bytes]], - **kwargs: Any - ) -> _models.KnowledgeBaseVersion: - """Creates or updates a KnowledgeBaseVersion. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param resource: The resource instance. Is one of the following types: KnowledgeBaseVersion, - JSON, IO[bytes] Required. - :type resource: ~azure.ai.discovery.models.KnowledgeBaseVersion or JSON or IO[bytes] - :return: KnowledgeBaseVersion. The KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.ai.discovery.models.KnowledgeBaseVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeBaseVersion] = kwargs.pop("cls", None) - - content_type = content_type or "application/merge-patch+json" - _content = None - if isinstance(resource, (IOBase, bytes)): - _content = resource - else: - _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_knowledge_base_versions_create_or_update_request( - knowledge_base_name=knowledge_base_name, - version_name=version_name, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.KnowledgeBaseVersion, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get(self, knowledge_base_name: str, version_name: str, **kwargs: Any) -> _models.KnowledgeBaseVersion: - """Fetch a KnowledgeBaseVersion by name. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :return: KnowledgeBaseVersion. The KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.ai.discovery.models.KnowledgeBaseVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models.KnowledgeBaseVersion] = kwargs.pop("cls", None) - - _request = build_knowledge_base_versions_get_request( - knowledge_base_name=knowledge_base_name, - version_name=version_name, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.KnowledgeBaseVersion, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_latest_version(self, knowledge_base_name: str, **kwargs: Any) -> _models.KnowledgeBaseVersion: - """Get the most recent version of KnowledgeBase. - - :param knowledge_base_name: Name of the KnowledgeBase. Required. - :type knowledge_base_name: str - :return: KnowledgeBaseVersion. The KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.ai.discovery.models.KnowledgeBaseVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models.KnowledgeBaseVersion] = kwargs.pop("cls", None) - - _request = build_knowledge_base_versions_get_latest_version_request( - knowledge_base_name=knowledge_base_name, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.KnowledgeBaseVersion, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, knowledge_base_name: str, *, created_since: Optional[datetime.datetime] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.KnowledgeBaseVersion"]: - """List KnowledgeBaseVersion resources. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :keyword created_since: The oldest creation timestamp to keep. Default value is None. - :paramtype created_since: ~datetime.datetime - :return: An iterator like instance of KnowledgeBaseVersion - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.KnowledgeBaseVersion]] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_knowledge_base_versions_list_request( - knowledge_base_name=knowledge_base_name, - created_since=created_since, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - async def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize( - List[_models.KnowledgeBaseVersion], - deserialized.get("value", []), - ) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("nextLink") or None, AsyncList(list_of_elem) - - async def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - @distributed_trace_async - async def get_operation_status( - self, knowledge_base_name: str, version_name: str, operation_id: str, **kwargs: Any - ) -> _models.KnowledgeBaseOperationStatus: - """Get the status of a long-running operation. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param operation_id: The unique ID of the operation. Required. - :type operation_id: str - :return: KnowledgeBaseOperationStatus. The KnowledgeBaseOperationStatus is compatible with - MutableMapping - :rtype: ~azure.ai.discovery.models.KnowledgeBaseOperationStatus - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models.KnowledgeBaseOperationStatus] = kwargs.pop("cls", None) - - _request = build_knowledge_base_versions_get_operation_status_request( - knowledge_base_name=knowledge_base_name, - version_name=version_name, - operation_id=operation_id, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.KnowledgeBaseOperationStatus, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - async def _start_indexing_initial( - self, - knowledge_base_name: str, - version_name: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - node_pool_id: str = _Unset, - project_id: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - if body is _Unset: - if node_pool_id is _Unset: - raise TypeError("missing required argument: node_pool_id") - body = {"nodePoolId": node_pool_id, "projectId": project_id} - body = {k: v for k, v in body.items() if v is not None} - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_knowledge_base_versions_start_indexing_request( - knowledge_base_name=knowledge_base_name, - version_name=version_name, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - response_headers["Repeatability-Result"] = self._deserialize( - "str", response.headers.get("Repeatability-Result") - ) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_start_indexing( - self, - knowledge_base_name: str, - version_name: str, - *, - node_pool_id: str, - content_type: str = "application/json", - project_id: Optional[str] = None, - **kwargs: Any - ) -> AsyncLROPoller[_models.KnowledgeBaseVersion]: - """Start indexing. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :keyword node_pool_id: Node pool ID. Required. - :paramtype node_pool_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword project_id: Project ID. Default value is None. - :paramtype project_id: str - :return: An instance of AsyncLROPoller that returns KnowledgeBaseVersion. The - KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_start_indexing( - self, - knowledge_base_name: str, - version_name: str, - body: JSON, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.KnowledgeBaseVersion]: - """Start indexing. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param body: Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns KnowledgeBaseVersion. The - KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_start_indexing( - self, - knowledge_base_name: str, - version_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.KnowledgeBaseVersion]: - """Start indexing. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param body: Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns KnowledgeBaseVersion. The - KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_start_indexing( - self, - knowledge_base_name: str, - version_name: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - node_pool_id: str = _Unset, - project_id: Optional[str] = None, - **kwargs: Any - ) -> AsyncLROPoller[_models.KnowledgeBaseVersion]: - """Start indexing. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword node_pool_id: Node pool ID. Required. - :paramtype node_pool_id: str - :keyword project_id: Project ID. Default value is None. - :paramtype project_id: str - :return: An instance of AsyncLROPoller that returns KnowledgeBaseVersion. The - KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeBaseVersion] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._start_indexing_initial( - knowledge_base_name=knowledge_base_name, - version_name=version_name, - body=body, - node_pool_id=node_pool_id, - project_id=project_id, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - response_headers["Repeatability-Result"] = self._deserialize( - "str", response.headers.get("Repeatability-Result") - ) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - - deserialized = _deserialize(_models.KnowledgeBaseVersion, response.json().get("result", {})) - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized - - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, - AsyncLROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs), - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.KnowledgeBaseVersion].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.KnowledgeBaseVersion]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - async def _cancel_indexing_initial( - self, - knowledge_base_name: str, - version_name: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - node_pool_id: str = _Unset, - project_id: Optional[str] = None, - **kwargs: Any - ) -> AsyncIterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - if body is _Unset: - if node_pool_id is _Unset: - raise TypeError("missing required argument: node_pool_id") - body = {"nodePoolId": node_pool_id, "projectId": project_id} - body = {k: v for k, v in body.items() if v is not None} - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_knowledge_base_versions_cancel_indexing_request( - knowledge_base_name=knowledge_base_name, - version_name=version_name, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - response_headers["Repeatability-Result"] = self._deserialize( - "str", response.headers.get("Repeatability-Result") - ) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def begin_cancel_indexing( - self, - knowledge_base_name: str, - version_name: str, - *, - node_pool_id: str, - content_type: str = "application/json", - project_id: Optional[str] = None, - **kwargs: Any - ) -> AsyncLROPoller[_models.KnowledgeBaseVersion]: - """Cancel indexing. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :keyword node_pool_id: Node pool ID. Required. - :paramtype node_pool_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword project_id: Project ID. Default value is None. - :paramtype project_id: str - :return: An instance of AsyncLROPoller that returns KnowledgeBaseVersion. The - KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_cancel_indexing( - self, - knowledge_base_name: str, - version_name: str, - body: JSON, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.KnowledgeBaseVersion]: - """Cancel indexing. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param body: Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns KnowledgeBaseVersion. The - KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def begin_cancel_indexing( - self, - knowledge_base_name: str, - version_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> AsyncLROPoller[_models.KnowledgeBaseVersion]: - """Cancel indexing. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param body: Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of AsyncLROPoller that returns KnowledgeBaseVersion. The - KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def begin_cancel_indexing( - self, - knowledge_base_name: str, - version_name: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - node_pool_id: str = _Unset, - project_id: Optional[str] = None, - **kwargs: Any - ) -> AsyncLROPoller[_models.KnowledgeBaseVersion]: - """Cancel indexing. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword node_pool_id: Node pool ID. Required. - :paramtype node_pool_id: str - :keyword project_id: Project ID. Default value is None. - :paramtype project_id: str - :return: An instance of AsyncLROPoller that returns KnowledgeBaseVersion. The - KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeBaseVersion] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._cancel_indexing_initial( - knowledge_base_name=knowledge_base_name, - version_name=version_name, - body=body, - node_pool_id=node_pool_id, - project_id=project_id, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - response_headers["Repeatability-Result"] = self._deserialize( - "str", response.headers.get("Repeatability-Result") - ) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - - deserialized = _deserialize(_models.KnowledgeBaseVersion, response.json().get("result", {})) - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized - - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, - AsyncLROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs), - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.KnowledgeBaseVersion].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.KnowledgeBaseVersion]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @api_version_validation( - method_added_on="2026-02-01-preview", - params_added_on={"2026-02-01-preview": ["api_version", "knowledge_base_name", "version_name", "accept"]}, - api_versions_list=["2026-02-01-preview"], - ) - async def _delete_initial(self, knowledge_base_name: str, version_name: str, **kwargs: Any) -> AsyncIterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_knowledge_base_versions_delete_request( - knowledge_base_name=knowledge_base_name, - version_name=version_name, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - @api_version_validation( - method_added_on="2026-02-01-preview", - params_added_on={"2026-02-01-preview": ["api_version", "knowledge_base_name", "version_name", "accept"]}, - api_versions_list=["2026-02-01-preview"], - ) - async def begin_delete( - self, knowledge_base_name: str, version_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.KnowledgeBaseVersion]: - """Delete a KnowledgeBaseVersion. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :return: An instance of AsyncLROPoller that returns KnowledgeBaseVersion. The - KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models.KnowledgeBaseVersion] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_initial( - knowledge_base_name=knowledge_base_name, - version_name=version_name, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - - deserialized = _deserialize(_models.KnowledgeBaseVersion, response.json().get("result", {})) - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized - - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, - AsyncLROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs), - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.KnowledgeBaseVersion].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.KnowledgeBaseVersion]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @api_version_validation( - method_added_on="2026-02-01-preview", - params_added_on={"2026-02-01-preview": ["api_version", "knowledge_base_name", "accept"]}, - api_versions_list=["2026-02-01-preview"], - ) - async def _delete_latest_version_initial(self, knowledge_base_name: str, **kwargs: Any) -> AsyncIterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_knowledge_base_versions_delete_latest_version_request( - knowledge_base_name=knowledge_base_name, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - @api_version_validation( - method_added_on="2026-02-01-preview", - params_added_on={"2026-02-01-preview": ["api_version", "knowledge_base_name", "accept"]}, - api_versions_list=["2026-02-01-preview"], - ) - async def begin_delete_latest_version( - self, knowledge_base_name: str, **kwargs: Any - ) -> AsyncLROPoller[_models.KnowledgeBaseVersion]: - """Delete the most recent version of KnowledgeBase. - - :param knowledge_base_name: Name of the KnowledgeBase. Required. - :type knowledge_base_name: str - :return: An instance of AsyncLROPoller that returns KnowledgeBaseVersion. The - KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.core.polling.AsyncLROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models.KnowledgeBaseVersion] = kwargs.pop("cls", None) - polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = await self._delete_latest_version_initial( - knowledge_base_name=knowledge_base_name, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - await raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - - deserialized = _deserialize(_models.KnowledgeBaseVersion, response.json().get("result", {})) - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized - - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, - AsyncLROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs), - ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) - else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.KnowledgeBaseVersion].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.KnowledgeBaseVersion]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/operations/_patch.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/operations/_patch.py deleted file mode 100644 index 87676c65a8f0..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/operations/_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/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/models/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/models/__init__.py deleted file mode 100644 index 298378d3278b..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/models/__init__.py +++ /dev/null @@ -1,48 +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 - KnowledgeBase, - KnowledgeBaseOperationStatus, - KnowledgeBaseVersion, - StorageAssetReference, - Tag, -) - -from ._enums import ( # type: ignore - ByType, - IndexingStatus, - OperationState, - ProvisioningState, - RepeatabilityResult, -) -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "KnowledgeBase", - "KnowledgeBaseOperationStatus", - "KnowledgeBaseVersion", - "StorageAssetReference", - "Tag", - "ByType", - "IndexingStatus", - "OperationState", - "ProvisioningState", - "RepeatabilityResult", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/models/_enums.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/models/_enums.py deleted file mode 100644 index 589beda7088d..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/models/_enums.py +++ /dev/null @@ -1,82 +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 enum import Enum -from azure.core import CaseInsensitiveEnumMeta - - -class ByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Enum for entity type.""" - - USER = "User" - """A human user.""" - APPLICATION = "Application" - """Application.""" - SYSTEM = "System" - """The backend system.""" - - -class IndexingStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Enum for IndexingStatus.""" - - NOT_STARTED = "NotStarted" - """Indexing Not started.""" - RUNNING = "Running" - """Running.""" - SUCCEEDED = "Succeeded" - """Succeeded.""" - CANCELED = "Canceled" - """Canceled.""" - FAILED = "Failed" - """Failed.""" - - -class OperationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Enum describing allowed operation states.""" - - NOT_STARTED = "NotStarted" - """The operation has not started.""" - RUNNING = "Running" - """The operation is in progress.""" - SUCCEEDED = "Succeeded" - """The operation has completed successfully.""" - FAILED = "Failed" - """The operation has failed.""" - CANCELED = "Canceled" - """The operation has been canceled by the user.""" - - -class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The resource provisioning state.""" - - SUCCEEDED = "Succeeded" - """Resource has been created.""" - FAILED = "Failed" - """Resource creation failed.""" - CANCELED = "Canceled" - """Resource creation was canceled.""" - ACCEPTED = "Accepted" - """The resource create request has been accepted.""" - PROVISIONING = "Provisioning" - """The resource is being provisioned.""" - UPDATING = "Updating" - """The resource is updating.""" - DELETING = "Deleting" - """The resource is being deleted.""" - - -class RepeatabilityResult(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Repeatability Result header options.""" - - ACCEPTED = "accepted" - """If the request was accepted and the server guarantees that the server state reflects a single - execution of the operation.""" - REJECTED = "rejected" - """If the request was rejected because the combination of Repeatability-First-Sent and - Repeatability-Request-ID were invalid or because the Repeatability-First-Sent value was outside - the range of values held by the server.""" diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/models/_models.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/models/_models.py deleted file mode 100644 index 406cb92737c5..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/models/_models.py +++ /dev/null @@ -1,358 +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=useless-super-delegation - -import datetime -from typing import Any, Mapping, Optional, TYPE_CHECKING, Union, overload - -from azure.core.exceptions import ODataV4Format - -from .._utils.model_base import Model as _Model, rest_field - -if TYPE_CHECKING: - from .. import models as _models - - -class KnowledgeBase(_Model): - """A knowledgeBase. - - :ivar name: The knowledgeBase name. Required. - :vartype name: str - :ivar id: The ID for the resource. - :vartype id: str - :ivar version: Version. Required. - :vartype version: str - :ivar bookshelf_name: The name of the associated Bookshelf tracked resource. Required. - :vartype bookshelf_name: str - :ivar storage_asset_references: Storage asset references to index. - :vartype storage_asset_references: list[~azure.ai.discovery.models.StorageAssetReference] - :ivar knowledge_base_url: URL to access the knowledge base. - :vartype knowledge_base_url: str - :ivar provisioning_state: Provisioning state. Known values are: "Succeeded", "Failed", - "Canceled", "Accepted", "Provisioning", "Updating", and "Deleting". - :vartype provisioning_state: str or ~azure.ai.discovery.models.ProvisioningState - :ivar created_at: The timestamp when the resource was created. - :vartype created_at: ~datetime.datetime - :ivar created_by: The ID of the user who created this resource. - :vartype created_by: str - :ivar created_by_type: The type of user who created this resource. Known values are: "User", - "Application", and "System". - :vartype created_by_type: str or ~azure.ai.discovery.models.ByType - :ivar last_modified_at: The timestamp when the resource was last updated. - :vartype last_modified_at: ~datetime.datetime - :ivar last_modified_by: The ID of the user who updated this resource. - :vartype last_modified_by: str - :ivar last_modified_by_type: The type of user who updated this resource. Known values are: - "User", "Application", and "System". - :vartype last_modified_by_type: str or ~azure.ai.discovery.models.ByType - :ivar tags: The tags. - :vartype tags: list[~azure.ai.discovery.models.Tag] - :ivar description: The description. Required. - :vartype description: str - :ivar copilot_instruction: The copilot instruction. Required. - :vartype copilot_instruction: str - :ivar status: The status. Known values are: "NotStarted", "Running", "Succeeded", "Canceled", - and "Failed". - :vartype status: str or ~azure.ai.discovery.models.IndexingStatus - """ - - name: str = rest_field(visibility=["read"]) - """The knowledgeBase name. Required.""" - id: Optional[str] = rest_field(visibility=["read"]) - """The ID for the resource.""" - version: str = rest_field(visibility=["read"]) - """Version. Required.""" - bookshelf_name: str = rest_field(name="bookshelfName", visibility=["read"]) - """The name of the associated Bookshelf tracked resource. Required.""" - storage_asset_references: Optional[list["_models.StorageAssetReference"]] = rest_field( - name="storageAssetReferences", visibility=["read", "create", "update"] - ) - """Storage asset references to index.""" - knowledge_base_url: Optional[str] = rest_field(name="knowledgeBaseUrl", visibility=["read"]) - """URL to access the knowledge base.""" - provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = rest_field( - name="provisioningState", visibility=["read"] - ) - """Provisioning state. Known values are: \"Succeeded\", \"Failed\", \"Canceled\", \"Accepted\", - \"Provisioning\", \"Updating\", and \"Deleting\".""" - created_at: Optional[datetime.datetime] = rest_field(name="createdAt", visibility=["read"], format="rfc3339") - """The timestamp when the resource was created.""" - created_by: Optional[str] = rest_field(name="createdBy", visibility=["read"]) - """The ID of the user who created this resource.""" - created_by_type: Optional[Union[str, "_models.ByType"]] = rest_field(name="createdByType", visibility=["read"]) - """The type of user who created this resource. Known values are: \"User\", \"Application\", and - \"System\".""" - last_modified_at: Optional[datetime.datetime] = rest_field( - name="lastModifiedAt", visibility=["read"], format="rfc3339" - ) - """The timestamp when the resource was last updated.""" - last_modified_by: Optional[str] = rest_field(name="lastModifiedBy", visibility=["read"]) - """The ID of the user who updated this resource.""" - last_modified_by_type: Optional[Union[str, "_models.ByType"]] = rest_field( - name="lastModifiedByType", visibility=["read"] - ) - """The type of user who updated this resource. Known values are: \"User\", \"Application\", and - \"System\".""" - tags: Optional[list["_models.Tag"]] = rest_field(visibility=["read", "create", "update"]) - """The tags.""" - description: str = rest_field(visibility=["read", "create", "update"]) - """The description. Required.""" - copilot_instruction: str = rest_field(name="copilotInstruction", visibility=["read", "create", "update"]) - """The copilot instruction. Required.""" - status: Optional[Union[str, "_models.IndexingStatus"]] = rest_field(visibility=["read"]) - """The status. Known values are: \"NotStarted\", \"Running\", \"Succeeded\", \"Canceled\", and - \"Failed\".""" - - @overload - def __init__( - self, - *, - description: str, - copilot_instruction: str, - storage_asset_references: Optional[list["_models.StorageAssetReference"]] = None, - tags: Optional[list["_models.Tag"]] = 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 KnowledgeBaseOperationStatus(_Model): - """Status of a KnowledgeBase operation. - - :ivar id: The unique ID of the operation. Required. - :vartype id: str - :ivar status: The status of the operation. Required. Known values are: "NotStarted", "Running", - "Succeeded", "Failed", and "Canceled". - :vartype status: str or ~azure.ai.discovery.models.OperationState - :ivar error: Error object that describes the error when status is 'Failed'. - :vartype error: ~azure.core.ODataV4Format - :ivar result: The KnowledgeBaseVersion result of the operation. - :vartype result: ~azure.ai.discovery.models.KnowledgeBaseVersion - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the operation. Required.""" - status: Union[str, "_models.OperationState"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the operation. Required. Known values are: \"NotStarted\", \"Running\", - \"Succeeded\", \"Failed\", and \"Canceled\".""" - error: Optional[ODataV4Format] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Error object that describes the error when status is 'Failed'.""" - result: Optional["_models.KnowledgeBaseVersion"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The KnowledgeBaseVersion result of the operation.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - status: Union[str, "_models.OperationState"], - error: Optional[ODataV4Format] = None, - result: Optional["_models.KnowledgeBaseVersion"] = 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 KnowledgeBaseVersion(_Model): - """A version. - - :ivar name: The version name. Required. - :vartype name: str - :ivar id: The ID for the resource. - :vartype id: str - :ivar version: Version. Required. - :vartype version: str - :ivar bookshelf_name: The name of the associated Bookshelf tracked resource. Required. - :vartype bookshelf_name: str - :ivar storage_asset_references: Storage asset references to index. - :vartype storage_asset_references: list[~azure.ai.discovery.models.StorageAssetReference] - :ivar knowledge_base_url: URL to access the knowledge base. - :vartype knowledge_base_url: str - :ivar provisioning_state: Provisioning state. Known values are: "Succeeded", "Failed", - "Canceled", "Accepted", "Provisioning", "Updating", and "Deleting". - :vartype provisioning_state: str or ~azure.ai.discovery.models.ProvisioningState - :ivar created_at: The timestamp when the resource was created. - :vartype created_at: ~datetime.datetime - :ivar created_by: The ID of the user who created this resource. - :vartype created_by: str - :ivar created_by_type: The type of user who created this resource. Known values are: "User", - "Application", and "System". - :vartype created_by_type: str or ~azure.ai.discovery.models.ByType - :ivar last_modified_at: The timestamp when the resource was last updated. - :vartype last_modified_at: ~datetime.datetime - :ivar last_modified_by: The ID of the user who updated this resource. - :vartype last_modified_by: str - :ivar last_modified_by_type: The type of user who updated this resource. Known values are: - "User", "Application", and "System". - :vartype last_modified_by_type: str or ~azure.ai.discovery.models.ByType - :ivar tags: The tags. - :vartype tags: list[~azure.ai.discovery.models.Tag] - :ivar description: The description. Required. - :vartype description: str - :ivar copilot_instruction: The copilot instruction. Required. - :vartype copilot_instruction: str - :ivar status: The status. Known values are: "NotStarted", "Running", "Succeeded", "Canceled", - and "Failed". - :vartype status: str or ~azure.ai.discovery.models.IndexingStatus - """ - - name: str = rest_field(visibility=["read"]) - """The version name. Required.""" - id: Optional[str] = rest_field(visibility=["read"]) - """The ID for the resource.""" - version: str = rest_field(visibility=["read"]) - """Version. Required.""" - bookshelf_name: str = rest_field(name="bookshelfName", visibility=["read"]) - """The name of the associated Bookshelf tracked resource. Required.""" - storage_asset_references: Optional[list["_models.StorageAssetReference"]] = rest_field( - name="storageAssetReferences", visibility=["read", "create", "update"] - ) - """Storage asset references to index.""" - knowledge_base_url: Optional[str] = rest_field(name="knowledgeBaseUrl", visibility=["read"]) - """URL to access the knowledge base.""" - provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = rest_field( - name="provisioningState", visibility=["read"] - ) - """Provisioning state. Known values are: \"Succeeded\", \"Failed\", \"Canceled\", \"Accepted\", - \"Provisioning\", \"Updating\", and \"Deleting\".""" - created_at: Optional[datetime.datetime] = rest_field(name="createdAt", visibility=["read"], format="rfc3339") - """The timestamp when the resource was created.""" - created_by: Optional[str] = rest_field(name="createdBy", visibility=["read"]) - """The ID of the user who created this resource.""" - created_by_type: Optional[Union[str, "_models.ByType"]] = rest_field(name="createdByType", visibility=["read"]) - """The type of user who created this resource. Known values are: \"User\", \"Application\", and - \"System\".""" - last_modified_at: Optional[datetime.datetime] = rest_field( - name="lastModifiedAt", visibility=["read"], format="rfc3339" - ) - """The timestamp when the resource was last updated.""" - last_modified_by: Optional[str] = rest_field(name="lastModifiedBy", visibility=["read"]) - """The ID of the user who updated this resource.""" - last_modified_by_type: Optional[Union[str, "_models.ByType"]] = rest_field( - name="lastModifiedByType", visibility=["read"] - ) - """The type of user who updated this resource. Known values are: \"User\", \"Application\", and - \"System\".""" - tags: Optional[list["_models.Tag"]] = rest_field(visibility=["read", "create", "update"]) - """The tags.""" - description: str = rest_field(visibility=["read", "create", "update"]) - """The description. Required.""" - copilot_instruction: str = rest_field(name="copilotInstruction", visibility=["read", "create", "update"]) - """The copilot instruction. Required.""" - status: Optional[Union[str, "_models.IndexingStatus"]] = rest_field(visibility=["read"]) - """The status. Known values are: \"NotStarted\", \"Running\", \"Succeeded\", \"Canceled\", and - \"Failed\".""" - - @overload - def __init__( - self, - *, - description: str, - copilot_instruction: str, - storage_asset_references: Optional[list["_models.StorageAssetReference"]] = None, - tags: Optional[list["_models.Tag"]] = 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 StorageAssetReference(_Model): - """Reference to a storage asset with identity information. - - :ivar id: The ARM resource ID of the storage asset. Required. - :vartype id: str - :ivar user_assigned_identity: The ARM resource ID of the User Assigned Managed Identity to - access the storage asset. - :vartype user_assigned_identity: str - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ARM resource ID of the storage asset. Required.""" - user_assigned_identity: Optional[str] = rest_field( - name="userAssignedIdentity", visibility=["read", "create", "update", "delete", "query"] - ) - """The ARM resource ID of the User Assigned Managed Identity to access the storage asset.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - user_assigned_identity: 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 Tag(_Model): - """Definition of Tag. - - :ivar key: Property key. - :vartype key: str - :ivar value: Property value. - :vartype value: str - """ - - key: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Property key.""" - value: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Property value.""" - - @overload - def __init__( - self, - *, - key: Optional[str] = None, - value: 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) diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/operations/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/operations/__init__.py deleted file mode 100644 index fe6367b60ed1..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/operations/__init__.py +++ /dev/null @@ -1,27 +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 ._operations import KnowledgeBasesOperations # type: ignore -from ._operations import KnowledgeBaseVersionsOperations # type: ignore - -from ._patch import __all__ as _patch_all -from ._patch import * -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "KnowledgeBasesOperations", - "KnowledgeBaseVersionsOperations", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore -_patch_sdk() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/operations/_operations.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/operations/_operations.py deleted file mode 100644 index b92d2b955823..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/operations/_operations.py +++ /dev/null @@ -1,1678 +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 collections.abc import MutableMapping -import datetime -from io import IOBase -import json -from typing import Any, Callable, IO, Iterator, Optional, TypeVar, Union, cast, overload -import urllib.parse -import uuid - -from azure.core import PipelineClient -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - StreamClosedError, - StreamConsumedError, - map_error, -) -from azure.core.paging import ItemPaged -from azure.core.pipeline import PipelineResponse -from azure.core.polling import LROPoller, NoPolling, PollingMethod -from azure.core.polling.base_polling import LROBasePolling -from azure.core.rest import HttpRequest, HttpResponse -from azure.core.tracing.decorator import distributed_trace -from azure.core.utils import case_insensitive_dict - -from .. import models as _models -from .._configuration import BookshelfClientConfiguration -from .._utils.model_base import SdkJSONEncoder, _deserialize -from .._utils.serialization import Deserializer, Serializer -from .._validation import api_version_validation - -T = TypeVar("T") -ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] -JSON = MutableMapping[str, Any] -_Unset: Any = object() -List = list - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_knowledge_bases_list_request(**kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/knowledgeBases" - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_knowledge_base_versions_create_or_update_request( # pylint: disable=name-too-long - knowledge_base_name: str, version_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/knowledgeBases/{knowledgeBaseName}/versions/{versionName}" - path_format_arguments = { - "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), - "versionName": _SERIALIZER.url("version_name", version_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_knowledge_base_versions_get_request( # pylint: disable=name-too-long - knowledge_base_name: str, version_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/knowledgeBases/{knowledgeBaseName}/versions/{versionName}" - path_format_arguments = { - "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), - "versionName": _SERIALIZER.url("version_name", version_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_knowledge_base_versions_get_latest_version_request( # pylint: disable=name-too-long - knowledge_base_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/knowledgeBases/{knowledgeBaseName}/versions/@latest" - path_format_arguments = { - "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_knowledge_base_versions_list_request( # pylint: disable=name-too-long - knowledge_base_name: str, *, created_since: Optional[datetime.datetime] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/knowledgeBases/{knowledgeBaseName}/versions" - path_format_arguments = { - "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if created_since is not None: - _params["createdSince"] = _SERIALIZER.query("created_since", created_since, "iso-8601") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_knowledge_base_versions_get_operation_status_request( # pylint: disable=name-too-long - knowledge_base_name: str, version_name: str, operation_id: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/knowledgeBases/{knowledgeBaseName}/versions/{versionName}/operations/{operationId}" - path_format_arguments = { - "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), - "versionName": _SERIALIZER.url("version_name", version_name, "str"), - "operationId": _SERIALIZER.url("operation_id", operation_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_knowledge_base_versions_start_indexing_request( # pylint: disable=name-too-long - knowledge_base_name: str, version_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/knowledgeBases/{knowledgeBaseName}/versions/{versionName}:startIndexing" - path_format_arguments = { - "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), - "versionName": _SERIALIZER.url("version_name", version_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if "Repeatability-Request-ID" not in _headers: - _headers["Repeatability-Request-ID"] = str(uuid.uuid4()) - if "Repeatability-First-Sent" not in _headers: - _headers["Repeatability-First-Sent"] = _SERIALIZER.serialize_data( - datetime.datetime.now(datetime.timezone.utc), "rfc-1123" - ) - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_knowledge_base_versions_cancel_indexing_request( # pylint: disable=name-too-long - knowledge_base_name: str, version_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/knowledgeBases/{knowledgeBaseName}/versions/{versionName}:cancelIndexing" - path_format_arguments = { - "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), - "versionName": _SERIALIZER.url("version_name", version_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if "Repeatability-Request-ID" not in _headers: - _headers["Repeatability-Request-ID"] = str(uuid.uuid4()) - if "Repeatability-First-Sent" not in _headers: - _headers["Repeatability-First-Sent"] = _SERIALIZER.serialize_data( - datetime.datetime.now(datetime.timezone.utc), "rfc-1123" - ) - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_knowledge_base_versions_delete_request( # pylint: disable=name-too-long - knowledge_base_name: str, version_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/knowledgeBases/{knowledgeBaseName}/versions/{versionName}" - path_format_arguments = { - "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), - "versionName": _SERIALIZER.url("version_name", version_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_knowledge_base_versions_delete_latest_version_request( # pylint: disable=name-too-long - knowledge_base_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/knowledgeBases/{knowledgeBaseName}/versions/@latest" - path_format_arguments = { - "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -class KnowledgeBasesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.ai.discovery.BookshelfClient`'s - :attr:`knowledge_bases` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: BookshelfClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @distributed_trace - def list(self, **kwargs: Any) -> ItemPaged["_models.KnowledgeBase"]: - """List KnowledgeBase resources. - - :return: An iterator like instance of KnowledgeBase - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.discovery.models.KnowledgeBase] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.KnowledgeBase]] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_knowledge_bases_list_request( - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize( - List[_models.KnowledgeBase], - deserialized.get("value", []), - ) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("nextLink") or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - -class KnowledgeBaseVersionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.ai.discovery.BookshelfClient`'s - :attr:`knowledge_base_versions` attribute. - """ - - def __init__(self, *args, **kwargs) -> None: - input_args = list(args) - self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") - self._config: BookshelfClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") - self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") - self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") - - @overload - def create_or_update( - self, - knowledge_base_name: str, - version_name: str, - resource: _models.KnowledgeBaseVersion, - *, - content_type: str = "application/merge-patch+json", - **kwargs: Any - ) -> _models.KnowledgeBaseVersion: - """Creates or updates a KnowledgeBaseVersion. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param resource: The resource instance. Required. - :type resource: ~azure.ai.discovery.models.KnowledgeBaseVersion - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :return: KnowledgeBaseVersion. The KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.ai.discovery.models.KnowledgeBaseVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - knowledge_base_name: str, - version_name: str, - resource: JSON, - *, - content_type: str = "application/merge-patch+json", - **kwargs: Any - ) -> _models.KnowledgeBaseVersion: - """Creates or updates a KnowledgeBaseVersion. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param resource: The resource instance. Required. - :type resource: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :return: KnowledgeBaseVersion. The KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.ai.discovery.models.KnowledgeBaseVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_or_update( - self, - knowledge_base_name: str, - version_name: str, - resource: IO[bytes], - *, - content_type: str = "application/merge-patch+json", - **kwargs: Any - ) -> _models.KnowledgeBaseVersion: - """Creates or updates a KnowledgeBaseVersion. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param resource: The resource instance. Required. - :type resource: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :return: KnowledgeBaseVersion. The KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.ai.discovery.models.KnowledgeBaseVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_or_update( - self, - knowledge_base_name: str, - version_name: str, - resource: Union[_models.KnowledgeBaseVersion, JSON, IO[bytes]], - **kwargs: Any - ) -> _models.KnowledgeBaseVersion: - """Creates or updates a KnowledgeBaseVersion. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param resource: The resource instance. Is one of the following types: KnowledgeBaseVersion, - JSON, IO[bytes] Required. - :type resource: ~azure.ai.discovery.models.KnowledgeBaseVersion or JSON or IO[bytes] - :return: KnowledgeBaseVersion. The KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.ai.discovery.models.KnowledgeBaseVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeBaseVersion] = kwargs.pop("cls", None) - - content_type = content_type or "application/merge-patch+json" - _content = None - if isinstance(resource, (IOBase, bytes)): - _content = resource - else: - _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_knowledge_base_versions_create_or_update_request( - knowledge_base_name=knowledge_base_name, - version_name=version_name, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200, 201]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.KnowledgeBaseVersion, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get(self, knowledge_base_name: str, version_name: str, **kwargs: Any) -> _models.KnowledgeBaseVersion: - """Fetch a KnowledgeBaseVersion by name. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :return: KnowledgeBaseVersion. The KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.ai.discovery.models.KnowledgeBaseVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models.KnowledgeBaseVersion] = kwargs.pop("cls", None) - - _request = build_knowledge_base_versions_get_request( - knowledge_base_name=knowledge_base_name, - version_name=version_name, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.KnowledgeBaseVersion, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_latest_version(self, knowledge_base_name: str, **kwargs: Any) -> _models.KnowledgeBaseVersion: - """Get the most recent version of KnowledgeBase. - - :param knowledge_base_name: Name of the KnowledgeBase. Required. - :type knowledge_base_name: str - :return: KnowledgeBaseVersion. The KnowledgeBaseVersion is compatible with MutableMapping - :rtype: ~azure.ai.discovery.models.KnowledgeBaseVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models.KnowledgeBaseVersion] = kwargs.pop("cls", None) - - _request = build_knowledge_base_versions_get_latest_version_request( - knowledge_base_name=knowledge_base_name, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.KnowledgeBaseVersion, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, knowledge_base_name: str, *, created_since: Optional[datetime.datetime] = None, **kwargs: Any - ) -> ItemPaged["_models.KnowledgeBaseVersion"]: - """List KnowledgeBaseVersion resources. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :keyword created_since: The oldest creation timestamp to keep. Default value is None. - :paramtype created_since: ~datetime.datetime - :return: An iterator like instance of KnowledgeBaseVersion - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.KnowledgeBaseVersion]] = kwargs.pop("cls", None) - - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - def prepare_request(next_link=None): - if not next_link: - - _request = build_knowledge_base_versions_list_request( - knowledge_base_name=knowledge_base_name, - created_since=created_since, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - else: - # make call to next link with the client's api-version - _parsed_next_link = urllib.parse.urlparse(next_link) - _next_request_params = case_insensitive_dict( - { - key: [urllib.parse.quote(v) for v in value] - for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() - } - ) - _next_request_params["api-version"] = self._config.api_version - _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params - ) - path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - return _request - - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize( - List[_models.KnowledgeBaseVersion], - deserialized.get("value", []), - ) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("nextLink") or None, iter(list_of_elem) - - def get_next(next_link=None): - _request = prepare_request(next_link) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response - - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - - @distributed_trace - def get_operation_status( - self, knowledge_base_name: str, version_name: str, operation_id: str, **kwargs: Any - ) -> _models.KnowledgeBaseOperationStatus: - """Get the status of a long-running operation. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param operation_id: The unique ID of the operation. Required. - :type operation_id: str - :return: KnowledgeBaseOperationStatus. The KnowledgeBaseOperationStatus is compatible with - MutableMapping - :rtype: ~azure.ai.discovery.models.KnowledgeBaseOperationStatus - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models.KnowledgeBaseOperationStatus] = kwargs.pop("cls", None) - - _request = build_knowledge_base_versions_get_operation_status_request( - knowledge_base_name=knowledge_base_name, - version_name=version_name, - operation_id=operation_id, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [200]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.KnowledgeBaseOperationStatus, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - def _start_indexing_initial( - self, - knowledge_base_name: str, - version_name: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - node_pool_id: str = _Unset, - project_id: Optional[str] = None, - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - if body is _Unset: - if node_pool_id is _Unset: - raise TypeError("missing required argument: node_pool_id") - body = {"nodePoolId": node_pool_id, "projectId": project_id} - body = {k: v for k, v in body.items() if v is not None} - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_knowledge_base_versions_start_indexing_request( - knowledge_base_name=knowledge_base_name, - version_name=version_name, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - response_headers["Repeatability-Result"] = self._deserialize( - "str", response.headers.get("Repeatability-Result") - ) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_start_indexing( - self, - knowledge_base_name: str, - version_name: str, - *, - node_pool_id: str, - content_type: str = "application/json", - project_id: Optional[str] = None, - **kwargs: Any - ) -> LROPoller[_models.KnowledgeBaseVersion]: - """Start indexing. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :keyword node_pool_id: Node pool ID. Required. - :paramtype node_pool_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword project_id: Project ID. Default value is None. - :paramtype project_id: str - :return: An instance of LROPoller that returns KnowledgeBaseVersion. The KnowledgeBaseVersion - is compatible with MutableMapping - :rtype: ~azure.core.polling.LROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_start_indexing( - self, - knowledge_base_name: str, - version_name: str, - body: JSON, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.KnowledgeBaseVersion]: - """Start indexing. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param body: Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns KnowledgeBaseVersion. The KnowledgeBaseVersion - is compatible with MutableMapping - :rtype: ~azure.core.polling.LROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_start_indexing( - self, - knowledge_base_name: str, - version_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.KnowledgeBaseVersion]: - """Start indexing. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param body: Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns KnowledgeBaseVersion. The KnowledgeBaseVersion - is compatible with MutableMapping - :rtype: ~azure.core.polling.LROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_start_indexing( - self, - knowledge_base_name: str, - version_name: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - node_pool_id: str = _Unset, - project_id: Optional[str] = None, - **kwargs: Any - ) -> LROPoller[_models.KnowledgeBaseVersion]: - """Start indexing. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword node_pool_id: Node pool ID. Required. - :paramtype node_pool_id: str - :keyword project_id: Project ID. Default value is None. - :paramtype project_id: str - :return: An instance of LROPoller that returns KnowledgeBaseVersion. The KnowledgeBaseVersion - is compatible with MutableMapping - :rtype: ~azure.core.polling.LROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeBaseVersion] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._start_indexing_initial( - knowledge_base_name=knowledge_base_name, - version_name=version_name, - body=body, - node_pool_id=node_pool_id, - project_id=project_id, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - response_headers["Repeatability-Result"] = self._deserialize( - "str", response.headers.get("Repeatability-Result") - ) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - - deserialized = _deserialize(_models.KnowledgeBaseVersion, response.json().get("result", {})) - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized - - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.KnowledgeBaseVersion].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.KnowledgeBaseVersion]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - def _cancel_indexing_initial( - self, - knowledge_base_name: str, - version_name: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - node_pool_id: str = _Unset, - project_id: Optional[str] = None, - **kwargs: Any - ) -> Iterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - if body is _Unset: - if node_pool_id is _Unset: - raise TypeError("missing required argument: node_pool_id") - body = {"nodePoolId": node_pool_id, "projectId": project_id} - body = {k: v for k, v in body.items() if v is not None} - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_knowledge_base_versions_cancel_indexing_request( - knowledge_base_name=knowledge_base_name, - version_name=version_name, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - response_headers["Repeatability-Result"] = self._deserialize( - "str", response.headers.get("Repeatability-Result") - ) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - def begin_cancel_indexing( - self, - knowledge_base_name: str, - version_name: str, - *, - node_pool_id: str, - content_type: str = "application/json", - project_id: Optional[str] = None, - **kwargs: Any - ) -> LROPoller[_models.KnowledgeBaseVersion]: - """Cancel indexing. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :keyword node_pool_id: Node pool ID. Required. - :paramtype node_pool_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword project_id: Project ID. Default value is None. - :paramtype project_id: str - :return: An instance of LROPoller that returns KnowledgeBaseVersion. The KnowledgeBaseVersion - is compatible with MutableMapping - :rtype: ~azure.core.polling.LROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_cancel_indexing( - self, - knowledge_base_name: str, - version_name: str, - body: JSON, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.KnowledgeBaseVersion]: - """Cancel indexing. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param body: Required. - :type body: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns KnowledgeBaseVersion. The KnowledgeBaseVersion - is compatible with MutableMapping - :rtype: ~azure.core.polling.LROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def begin_cancel_indexing( - self, - knowledge_base_name: str, - version_name: str, - body: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> LROPoller[_models.KnowledgeBaseVersion]: - """Cancel indexing. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param body: Required. - :type body: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: An instance of LROPoller that returns KnowledgeBaseVersion. The KnowledgeBaseVersion - is compatible with MutableMapping - :rtype: ~azure.core.polling.LROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def begin_cancel_indexing( - self, - knowledge_base_name: str, - version_name: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - node_pool_id: str = _Unset, - project_id: Optional[str] = None, - **kwargs: Any - ) -> LROPoller[_models.KnowledgeBaseVersion]: - """Cancel indexing. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword node_pool_id: Node pool ID. Required. - :paramtype node_pool_id: str - :keyword project_id: Project ID. Default value is None. - :paramtype project_id: str - :return: An instance of LROPoller that returns KnowledgeBaseVersion. The KnowledgeBaseVersion - is compatible with MutableMapping - :rtype: ~azure.core.polling.LROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} - - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.KnowledgeBaseVersion] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._cancel_indexing_initial( - knowledge_base_name=knowledge_base_name, - version_name=version_name, - body=body, - node_pool_id=node_pool_id, - project_id=project_id, - content_type=content_type, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - response_headers["Repeatability-Result"] = self._deserialize( - "str", response.headers.get("Repeatability-Result") - ) - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - - deserialized = _deserialize(_models.KnowledgeBaseVersion, response.json().get("result", {})) - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized - - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.KnowledgeBaseVersion].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.KnowledgeBaseVersion]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @api_version_validation( - method_added_on="2026-02-01-preview", - params_added_on={"2026-02-01-preview": ["api_version", "knowledge_base_name", "version_name", "accept"]}, - api_versions_list=["2026-02-01-preview"], - ) - def _delete_initial(self, knowledge_base_name: str, version_name: str, **kwargs: Any) -> Iterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_knowledge_base_versions_delete_request( - knowledge_base_name=knowledge_base_name, - version_name=version_name, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - @api_version_validation( - method_added_on="2026-02-01-preview", - params_added_on={"2026-02-01-preview": ["api_version", "knowledge_base_name", "version_name", "accept"]}, - api_versions_list=["2026-02-01-preview"], - ) - def begin_delete( - self, knowledge_base_name: str, version_name: str, **kwargs: Any - ) -> LROPoller[_models.KnowledgeBaseVersion]: - """Delete a KnowledgeBaseVersion. - - :param knowledge_base_name: The knowledgeBase name. Required. - :type knowledge_base_name: str - :param version_name: The version name. Required. - :type version_name: str - :return: An instance of LROPoller that returns KnowledgeBaseVersion. The KnowledgeBaseVersion - is compatible with MutableMapping - :rtype: ~azure.core.polling.LROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models.KnowledgeBaseVersion] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_initial( - knowledge_base_name=knowledge_base_name, - version_name=version_name, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - - deserialized = _deserialize(_models.KnowledgeBaseVersion, response.json().get("result", {})) - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized - - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.KnowledgeBaseVersion].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.KnowledgeBaseVersion]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) - - @api_version_validation( - method_added_on="2026-02-01-preview", - params_added_on={"2026-02-01-preview": ["api_version", "knowledge_base_name", "accept"]}, - api_versions_list=["2026-02-01-preview"], - ) - def _delete_latest_version_initial(self, knowledge_base_name: str, **kwargs: Any) -> Iterator[bytes]: - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_knowledge_base_versions_delete_latest_version_request( - knowledge_base_name=knowledge_base_name, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _decompress = kwargs.pop("decompress", True) - _stream = True - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - - response = pipeline_response.http_response - - if response.status_code not in [202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - @api_version_validation( - method_added_on="2026-02-01-preview", - params_added_on={"2026-02-01-preview": ["api_version", "knowledge_base_name", "accept"]}, - api_versions_list=["2026-02-01-preview"], - ) - def begin_delete_latest_version( - self, knowledge_base_name: str, **kwargs: Any - ) -> LROPoller[_models.KnowledgeBaseVersion]: - """Delete the most recent version of KnowledgeBase. - - :param knowledge_base_name: Name of the KnowledgeBase. Required. - :type knowledge_base_name: str - :return: An instance of LROPoller that returns KnowledgeBaseVersion. The KnowledgeBaseVersion - is compatible with MutableMapping - :rtype: ~azure.core.polling.LROPoller[~azure.ai.discovery.models.KnowledgeBaseVersion] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[_models.KnowledgeBaseVersion] = kwargs.pop("cls", None) - polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) - lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) - cont_token: Optional[str] = kwargs.pop("continuation_token", None) - if cont_token is None: - raw_result = self._delete_latest_version_initial( - knowledge_base_name=knowledge_base_name, - cls=lambda x, y, z: x, - headers=_headers, - params=_params, - **kwargs - ) - raw_result.http_response.read() # type: ignore - kwargs.pop("error_map", None) - - def get_long_running_output(pipeline_response): - response_headers = {} - response = pipeline_response.http_response - response_headers["Operation-Location"] = self._deserialize( - "str", response.headers.get("Operation-Location") - ) - - deserialized = _deserialize(_models.KnowledgeBaseVersion, response.json().get("result", {})) - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized - - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - if polling is True: - polling_method: PollingMethod = cast( - PollingMethod, LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) - ) - elif polling is False: - polling_method = cast(PollingMethod, NoPolling()) - else: - polling_method = polling - if cont_token: - return LROPoller[_models.KnowledgeBaseVersion].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.KnowledgeBaseVersion]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/operations/_patch.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/operations/_patch.py deleted file mode 100644 index 87676c65a8f0..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/operations/_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/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/py.typed b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/dev_requirements.txt b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/dev_requirements.txt deleted file mode 100644 index 0e53b6a72db5..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/dev_requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ --e ../../../eng/tools/azure-sdk-tools -../../core/azure-core -aiohttp \ No newline at end of file diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_cancel_indexing_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_cancel_indexing_maximum_set_gen.py deleted file mode 100644 index 22f8ba3b413a..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_cancel_indexing_maximum_set_gen.py +++ /dev/null @@ -1,44 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import BookshelfClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python knowledge_base_versions_cancel_indexing_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = BookshelfClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.knowledge_base_versions.begin_cancel_indexing( - knowledge_base_name="e57059bfca4633b98b", - version_name="cf64608c6518a1e64e", - body={"nodePoolId": "ueuddxqctajmqmgghpnhuavsije", "projectId": "mly"}, - node_pool_id="str", - ).result() - print(response) - - -# x-ms-original-file: 2026-02-01-preview/KnowledgeBaseVersions_CancelIndexing_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_create_or_update_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_create_or_update_maximum_set_gen.py deleted file mode 100644 index f53c6a69bce1..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_create_or_update_maximum_set_gen.py +++ /dev/null @@ -1,54 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# 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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import BookshelfClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python knowledge_base_versions_create_or_update_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = BookshelfClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.knowledge_base_versions.create_or_update( - knowledge_base_name="ae6f4c420b58addbf3", - version_name="b433a6ba4c4a63c863", - resource={ - "copilotInstruction": "lzwsycfvrbceufnrohqwkgut", - "description": "hwckfj", - "storageAssetReferences": [ - { - "id": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example-rg/providers/Microsoft.Discovery/storageContainers/example-storageContainer/storageAssets/example-storageAsset", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/example-userAssignedIdentity", - } - ], - "tags": [{"key": "lxunxbwhxascviiwvhokqci", "value": "qbafqzakqkebafgdinfvwxsfdofn"}], - }, - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/KnowledgeBaseVersions_CreateOrUpdate_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_delete_latest_version_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_delete_latest_version_maximum_set_gen.py deleted file mode 100644 index 9d9b49c6c0b6..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_delete_latest_version_maximum_set_gen.py +++ /dev/null @@ -1,41 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import BookshelfClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python knowledge_base_versions_delete_latest_version_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = BookshelfClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.knowledge_base_versions.begin_delete_latest_version( - knowledge_base_name="b55988eb9d241689b8", - ).result() - print(response) - - -# x-ms-original-file: 2026-02-01-preview/KnowledgeBaseVersions_DeleteLatestVersion_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_delete_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_delete_maximum_set_gen.py deleted file mode 100644 index 0358a74c2e57..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_delete_maximum_set_gen.py +++ /dev/null @@ -1,42 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import BookshelfClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python knowledge_base_versions_delete_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = BookshelfClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.knowledge_base_versions.begin_delete( - knowledge_base_name="f0c30a8258f748aa18", - version_name="50feb896eb49077da6", - ).result() - print(response) - - -# x-ms-original-file: 2026-02-01-preview/KnowledgeBaseVersions_Delete_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_get_latest_version_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_get_latest_version_maximum_set_gen.py deleted file mode 100644 index 081e33874cb9..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_get_latest_version_maximum_set_gen.py +++ /dev/null @@ -1,41 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import BookshelfClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python knowledge_base_versions_get_latest_version_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = BookshelfClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.knowledge_base_versions.get_latest_version( - knowledge_base_name="0601573863695be9da", - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/KnowledgeBaseVersions_GetLatestVersion_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_get_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_get_maximum_set_gen.py deleted file mode 100644 index 0116bfd22d96..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_get_maximum_set_gen.py +++ /dev/null @@ -1,42 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import BookshelfClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python knowledge_base_versions_get_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = BookshelfClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.knowledge_base_versions.get( - knowledge_base_name="4c4d48817f6a3ed426", - version_name="3b8d0a60c75b8e2f09", - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/KnowledgeBaseVersions_Get_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_get_operation_status_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_get_operation_status_maximum_set_gen.py deleted file mode 100644 index d25c76082764..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_get_operation_status_maximum_set_gen.py +++ /dev/null @@ -1,43 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import BookshelfClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python knowledge_base_versions_get_operation_status_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = BookshelfClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.knowledge_base_versions.get_operation_status( - knowledge_base_name="cb942f669e90f0d39d", - version_name="033aa0e2c27b2ec279", - operation_id="lhtlukfyjhwezaecfcgyicmeedzl", - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/KnowledgeBaseVersions_GetOperationStatus_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_list_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_list_maximum_set_gen.py deleted file mode 100644 index f8cdfedfce66..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_list_maximum_set_gen.py +++ /dev/null @@ -1,42 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import BookshelfClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python knowledge_base_versions_list_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = BookshelfClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.knowledge_base_versions.list( - knowledge_base_name="5feeace75fdca6cb6e", - ) - for item in response: - print(item) - - -# x-ms-original-file: 2026-02-01-preview/KnowledgeBaseVersions_List_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_start_indexing_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_start_indexing_maximum_set_gen.py deleted file mode 100644 index d18872c8d90c..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_base_versions_start_indexing_maximum_set_gen.py +++ /dev/null @@ -1,44 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import BookshelfClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python knowledge_base_versions_start_indexing_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = BookshelfClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.knowledge_base_versions.begin_start_indexing( - knowledge_base_name="5da1f8945fdb7143c7", - version_name="3abcb1f011d1790665", - body={"nodePoolId": "ueuddxqctajmqmgghpnhuavsije", "projectId": "mly"}, - node_pool_id="str", - ).result() - print(response) - - -# x-ms-original-file: 2026-02-01-preview/KnowledgeBaseVersions_StartIndexing_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_bases_list_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_bases_list_maximum_set_gen.py deleted file mode 100644 index 98de998bd034..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_samples/knowledge_bases_list_maximum_set_gen.py +++ /dev/null @@ -1,40 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import BookshelfClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python knowledge_bases_list_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = BookshelfClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.knowledge_bases.list() - for item in response: - print(item) - - -# x-ms-original-file: 2026-02-01-preview/KnowledgeBases_List_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/test_bookshelf_knowledge_bases_operations.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/test_bookshelf_knowledge_bases_operations.py deleted file mode 100644 index a5ed2923cb49..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/test_bookshelf_knowledge_bases_operations.py +++ /dev/null @@ -1,22 +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. -# -------------------------------------------------------------------------- -import pytest -from devtools_testutils import recorded_by_proxy -from testpreparer import BookshelfClientTestBase, BookshelfPreparer - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestBookshelfKnowledgeBasesOperations(BookshelfClientTestBase): - @BookshelfPreparer() - @recorded_by_proxy - def test_knowledge_bases_list(self, bookshelf_endpoint): - client = self.create_client(endpoint=bookshelf_endpoint) - response = client.knowledge_bases.list() - result = [r for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/test_bookshelf_knowledge_bases_operations_async.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/test_bookshelf_knowledge_bases_operations_async.py deleted file mode 100644 index 1dc6360d2d8f..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/test_bookshelf_knowledge_bases_operations_async.py +++ /dev/null @@ -1,23 +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. -# -------------------------------------------------------------------------- -import pytest -from devtools_testutils.aio import recorded_by_proxy_async -from testpreparer import BookshelfPreparer -from testpreparer_async import BookshelfClientTestBaseAsync - - -@pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestBookshelfKnowledgeBasesOperationsAsync(BookshelfClientTestBaseAsync): - @BookshelfPreparer() - @recorded_by_proxy_async - async def test_knowledge_bases_list(self, bookshelf_endpoint): - client = self.create_async_client(endpoint=bookshelf_endpoint) - response = client.knowledge_bases.list() - result = [r async for r in response] - # please add some check logic here by yourself - # ... diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/testpreparer_async.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/testpreparer_async.py deleted file mode 100644 index 6c615610688f..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/testpreparer_async.py +++ /dev/null @@ -1,20 +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 azure.ai.discovery.aio import BookshelfClient -from devtools_testutils import AzureRecordedTestCase - - -class BookshelfClientTestBaseAsync(AzureRecordedTestCase): - - def create_async_client(self, endpoint): - credential = self.get_credential(BookshelfClient, is_async=True) - return self.create_client_from_credential( - BookshelfClient, - credential=credential, - endpoint=endpoint, - ) diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/pyproject.toml b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/pyproject.toml deleted file mode 100644 index f843669f0665..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/pyproject.toml +++ /dev/null @@ -1,61 +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. -# -------------------------------------------------------------------------- - -[build-system] -requires = ["setuptools>=77.0.3", "wheel"] -build-backend = "setuptools.build_meta" - -[project] -name = "azure-ai-discovery" -authors = [ - { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, -] -description = "Microsoft Corporation Azure Ai Discovery Client Library for Python" -license = "MIT" -classifiers = [ - "Development Status :: 4 - Beta", - "Programming Language :: Python", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", -] -requires-python = ">=3.9" -keywords = ["azure", "azure sdk"] - -dependencies = [ - "isodate>=0.6.1", - "azure-core>=1.37.0", - "typing-extensions>=4.6.0", -] -dynamic = [ -"version", "readme" -] - -[project.urls] -repository = "https://github.com/Azure/azure-sdk-for-python" - -[tool.setuptools.dynamic] -version = {attr = "azure.ai.discovery._version.VERSION"} -readme = {file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown"} - -[tool.setuptools.packages.find] -exclude = [ - "tests*", - "generated_tests*", - "samples*", - "generated_samples*", - "doc*", - "azure", - "azure.ai", -] - -[tool.setuptools.package-data] -pytyped = ["py.typed"] diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/tsp-location.yaml b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/tsp-location.yaml deleted file mode 100644 index aec67413bf0c..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/tsp-location.yaml +++ /dev/null @@ -1,3 +0,0 @@ -directory: specification/discovery/Discovery.Bookshelf -commit: df74858bfda6128d16c98265db2a6f42e89b20ff -repo: Azure/azure-rest-api-specs diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_client.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_client.py similarity index 53% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_client.py rename to sdk/discovery/azure-ai-discovery/azure/ai/discovery/_client.py index 3113f7adb190..1095e4ae7a36 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_client.py +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_client.py @@ -7,16 +7,27 @@ # -------------------------------------------------------------------------- from copy import deepcopy +import sys from typing import Any, TYPE_CHECKING -from typing_extensions import Self from azure.core import PipelineClient from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse -from ._configuration import WorkspaceClientConfiguration +from ._configuration import BookshelfClientConfiguration, WorkspaceClientConfiguration from ._utils.serialization import Deserializer, Serializer -from .operations import ConversationsOperations, InvestigationsOperations, TasksOperations, ToolsOperations +from .operations import ( + ConversationsOperations, + InvestigationsOperations, + KnowledgeBasesOperations, + TasksOperations, + ToolsOperations, +) + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore if TYPE_CHECKING: from azure.core.credentials import TokenCredential @@ -38,9 +49,9 @@ class WorkspaceClient: :type endpoint: str :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials.TokenCredential - :keyword api_version: The API version to use for this operation. Known values are - "2026-02-01-preview" and None. Default value is "2026-02-01-preview". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: The API version to use for this operation. Known values are "2026-06-01" + and None. Default value is None. If not set, the operation's default API version will be used. + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. @@ -112,3 +123,86 @@ def __enter__(self) -> Self: def __exit__(self, *exc_details: Any) -> None: self._client.__exit__(*exc_details) + + +class BookshelfClient: + """BookshelfClient. + + :ivar knowledge_bases: KnowledgeBasesOperations operations + :vartype knowledge_bases: azure.ai.discovery.operations.KnowledgeBasesOperations + :param endpoint: Supported Microsoft Bookshelf Services endpoints (protocol and hostname, for + example: https://{bookshelfName}.discovery.azure.com). Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Known values are "2026-06-01" + and None. Default value is None. If not set, the operation's default API version will be used. + Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: + _endpoint = "{endpoint}" + self._config = BookshelfClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.knowledge_bases = KnowledgeBasesOperations(self._client, self._config, self._serialize, self._deserialize) + + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_configuration.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_configuration.py similarity index 50% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_configuration.py rename to sdk/discovery/azure-ai-discovery/azure/ai/discovery/_configuration.py index 30af4a539e70..795b64f3bfde 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_configuration.py +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_configuration.py @@ -27,14 +27,63 @@ class WorkspaceClientConfiguration: # pylint: disable=too-many-instance-attribu :type endpoint: str :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials.TokenCredential - :keyword api_version: The API version to use for this operation. Known values are - "2026-02-01-preview" and None. Default value is "2026-02-01-preview". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: The API version to use for this operation. Known values are "2026-06-01" + and None. Default value is None. If not set, the operation's default API version will be used. + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2026-02-01-preview") + api_version: str = kwargs.pop("api_version", "2026-06-01") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://discovery.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "ai-discovery/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) + + +class BookshelfClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for BookshelfClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Supported Microsoft Bookshelf Services endpoints (protocol and hostname, for + example: https://{bookshelfName}.discovery.azure.com). Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials.TokenCredential + :keyword api_version: The API version to use for this operation. Known values are "2026-06-01" + and None. Default value is None. If not set, the operation's default API version will be used. + Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2026-06-01") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_patch.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_patch.py similarity index 54% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_patch.py rename to sdk/discovery/azure-ai-discovery/azure/ai/discovery/_patch.py index bf4c7782ecc9..1fecda03b1fe 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_patch.py +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_patch.py @@ -7,24 +7,51 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + from typing import Any, Optional, TYPE_CHECKING from ._client import BookshelfClient as _GeneratedBookshelfClient +from ._client import WorkspaceClient as _GeneratedWorkspaceClient if TYPE_CHECKING: from azure.core.credentials import TokenCredential from azure.core.pipeline.transport import HttpTransport +class WorkspaceClient(_GeneratedWorkspaceClient): + """WorkspaceClient with an explicit ``transport`` keyword-only argument. + + See https://azure.github.io/azure-sdk/python_design.html#python-client-constructor-transport-argument + + :keyword api_version: The API version to use for this operation. Known values are "2026-06-01". + Overriding the default may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + endpoint: str, + credential: "TokenCredential", + *, + api_version: Optional[str] = None, + transport: Optional["HttpTransport"] = None, + **kwargs: Any, + ) -> None: + if api_version is not None: + kwargs["api_version"] = api_version + if transport is not None: + kwargs["transport"] = transport + super().__init__(endpoint=endpoint, credential=credential, **kwargs) + + class BookshelfClient(_GeneratedBookshelfClient): - """BookshelfClient with explicit ``transport`` keyword-only argument. + """BookshelfClient with an explicit ``transport`` keyword-only argument. See https://azure.github.io/azure-sdk/python_design.html#python-client-constructor-transport-argument - :ivar knowledge_bases: KnowledgeBasesOperations operations - :vartype knowledge_bases: azure.ai.discovery.operations.KnowledgeBasesOperations - :ivar knowledge_base_versions: KnowledgeBaseVersionsOperations operations - :vartype knowledge_base_versions: azure.ai.discovery.operations.KnowledgeBaseVersionsOperations + :keyword api_version: The API version to use for this operation. Known values are "2026-06-01". + Overriding the default may result in unsupported behavior. + :paramtype api_version: str """ def __init__( @@ -36,22 +63,6 @@ def __init__( transport: Optional["HttpTransport"] = None, **kwargs: Any, ) -> None: - """Create a new ``BookshelfClient``. - - :param endpoint: The Discovery service endpoint, in the form - ``https://.services.ai.azure.com``. Required. - :type endpoint: str - :param credential: Credential used to authenticate requests to the service. - Required. - :type credential: ~azure.core.credentials.TokenCredential - :keyword api_version: The API version to use for the request. Default value - is the latest service version supported by this client. Note that - overriding this default value may result in unsupported behavior. - :paramtype api_version: str - :keyword transport: The HTTP transport to use. If not specified, the default - ``azure-core`` transport (``RequestsTransport``) is used. - :paramtype transport: ~azure.core.pipeline.transport.HttpTransport - """ if api_version is not None: kwargs["api_version"] = api_version if transport is not None: @@ -59,7 +70,7 @@ def __init__( super().__init__(endpoint=endpoint, credential=credential, **kwargs) -__all__: list[str] = ["BookshelfClient"] +__all__: list[str] = ["WorkspaceClient", "BookshelfClient"] def patch_sdk(): diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_utils/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_utils/__init__.py similarity index 100% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_utils/__init__.py rename to sdk/discovery/azure-ai-discovery/azure/ai/discovery/_utils/__init__.py diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_utils/model_base.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_utils/model_base.py similarity index 70% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_utils/model_base.py rename to sdk/discovery/azure-ai-discovery/azure/ai/discovery/_utils/model_base.py index 7b7f8ba67b53..0f2c5bdfe70f 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_utils/model_base.py +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_utils/model_base.py @@ -23,14 +23,19 @@ 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 +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + _LOGGER = logging.getLogger(__name__) __all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] @@ -104,6 +109,29 @@ def _serialize_bytes(o, format: typing.Optional[str] = None) -> str: return encoded +def _serialize_duration(td: timedelta, format: typing.Optional[str] = None): + """Serialize a timedelta to its wire representation. + + For the ``seconds``/``milliseconds`` encodings the value is converted to a + numeric value, otherwise it falls back to an ISO 8601 duration string. + + :param timedelta td: The timedelta to serialize. + :param str format: The duration encoding format. + :rtype: int or float or str + :return: serialized duration + """ + seconds = td.total_seconds() + if format == "duration-seconds-int": + return int(seconds) + if format == "duration-seconds-float": + return seconds + if format == "duration-milliseconds-int": + return int(seconds * 1000) + if format == "duration-milliseconds-float": + return seconds * 1000 + return _timedelta_as_isostr(td) + + def _serialize_datetime(o, format: typing.Optional[str] = None): if hasattr(o, "year") and hasattr(o, "hour"): if format == "rfc7231": @@ -296,6 +324,12 @@ def _deserialize_duration(attr): return isodate.parse_duration(attr) +def _deserialize_duration_numeric(attr, unit): + if isinstance(attr, timedelta): + return attr + return timedelta(**{unit: float(attr)}) + + def _deserialize_decimal(attr): if isinstance(attr, decimal.Decimal): return attr @@ -325,6 +359,10 @@ def _deserialize_int_as_str(attr): "unix-timestamp": _deserialize_datetime_unix_timestamp, "base64": _deserialize_bytes, "base64url": _deserialize_bytes_base64, + "duration-seconds-int": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-seconds-float": functools.partial(_deserialize_duration_numeric, unit="seconds"), + "duration-milliseconds-int": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), + "duration-milliseconds-float": functools.partial(_deserialize_duration_numeric, unit="milliseconds"), } @@ -420,21 +458,21 @@ def __ne__(self, other: typing.Any) -> bool: def keys(self) -> typing.KeysView[str]: """ - :returns: a set-like object providing a view on D's keys + :returns: a set-like object providing a view on the mapping'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 + :returns: an object providing a view on the mapping'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 + :returns: a set-like object providing a view on the mapping's items :rtype: ~typing.ItemsView """ return self._data.items() @@ -444,7 +482,7 @@ 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. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ try: @@ -479,19 +517,19 @@ 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. + :raises KeyError: if the dictionary is empty. """ return self._data.popitem() def clear(self) -> None: """ - Remove all items from D. + Remove all items from the dictionary. """ 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. + Update the dictionary from a mapping or an iterable of key-value pairs. :param any args: Either a mapping object or an iterable of key-value pairs. """ self._data.update(*args, **kwargs) @@ -504,10 +542,11 @@ def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint 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 + Return the value for key if key is in the dictionary; otherwise set the key to + default and return default. :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. + :returns: The value for key if key is in the dictionary, else default. :rtype: any """ if default is _UNSET: @@ -559,7 +598,7 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m pass # Last, try datetime.timedelta try: - return _timedelta_as_isostr(o) + return _serialize_duration(o, format) except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass @@ -585,6 +624,239 @@ def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typin return _serialize(value, rf._format) +# ============================================================================ +# Fast-path scalar deserializer functions for rest_field(deserializer=...) +# These are referenced from rest_field declarations to bypass the generic +# _deserialize -> _deserialize_with_callable chain. +# Only simple/primitive types — no models or container types. +# ============================================================================ + + +def _xml_deser_str(value): + if isinstance(value, ET.Element): + return value.text or "" + return str(value) if value is not None else None + + +def _xml_deser_int(value): + if isinstance(value, ET.Element): + return int(value.text) if value.text else None + return int(value) if value is not None else None + + +def _xml_deser_float(value): + if isinstance(value, ET.Element): + return float(value.text) if value.text else None + return float(value) if value is not None else None + + +def _xml_deser_bool(value): + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + if text in (True, False): + return text + return text.lower() == "true" + + +# pylint: disable=docstring-missing-param +def _xml_deser_bytes(value): + """Deserialize bytes from XML (base64).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes(text) + + +def _xml_deser_bytes_base64url(value): + """Deserialize bytes from XML (base64url).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_bytes_base64(text) + + +def _xml_deser_datetime(value): + """Deserialize a datetime from XML (ISO 8601 / rfc3339).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime(text) + + +def _xml_deser_datetime_rfc7231(value): + """Deserialize a datetime from XML (RFC7231 format).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_rfc7231(text) + + +def _xml_deser_datetime_unix_timestamp(value): + """Deserialize a datetime from XML (Unix timestamp).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_datetime_unix_timestamp(float(text)) + + +def _xml_deser_date(value): + """Deserialize a date from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_date(text) + + +def _xml_deser_time(value): + """Deserialize a time from XML (ISO 8601).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_time(text) + + +def _xml_deser_duration(value): + """Deserialize a timedelta from XML (ISO 8601 duration).""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_duration(text) + + +def _xml_deser_decimal(value): + """Deserialize a Decimal from XML.""" + if isinstance(value, ET.Element): + text = value.text + else: + text = value + if text is None: + return None + return _deserialize_decimal(text) + + +def _xml_deser_enum_or_str(enum_cls, value): + """Deserialize a Union[EnumType, str] from XML.""" + text = value.text if isinstance(value, ET.Element) else value + if text is None: + return None + try: + return enum_cls(text) + except ValueError: + return text + + +def _extract_xml_model_type(rf_type): + """Extract the concrete Model class from a resolved rf._type partial chain. + + Unwraps ``Optional[Model]`` and ``_deserialize_model(Model, ...)`` + wrappers. Only handles Model and Optional[Model] — other composite + types (List, Dict, Union, etc.) return None and fall through to the + generic ``_deserialize`` path at runtime. + """ + if rf_type is None: + return None + if isinstance(rf_type, type) and _is_model(rf_type): + return rf_type + if not isinstance(rf_type, functools.partial): + return None + func = rf_type.func + args = rf_type.args + if func is _deserialize_with_optional and args: + return _extract_xml_model_type(args[0]) + if func is _deserialize_model and args: + cls = args[0] + return cls if isinstance(cls, type) and _is_model(cls) else None + return None + + +def _build_xml_field_plan( # pylint: disable=docstring-missing-return, docstring-missing-rtype, unused-variable + cls, attr_to_rest_field: dict +) -> list: + """Build a precomputed XML field plan for fast _init_from_xml iteration. + + Called once per model class in __new__. Returns a list of tuples: + (rest_name, xml_name, kind, deser, rf_type, is_optional, items_name) + + kind: 0=wrapped, 1=attribute, 2=unwrapped, 3=text + + For Model and Optional[Model] fields that lack a scalar + ``_deserializer``, this function precomputes the Model class as the + deserializer so ``_init_from_xml`` can call ``ModelClass(element)`` + directly instead of going through the expensive + ``_get_deserialize_callable_from_annotation`` chain at runtime. + """ + model_meta = getattr(cls, "_xml", {}) + model_ns = model_meta.get("ns") or model_meta.get("namespace") + plan = [] + + for rf in attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + deser = rf._deserializer + + 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 + + is_optional = rf._is_optional + + # For Model / Optional[Model] fields without a scalar deserializer, + # precompute the Model class as the deserializer. + if deser is None and rf._type is not None: + model_cls = _extract_xml_model_type(rf._type) + if model_cls is not None: + deser = model_cls + + if prop_meta.get("attribute", False): + plan.append((rf._rest_name, xml_name, 1, deser, rf._type, is_optional, None)) + elif prop_meta.get("unwrapped", False): + items_name = prop_meta.get("itemsName") + if items_name: + items_ns = prop_meta.get("itemsNs") + if items_ns is not None: + xml_ns = items_ns + if xml_ns: + items_name = "{" + xml_ns + "}" + items_name + else: + items_name = xml_name + plan.append((rf._rest_name, xml_name, 2, deser, rf._type, is_optional, items_name)) + elif prop_meta.get("text", False): + plan.append((rf._rest_name, xml_name, 3, deser, rf._type, is_optional, None)) + else: + plan.append((rf._rest_name, xml_name, 0, deser, rf._type, is_optional, None)) + + return plan + + +# pylint: enable=docstring-missing-param class Model(_MyMutableMapping): _is_model = True # label whether current class's _attr_to_rest_field has been calculated @@ -595,62 +867,10 @@ 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: # pylint: disable=too-many-nested-blocks + dict_to_pass: dict[str, typing.Any] = {} + if args: if isinstance(args[0], ET.Element): - existed_attr_keys = [] - model_meta = getattr(self, "_xml", {}) - - 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 = prop_meta.get("ns", model_meta.get("ns", None)) - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - - # attribute - if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) - continue - - # unwrapped element is array - if prop_meta.get("unwrapped", False): - # unwrapped array could either use prop items meta/prop meta - if prop_meta.get("itemsName"): - xml_name = prop_meta.get("itemsName") - xml_ns = prop_meta.get("itemNs") - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - items = args[0].findall(xml_name) # pyright: ignore - if len(items) > 0: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) - elif not rf._is_optional: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = [] - continue - - # text element is primitive type - if prop_meta.get("text", False): - if args[0].text is not None: - dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) - continue - - # wrapped element could be normal property or array, it should only have one element - item = args[0].find(xml_name) - if item is not None: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) - - # rest thing is additional properties - for e in args[0]: - if e.tag not in existed_attr_keys: - dict_to_pass[e.tag] = _convert_element(e) + 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()} @@ -667,8 +887,117 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: if v is not None } ) + # Apply client default values for fields the caller didn't set so that + # defaults are part of `_data` and therefore included during serialization. + for rf in self._attr_to_rest_field.values(): + if rf._default is _UNSET: + continue + if rf._rest_name in dict_to_pass: + continue + dict_to_pass[rf._rest_name] = _create_value(rf, rf._default) super().__init__(dict_to_pass) + def _init_from_xml( # pylint: disable=too-many-branches, too-many-statements + 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] = {} + existed_attr_keys: list[str] = [] + + field_plan = getattr(self, "_xml_field_plan", None) + if field_plan: + for rest_name, xml_name, kind, deser, rf_type, is_optional, items_name in field_plan: + if kind == 0: # wrapped element (most common) + item = element.find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(item) + else: + result[rest_name] = _deserialize(rf_type, item) + elif kind == 1: # attribute + attr_val = element.get(xml_name) + if attr_val is not None: + existed_attr_keys.append(xml_name) + if deser: + result[rest_name] = deser(attr_val) + else: + result[rest_name] = attr_val + elif kind == 2: # unwrapped array + items = element.findall(items_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(items_name) + if deser: + result[rest_name] = deser(items) + else: + result[rest_name] = _deserialize(rf_type, items) + elif not is_optional: + existed_attr_keys.append(items_name) + result[rest_name] = [] + elif kind == 3: # text + if element.text is not None: + if deser: + result[rest_name] = deser(element.text) + else: + result[rest_name] = element.text + else: + model_meta = getattr(self, "_xml", {}) + 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): + _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 + 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__) @@ -693,6 +1022,9 @@ def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: 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()) + # Build XML field plan for fast _init_from_xml (only for XML models) + if getattr(cls, "_xml", None): + cls._xml_field_plan = _build_xml_field_plan(cls, attr_to_rest_field) cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") return super().__new__(cls) @@ -721,7 +1053,7 @@ def _deserialize(cls, data, exist_discriminators): model_meta = getattr(cls, "_xml", {}) prop_meta = getattr(discriminator, "_xml", {}) xml_name = prop_meta.get("name", discriminator._rest_name) - xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + xml_ns = _resolve_xml_ns(prop_meta, model_meta) if xml_ns: xml_name = "{" + xml_ns + "}" + xml_name @@ -1067,6 +1399,7 @@ def __init__( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, ): self._type = type self._rest_name_input = name @@ -1079,6 +1412,7 @@ def __init__( self._format = format self._is_multipart_file_input = is_multipart_file_input self._xml = xml if xml is not None else {} + self._deserializer = deserializer @property def _class_type(self) -> typing.Any: @@ -1098,7 +1432,10 @@ 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) + item = obj._data.get(self._rest_name, _UNSET) + if item is _UNSET: + # Field not set by user; return the client default if one exists, otherwise None + return self._default if self._default is not _UNSET else None if item is None: return item if self._is_model: @@ -1111,7 +1448,11 @@ def __get__(self, obj: Model, type=None): # pylint: disable=redefined-builtin # 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) + # Fast path: use _deserializer directly (avoids _serialize/_deserialize chain) + if self._deserializer: + deserialized = self._deserializer(item) + else: + 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 @@ -1157,6 +1498,7 @@ def rest_field( format: typing.Optional[str] = None, is_multipart_file_input: bool = False, xml: typing.Optional[dict[str, typing.Any]] = None, + deserializer: typing.Optional[typing.Callable] = None, ) -> typing.Any: return _RestField( name=name, @@ -1166,6 +1508,7 @@ def rest_field( format=format, is_multipart_file_input=is_multipart_file_input, xml=xml, + deserializer=deserializer, ) @@ -1190,6 +1533,56 @@ def serialize_xml(model: Model, exclude_readonly: bool = False) -> 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, @@ -1201,10 +1594,16 @@ def _get_element( # 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( - model_meta.get("name", o.__class__.__name__), + element_name, model_meta.get("prefix"), - model_meta.get("ns"), + _model_ns, ) readonly_props = [] @@ -1226,7 +1625,9 @@ def _get_element( # additional properties will not have rest field, use the wire name as xml name prop_meta = {"name": k} - # if no ns for prop, use model's + # 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") @@ -1238,12 +1639,7 @@ def _get_element( # text could only set on primitive type wrapped_element.text = _get_primitive_type_value(v) elif prop_meta.get("attribute", False): - xml_name = prop_meta.get("name", k) - if prop_meta.get("ns"): - ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore - xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore - # attribute should be primitive type - wrapped_element.set(xml_name, _get_primitive_type_value(v)) + _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)) @@ -1252,6 +1648,7 @@ def _get_element( 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( @@ -1259,7 +1656,7 @@ def _get_element( exclude_readonly, { "name": k, - "ns": parent_meta.get("ns") if parent_meta else None, + "ns": _dict_ns, "prefix": parent_meta.get("prefix") if parent_meta else None, }, ) @@ -1268,13 +1665,16 @@ def _get_element( # 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": parent_meta.get("itemsNs", parent_meta.get("ns")), + "ns": _items_ns, }, ) @@ -1286,8 +1686,9 @@ def _get_wrapped_element( 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.get("ns") if meta else None + 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)) @@ -1308,11 +1709,29 @@ def _get_primitive_type_value(v) -> str: 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: - ET.register_namespace(prefix, ns) + _safe_register_namespace(prefix, ns) if ns: return ET.Element("{" + ns + "}" + tag) return ET.Element(tag) @@ -1323,6 +1742,8 @@ def _deserialize_xml( value: str, ) -> typing.Any: element = ET.fromstring(value) # nosec + if _is_model(deserializer): + return deserializer._deserialize(element, []) return _deserialize(deserializer, element) diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_utils/serialization.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_utils/serialization.py similarity index 93% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_utils/serialization.py rename to sdk/discovery/azure-ai-discovery/azure/ai/discovery/_utils/serialization.py index 81ec1de5922b..75906e2eb77f 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_utils/serialization.py +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_utils/serialization.py @@ -39,11 +39,15 @@ 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 +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self + _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") JSON = MutableMapping[str, Any] @@ -516,6 +520,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Serializer.serialize_rfc, "unix-time": Serializer.serialize_unix, "duration": Serializer.serialize_duration, + "duration-seconds-int": Serializer.serialize_duration_seconds_int, + "duration-seconds-float": Serializer.serialize_duration_seconds_float, + "duration-milliseconds-int": Serializer.serialize_duration_milliseconds_int, + "duration-milliseconds-float": Serializer.serialize_duration_milliseconds_float, "date": Serializer.serialize_date, "time": Serializer.serialize_time, "decimal": Serializer.serialize_decimal, @@ -1105,6 +1113,61 @@ def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) + @staticmethod + def _serialize_duration_numeric(attr, scale, as_int): + """Serialize a TimeDelta into a numeric value scaled to the wire unit. + + :param TimeDelta attr: Object to be serialized. + :param int scale: Multiplier applied to total seconds (1 for seconds, 1000 for milliseconds). + :param bool as_int: Whether to truncate the result to an int. + :rtype: int or float + :return: serialized duration + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + value = attr.total_seconds() * scale if isinstance(attr, datetime.timedelta) else attr + return int(value) if as_int else float(value) + + @staticmethod + def serialize_duration_seconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, True) + + @staticmethod + def serialize_duration_seconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of seconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1, False) + + @staticmethod + def serialize_duration_milliseconds_int(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into an integer number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: int + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, True) + + @staticmethod + def serialize_duration_milliseconds_float(attr, **kwargs): # pylint: disable=unused-argument + """Serialize TimeDelta object into a floating point number of milliseconds. + + :param TimeDelta attr: Object to be serialized. + :rtype: float + :return: serialized duration + """ + return Serializer._serialize_duration_numeric(attr, 1000, False) + @staticmethod def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. @@ -1377,6 +1440,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: "rfc-1123": Deserializer.deserialize_rfc, "unix-time": Deserializer.deserialize_unix, "duration": Deserializer.deserialize_duration, + "duration-seconds-int": Deserializer.deserialize_duration_seconds, + "duration-seconds-float": Deserializer.deserialize_duration_seconds, + "duration-milliseconds-int": Deserializer.deserialize_duration_milliseconds, + "duration-milliseconds-float": Deserializer.deserialize_duration_milliseconds, "date": Deserializer.deserialize_date, "time": Deserializer.deserialize_time, "decimal": Deserializer.deserialize_decimal, @@ -1389,6 +1456,10 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: } self.deserialize_expected_types = { "duration": (isodate.Duration, datetime.timedelta), + "duration-seconds-int": (isodate.Duration, datetime.timedelta), + "duration-seconds-float": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-int": (isodate.Duration, datetime.timedelta), + "duration-milliseconds-float": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } self.dependencies: dict[str, type] = dict(classes) if classes else {} @@ -1401,7 +1472,7 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: # Otherwise, result are unexpected self.additional_properties_detection = True - def __call__(self, target_obj, response_data, content_type=None): + def __call__(self, target_obj, response_data, content_type=None): # pylint: disable=too-many-return-statements """Call the deserializer to process a REST response. :param str target_obj: Target data type to deserialize to. @@ -1411,6 +1482,27 @@ def __call__(self, target_obj, response_data, content_type=None): :return: Deserialized object. :rtype: object """ + # Fast path for header deserialization: response_data is a plain str or None + # and target_obj is a simple scalar type. This avoids the expensive + # _unpack_content → _deserialize → _classify_target → deserialize_data chain. + if response_data is None: + return None + if target_obj == "str" and isinstance(response_data, str): + return response_data + if isinstance(response_data, str): + if target_obj == "int": + return int(response_data) + if target_obj == "bool": + if response_data in ("true", "1", "True"): + return True + if response_data in ("false", "0", "False"): + return False + return bool(response_data) + if target_obj == "rfc-1123": + return Deserializer.deserialize_rfc(response_data) + if target_obj == "bytearray": + return Deserializer.deserialize_bytearray(response_data) + data = self._unpack_content(response_data, content_type) return self._deserialize(target_obj, data) @@ -1929,6 +2021,48 @@ def deserialize_duration(attr): raise DeserializationError(msg) from err return duration + @staticmethod + def _deserialize_duration_numeric(attr, unit): + """Deserialize a numeric duration value into a TimeDelta object. + + :param float attr: response value to be deserialized. + :param str unit: The wire unit, used as the ``timedelta`` keyword + (``"seconds"`` or ``"milliseconds"``). + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = datetime.timedelta(**{unit: float(attr)}) # type: ignore + except (ValueError, OverflowError, TypeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + return duration + + @staticmethod + def deserialize_duration_seconds(attr): + """Deserialize a numeric number of seconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "seconds") + + @staticmethod + def deserialize_duration_milliseconds(attr): + """Deserialize a numeric number of milliseconds into a TimeDelta object. + + :param float attr: response value to be deserialized. + :return: Deserialized duration + :rtype: TimeDelta + :raises DeserializationError: if value is invalid. + """ + return Deserializer._deserialize_duration_numeric(attr, "milliseconds") + @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_validation.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_validation.py similarity index 100% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/_validation.py rename to sdk/discovery/azure-ai-discovery/azure/ai/discovery/_validation.py diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_version.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_version.py index f1a7251e3b94..96b1c6687b61 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_version.py +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_version.py @@ -4,4 +4,4 @@ # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------- -VERSION = "1.0.0b1" +VERSION = "1.0.0" diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/CHANGELOG.md b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/CHANGELOG.md deleted file mode 100644 index b957b2575b48..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/CHANGELOG.md +++ /dev/null @@ -1,7 +0,0 @@ -# Release History - -## 1.0.0b1 (1970-01-01) - -### Other Changes - - - Initial version \ No newline at end of file diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/LICENSE b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/LICENSE deleted file mode 100644 index 63447fd8bbbf..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) Microsoft Corporation. - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/MANIFEST.in b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/MANIFEST.in deleted file mode 100644 index 64845ff3f4fc..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/MANIFEST.in +++ /dev/null @@ -1,7 +0,0 @@ -include *.md -include LICENSE -include azure/ai/discovery/py.typed -recursive-include tests *.py -recursive-include samples *.py *.md -include azure/__init__.py -include azure/ai/__init__.py diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/__init__.py deleted file mode 100644 index 32abe24fce30..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -# Re-export WorkspaceClient from the generated sub-client -from .azure.ai.discovery import WorkspaceClient # type: ignore - -__all__ = ["WorkspaceClient"] diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/_metadata.json b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/_metadata.json deleted file mode 100644 index 3c507ec1b8f6..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/_metadata.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "apiVersion": "2026-02-01-preview", - "apiVersions": { - "Microsoft.Discovery.Workspace": "2026-02-01-preview" - } -} \ No newline at end of file diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/__init__.py deleted file mode 100644 index d55ccad1f573..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/__init__.py deleted file mode 100644 index d55ccad1f573..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/__init__.py +++ /dev/null @@ -1 +0,0 @@ -__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/__init__.py deleted file mode 100644 index 922d8ab09483..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/__init__.py +++ /dev/null @@ -1,32 +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 ._client import WorkspaceClient # type: ignore -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "WorkspaceClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_patch.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_patch.py deleted file mode 100644 index b3673520aa9c..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_patch.py +++ /dev/null @@ -1,75 +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 -""" -from typing import Any, Optional, TYPE_CHECKING - -from ._client import WorkspaceClient as _GeneratedWorkspaceClient - -if TYPE_CHECKING: - from azure.core.credentials import TokenCredential - from azure.core.pipeline.transport import HttpTransport - - -class WorkspaceClient(_GeneratedWorkspaceClient): - """WorkspaceClient with explicit ``transport`` keyword-only argument. - - See https://azure.github.io/azure-sdk/python_design.html#python-client-constructor-transport-argument - - :ivar investigations: InvestigationsOperations operations - :vartype investigations: azure.ai.discovery.operations.InvestigationsOperations - :ivar conversations: ConversationsOperations operations - :vartype conversations: azure.ai.discovery.operations.ConversationsOperations - :ivar tools: ToolsOperations operations - :vartype tools: azure.ai.discovery.operations.ToolsOperations - :ivar tasks: TasksOperations operations - :vartype tasks: azure.ai.discovery.operations.TasksOperations - """ - - def __init__( - self, - endpoint: str, - credential: "TokenCredential", - *, - api_version: Optional[str] = None, - transport: Optional["HttpTransport"] = None, - **kwargs: Any, - ) -> None: - """Create a new ``WorkspaceClient``. - - :param endpoint: The Discovery service endpoint, in the form - ``https://.services.ai.azure.com``. Required. - :type endpoint: str - :param credential: Credential used to authenticate requests to the service. - Required. - :type credential: ~azure.core.credentials.TokenCredential - :keyword api_version: The API version to use for the request. Default value - is the latest service version supported by this client. Note that - overriding this default value may result in unsupported behavior. - :paramtype api_version: str - :keyword transport: The HTTP transport to use. If not specified, the default - ``azure-core`` transport (``RequestsTransport``) is used. - :paramtype transport: ~azure.core.pipeline.transport.HttpTransport - """ - if api_version is not None: - kwargs["api_version"] = api_version - if transport is not None: - kwargs["transport"] = transport - super().__init__(endpoint=endpoint, credential=credential, **kwargs) - - -__all__: list[str] = ["WorkspaceClient"] - - -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/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_utils/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_utils/__init__.py deleted file mode 100644 index 8026245c2abc..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_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/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_utils/model_base.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_utils/model_base.py deleted file mode 100644 index 7b7f8ba67b53..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_utils/model_base.py +++ /dev/null @@ -1,1350 +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: # pylint: disable=too-many-nested-blocks - if isinstance(args[0], ET.Element): - existed_attr_keys = [] - model_meta = getattr(self, "_xml", {}) - - 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 = prop_meta.get("ns", model_meta.get("ns", None)) - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - - # attribute - if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) - continue - - # unwrapped element is array - if prop_meta.get("unwrapped", False): - # unwrapped array could either use prop items meta/prop meta - if prop_meta.get("itemsName"): - xml_name = prop_meta.get("itemsName") - xml_ns = prop_meta.get("itemNs") - if xml_ns: - xml_name = "{" + xml_ns + "}" + xml_name - items = args[0].findall(xml_name) # pyright: ignore - if len(items) > 0: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) - elif not rf._is_optional: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = [] - continue - - # text element is primitive type - if prop_meta.get("text", False): - if args[0].text is not None: - dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) - continue - - # wrapped element could be normal property or array, it should only have one element - item = args[0].find(xml_name) - if item is not None: - existed_attr_keys.append(xml_name) - dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) - - # rest thing is additional properties - for e in args[0]: - if e.tag not in existed_attr_keys: - dict_to_pass[e.tag] = _convert_element(e) - 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 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._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_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 = prop_meta.get("ns", model_meta.get("ns", None)) - 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) - - 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, - ): - 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 {} - - @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, -) -> typing.Any: - return _RestField( - name=name, - type=type, - visibility=visibility, - default=default, - format=format, - is_multipart_file_input=is_multipart_file_input, - xml=xml, - ) - - -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_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: - wrapped_element = _create_xml_element( - model_meta.get("name", o.__class__.__name__), - model_meta.get("prefix"), - model_meta.get("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} - - # if no ns for prop, use model's - 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): - xml_name = prop_meta.get("name", k) - if prop_meta.get("ns"): - ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore - xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore - # attribute should be primitive type - wrapped_element.set(xml_name, _get_primitive_type_value(v)) - 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 = [] - for k, v in o.items(): - result.append( - _get_wrapped_element( - v, - exclude_readonly, - { - "name": k, - "ns": parent_meta.get("ns") if parent_meta else None, - "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: - 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": parent_meta.get("itemsNs", parent_meta.get("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: - wrapped_element = _create_xml_element( - meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None - ) - 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 _create_xml_element( - tag: typing.Any, prefix: typing.Optional[str] = None, ns: typing.Optional[str] = None -) -> ET.Element: - if prefix and ns: - ET.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/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_utils/serialization.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_utils/serialization.py deleted file mode 100644 index 81ec1de5922b..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_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/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_validation.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_validation.py deleted file mode 100644 index f5af3a4eb8a2..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_validation.py +++ /dev/null @@ -1,66 +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. -# -------------------------------------------------------------------------- -import functools - - -def api_version_validation(**kwargs): - params_added_on = kwargs.pop("params_added_on", {}) - method_added_on = kwargs.pop("method_added_on", "") - api_versions_list = kwargs.pop("api_versions_list", []) - - def _index_with_default(value: str, default: int = -1) -> int: - """Get the index of value in lst, or return default if not found. - - :param value: The value to search for in the api_versions_list. - :type value: str - :param default: The default value to return if the value is not found. - :type default: int - :return: The index of the value in the list, or the default value if not found. - :rtype: int - """ - try: - return api_versions_list.index(value) - except ValueError: - return default - - def decorator(func): - @functools.wraps(func) - def wrapper(*args, **kwargs): - try: - # this assumes the client has an _api_version attribute - client = args[0] - client_api_version = client._config.api_version # pylint: disable=protected-access - except AttributeError: - return func(*args, **kwargs) - - if _index_with_default(method_added_on) > _index_with_default(client_api_version): - raise ValueError( - f"'{func.__name__}' is not available in API version " - f"{client_api_version}. Pass service API version {method_added_on} or newer to your client." - ) - - unsupported = { - parameter: api_version - for api_version, parameters in params_added_on.items() - for parameter in parameters - if parameter in kwargs and _index_with_default(api_version) > _index_with_default(client_api_version) - } - if unsupported: - raise ValueError( - "".join( - [ - f"'{param}' is not available in API version {client_api_version}. " - f"Use service API version {version} or newer.\n" - for param, version in unsupported.items() - ] - ) - ) - return func(*args, **kwargs) - - return wrapper - - return decorator diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_version.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_version.py deleted file mode 100644 index be71c81bd282..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/_version.py +++ /dev/null @@ -1,9 +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. -# -------------------------------------------------------------------------- - -VERSION = "1.0.0b1" diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/__init__.py deleted file mode 100644 index ceacbbbbb3ce..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/__init__.py +++ /dev/null @@ -1,29 +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 ._client import WorkspaceClient # type: ignore - -try: - from ._patch import __all__ as _patch_all - from ._patch import * -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [ - "WorkspaceClient", -] -__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore - -_patch_sdk() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/_configuration.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/_configuration.py deleted file mode 100644 index 0ba7a46d0ca8..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/_configuration.py +++ /dev/null @@ -1,65 +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 - -from azure.core.pipeline import policies - -from .._version import VERSION - -if TYPE_CHECKING: - from azure.core.credentials_async import AsyncTokenCredential - - -class WorkspaceClientConfiguration: # pylint: disable=too-many-instance-attributes - """Configuration for WorkspaceClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param endpoint: Supported Discovery Workspace Services endpoints (protocol and hostname, for - example: https://{workspaceName}.discovery.azure.com). Required. - :type endpoint: str - :param credential: Credential used to authenticate requests to the service. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: The API version to use for this operation. Known values are - "2026-02-01-preview" and None. Default value is "2026-02-01-preview". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2026-02-01-preview") - - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - - self.endpoint = endpoint - self.credential = credential - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://discovery.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "ai-discovery/{}".format(VERSION)) - self.polling_interval = kwargs.get("polling_interval", 30) - self._configure(**kwargs) - - def _configure(self, **kwargs: Any) -> None: - self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) - self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) - self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) - self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) - self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) - self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) - self.authentication_policy = kwargs.get("authentication_policy") - if self.credential and not self.authentication_policy: - self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/_patch.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/_patch.py deleted file mode 100644 index 94bf444c4091..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/_patch.py +++ /dev/null @@ -1,75 +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 -""" -from typing import Any, Optional, TYPE_CHECKING - -from ._client import WorkspaceClient as _GeneratedWorkspaceClient - -if TYPE_CHECKING: - from azure.core.credentials_async import AsyncTokenCredential - from azure.core.pipeline.transport import AsyncHttpTransport - - -class WorkspaceClient(_GeneratedWorkspaceClient): - """Async WorkspaceClient with explicit ``transport`` keyword-only argument. - - See https://azure.github.io/azure-sdk/python_design.html#python-client-constructor-transport-argument - - :ivar investigations: InvestigationsOperations operations - :vartype investigations: azure.ai.discovery.aio.operations.InvestigationsOperations - :ivar conversations: ConversationsOperations operations - :vartype conversations: azure.ai.discovery.aio.operations.ConversationsOperations - :ivar tools: ToolsOperations operations - :vartype tools: azure.ai.discovery.aio.operations.ToolsOperations - :ivar tasks: TasksOperations operations - :vartype tasks: azure.ai.discovery.aio.operations.TasksOperations - """ - - def __init__( - self, - endpoint: str, - credential: "AsyncTokenCredential", - *, - api_version: Optional[str] = None, - transport: Optional["AsyncHttpTransport"] = None, - **kwargs: Any, - ) -> None: - """Create a new asynchronous ``WorkspaceClient``. - - :param endpoint: The Discovery service endpoint, in the form - ``https://.services.ai.azure.com``. Required. - :type endpoint: str - :param credential: Credential used to authenticate requests to the service. - Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: The API version to use for the request. Default value - is the latest service version supported by this client. Note that - overriding this default value may result in unsupported behavior. - :paramtype api_version: str - :keyword transport: The async HTTP transport to use. If not specified, the - default ``azure-core`` async transport (``AioHttpTransport``) is used. - :paramtype transport: ~azure.core.pipeline.transport.AsyncHttpTransport - """ - if api_version is not None: - kwargs["api_version"] = api_version - if transport is not None: - kwargs["transport"] = transport - super().__init__(endpoint=endpoint, credential=credential, **kwargs) - - -__all__: list[str] = ["WorkspaceClient"] - - -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/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/operations/_patch.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/operations/_patch.py deleted file mode 100644 index 87676c65a8f0..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/operations/_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/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/models/_patch.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/models/_patch.py deleted file mode 100644 index 87676c65a8f0..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/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/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/operations/_patch.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/operations/_patch.py deleted file mode 100644 index 87676c65a8f0..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/operations/_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/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/py.typed b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/dev_requirements.txt b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/dev_requirements.txt deleted file mode 100644 index 0e53b6a72db5..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/dev_requirements.txt +++ /dev/null @@ -1,3 +0,0 @@ --e ../../../eng/tools/azure-sdk-tools -../../core/azure-core -aiohttp \ No newline at end of file diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/conversations_create_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/conversations_create_maximum_set_gen.py deleted file mode 100644 index 2eba08cc5d07..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/conversations_create_maximum_set_gen.py +++ /dev/null @@ -1,46 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python conversations_create_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.conversations.create( - body={ - "displayName": "epnykokjliolcibibw", - "investigationName": "dcaovanpmdfxmufcriqxbxndxob", - "projectName": "xmqmprmbzutvyprkjaipfchescb", - }, - project_name="str", - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Conversations_Create_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/conversations_delete_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/conversations_delete_maximum_set_gen.py deleted file mode 100644 index e6bcb32a6eb3..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/conversations_delete_maximum_set_gen.py +++ /dev/null @@ -1,40 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python conversations_delete_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - client.conversations.delete( - conversation_name="757991cbc8d7ba5a75", - ) - - -# x-ms-original-file: 2026-02-01-preview/Conversations_Delete_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/conversations_get_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/conversations_get_maximum_set_gen.py deleted file mode 100644 index efd8027699ca..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/conversations_get_maximum_set_gen.py +++ /dev/null @@ -1,41 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python conversations_get_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.conversations.get( - conversation_name="30646d5bd5684f4f23", - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Conversations_Get_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/conversations_list_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/conversations_list_maximum_set_gen.py deleted file mode 100644 index b9a6da14e6c1..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/conversations_list_maximum_set_gen.py +++ /dev/null @@ -1,39 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python conversations_list_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.conversations.list() - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Conversations_List_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/conversations_update_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/conversations_update_maximum_set_gen.py deleted file mode 100644 index d3d7be997621..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/conversations_update_maximum_set_gen.py +++ /dev/null @@ -1,46 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python conversations_update_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.conversations.update( - conversation_name="d5289e38a8e58959f6", - resource={ - "displayName": "ybmspkhivqubhusomhzvdroaqxh", - "investigationName": "vtgormvraqcudwgaxwg", - "projectName": "axqhafhpwssbxznhfdb", - }, - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Conversations_Update_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_create_or_replace_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_create_or_replace_maximum_set_gen.py deleted file mode 100644 index 81fbe8d8d769..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_create_or_replace_maximum_set_gen.py +++ /dev/null @@ -1,50 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python investigations_create_or_replace_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.investigations.create_or_replace( - project_name="cfbf81872054d0d9d2", - investigation_name="6ed772a45d42ef926f", - resource={ - "createdByType": "User", - "description": "uooqwtf", - "displayName": "ntzixeevitsbjwxmlbbbhs", - "lastModifiedByType": "User", - "status": "Created", - "tags": [{"key": "smfd", "value": "lfrfhd"}], - }, - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Investigations_CreateOrReplace_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_create_or_update_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_create_or_update_maximum_set_gen.py deleted file mode 100644 index 77e251ee8fec..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_create_or_update_maximum_set_gen.py +++ /dev/null @@ -1,47 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python investigations_create_or_update_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.investigations.create_or_update( - project_name="74d7a98a947cf364b6", - investigation_name="1e4f8497c72b116560", - resource={ - "description": "mmnwxgyi", - "displayName": "ddijamgvobmjay", - "tags": [{"key": "smfd", "value": "lfrfhd"}], - }, - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Investigations_CreateOrUpdate_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_delete_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_delete_maximum_set_gen.py deleted file mode 100644 index d8992a691f14..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_delete_maximum_set_gen.py +++ /dev/null @@ -1,42 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python investigations_delete_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.investigations.begin_delete( - project_name="9347970e6dd0377b6a", - investigation_name="356282394a90f5ab63", - ).result() - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Investigations_Delete_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_get_discovery_engine_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_get_discovery_engine_maximum_set_gen.py deleted file mode 100644 index ae16e5c24ef4..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_get_discovery_engine_maximum_set_gen.py +++ /dev/null @@ -1,42 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python investigations_get_discovery_engine_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.investigations.get_discovery_engine( - project_name="cbb93a24f737ca72fd", - investigation_name="5dd011f234eb370f21", - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Investigations_GetDiscoveryEngine_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_get_discovery_engine_memory_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_get_discovery_engine_memory_maximum_set_gen.py deleted file mode 100644 index cbb367e31741..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_get_discovery_engine_memory_maximum_set_gen.py +++ /dev/null @@ -1,42 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python investigations_get_discovery_engine_memory_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.investigations.get_discovery_engine_memory( - project_name="697a8775a22a91aa0d", - investigation_name="172e0546a46318684a", - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Investigations_GetDiscoveryEngineMemory_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_get_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_get_maximum_set_gen.py deleted file mode 100644 index 1f260fadd841..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_get_maximum_set_gen.py +++ /dev/null @@ -1,42 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python investigations_get_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.investigations.get( - project_name="1604b2e5c2c73a8fc6", - investigation_name="544f85c8e73b336f30", - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Investigations_Get_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_get_operation_status_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_get_operation_status_maximum_set_gen.py deleted file mode 100644 index 6b2678955554..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_get_operation_status_maximum_set_gen.py +++ /dev/null @@ -1,43 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python investigations_get_operation_status_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.investigations.get_operation_status( - project_name="c4d433160105cb7e05", - investigation_name="27c77e83d983252ba5", - operation_id="gtqbgvfrbddxtwpwtogqugkgkfezt", - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Investigations_GetOperationStatus_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_list_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_list_maximum_set_gen.py deleted file mode 100644 index 77b96a6f2876..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_list_maximum_set_gen.py +++ /dev/null @@ -1,41 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python investigations_list_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.investigations.list( - project_name="24b1966c0a3b9f2f30", - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Investigations_List_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_start_discovery_engine_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_start_discovery_engine_maximum_set_gen.py deleted file mode 100644 index 7b0c9c08b9de..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_start_discovery_engine_maximum_set_gen.py +++ /dev/null @@ -1,42 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python investigations_start_discovery_engine_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.investigations.start_discovery_engine( - project_name="7d39330561b94bdcc3", - investigation_name="343c643fdf27bb346f", - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Investigations_StartDiscoveryEngine_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_stop_discovery_engine_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_stop_discovery_engine_maximum_set_gen.py deleted file mode 100644 index 94a4f547ffa2..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_stop_discovery_engine_maximum_set_gen.py +++ /dev/null @@ -1,42 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python investigations_stop_discovery_engine_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.investigations.stop_discovery_engine( - project_name="be621383ce50697d42", - investigation_name="baf0b8e0658f3b20ac", - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Investigations_StopDiscoveryEngine_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_update_discovery_engine_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_update_discovery_engine_maximum_set_gen.py deleted file mode 100644 index c0832fec6bab..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/investigations_update_discovery_engine_maximum_set_gen.py +++ /dev/null @@ -1,43 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python investigations_update_discovery_engine_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.investigations.update_discovery_engine( - project_name="30180fbf0aa35804ad", - investigation_name="c16fa428b6f538f21d", - body={"configuration": {}, "discoveryEngineStatus": "Inactive", "systemPrompt": "jai"}, - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Investigations_UpdateDiscoveryEngine_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_add_comment_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_add_comment_maximum_set_gen.py deleted file mode 100644 index 9efb89572eed..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_add_comment_maximum_set_gen.py +++ /dev/null @@ -1,49 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python tasks_add_comment_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.tasks.add_comment( - task_name="c8fc097eeb1d82840e", - project_name="cd6107a453d2b9c4e4", - investigation_name="f17d4ec2f807991d9f", - body={ - "createdBy": "foypxuisqdsv", - "createdByType": "User", - "text": "pigdcoefkzcebicjbi", - "timestamp": "2026-04-16T16:55:20.492Z", - }, - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Tasks_AddComment_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_add_execution_history_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_add_execution_history_maximum_set_gen.py deleted file mode 100644 index 26f91ba94334..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_add_execution_history_maximum_set_gen.py +++ /dev/null @@ -1,54 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# 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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python tasks_add_execution_history_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.tasks.add_execution_history( - project_name="f5f4bd1b53bb57c393", - investigation_name="88e472b2d6ebfaf87f", - task_name="35a738e7f0b4b429f6", - body={ - "action": "veywfetcgapz", - "additionalDetails": {}, - "createdAt": "2026-04-16T16:55:20.492Z", - "createdBy": "tugvjglavtqj", - "createdByType": "User", - "responseMessageId": "kvfdivtewku", - "responseMessageText": "bqjvvdnnne", - "summary": "goqxtiwjxekomivvvcyrvpjupsrxigliqnnbjofaxsobszvypeshsujdgunyxknwytujbincrmtkffvyxyumnqpptoymibtwswwqkfhfjrpezzcshktgysxylalckotgobbejnuhkkzqztcxvxmpxulrgywijlypqnsveuxdvcziyhhwtihiseojsjmykxfhibfbjxeotiqxjcbshzunyebpxfnhbuscxjvuftzjpqulxxvicovlfnmozyyojprwkmjyyzmxkvomadzxnbzkgklzsimzgcnyyeqldmquntxuafwvpbywyvwdzhutpkuueqvhpdyotmcmezlniwowcrsoygsidjjnravkhodnlilxmooskbsxytkfqhptqpnqnigynjvefovjroxokuhbwrlpbigizottcdsvlyyqmrcrqsuvdpmvcrcttmwhgdziqbuehoaxnhszdkrmyc", - }, - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Tasks_AddExecutionHistory_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_create_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_create_maximum_set_gen.py deleted file mode 100644 index 1823fd35f8ab..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_create_maximum_set_gen.py +++ /dev/null @@ -1,74 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# 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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python tasks_create_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.tasks.create( - project_name="fa7fb60629081486ee", - investigation_name="8ce57cdb3168cfc8ef", - body={ - "assignedTo": {"id": "ixab", "type": "User"}, - "comments": [ - { - "createdBy": "foypxuisqdsv", - "createdByType": "User", - "text": "pigdcoefkzcebicjbi", - "timestamp": "2026-04-16T16:55:20.492Z", - } - ], - "createdByType": "User", - "dependsOn": ["peknigqbomd"], - "description": "cawdurbbghvez", - "investigationId": "zhjwxsrmtgbezvbjopbdhegpg", - "lastModifiedByType": "User", - "parentId": "ju", - "priority": "Low", - "relatedTo": ["wjjhlkqayhfjugqphistorg"], - "status": "New", - "storageAssetIds": [ - "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example-rg/providers/Microsoft.Discovery/storageContainers/example-storageContainer/storageAssets/example-storageAsset" - ], - "taskResult": { - "storageAssetIds": [ - "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example-rg/providers/Microsoft.Discovery/storageContainers/example-storageContainer/storageAssets/example-storageAsset" - ], - "text": "zwcwetwdeml", - }, - "title": "kklflskihtgducwuipmg", - "validationRequirements": ["mmqqcxortskregd"], - }, - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Tasks_Create_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_delete_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_delete_maximum_set_gen.py deleted file mode 100644 index d8fdeeaceb0e..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_delete_maximum_set_gen.py +++ /dev/null @@ -1,42 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python tasks_delete_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - client.tasks.delete( - project_name="65088c72771f0cb5db", - investigation_name="7db99d50457dfa4d15", - task_name="cf66765cf1b7ee1519", - ) - - -# x-ms-original-file: 2026-02-01-preview/Tasks_Delete_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_get_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_get_maximum_set_gen.py deleted file mode 100644 index 52d21d2e6af6..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_get_maximum_set_gen.py +++ /dev/null @@ -1,43 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python tasks_get_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.tasks.get( - project_name="4f37071081a4cf7285", - investigation_name="29cd9e016c511fcf72", - task_name="3f3772ad2687cc7bac", - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Tasks_Get_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_list_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_list_maximum_set_gen.py deleted file mode 100644 index 49ad103fe46f..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_list_maximum_set_gen.py +++ /dev/null @@ -1,43 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python tasks_list_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.tasks.list( - project_name="e526554572c01f152a", - investigation_name="9fbcfb7ff10fd15170", - ) - for item in response: - print(item) - - -# x-ms-original-file: 2026-02-01-preview/Tasks_List_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_start_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_start_maximum_set_gen.py deleted file mode 100644 index d9595cb16ac9..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_start_maximum_set_gen.py +++ /dev/null @@ -1,43 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python tasks_start_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.tasks.start( - project_name="5371d1fd485ee29898", - investigation_name="e8065f7f0641956f8b", - task_name="79cf5c9f68785aea5c", - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Tasks_Start_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_update_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_update_maximum_set_gen.py deleted file mode 100644 index 509d1a24b761..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tasks_update_maximum_set_gen.py +++ /dev/null @@ -1,74 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# 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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python tasks_update_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.tasks.update( - project_name="357b0c7633679b4568", - investigation_name="847b92494d34a4037c", - task_name="d7b81df4b1632c67ef", - resource={ - "assignedTo": {"id": "pqyjwdnqbpgpirlixioldk", "type": "User"}, - "comments": [ - { - "createdBy": "foypxuisqdsv", - "createdByType": "User", - "text": "pigdcoefkzcebicjbi", - "timestamp": "2026-04-16T16:55:20.492Z", - } - ], - "createdByType": "User", - "dependsOn": ["pjubwdhungcb"], - "description": "fottcyvmiqydwbqpbhfxyfbjr", - "investigationId": "kfkhyukpoxsi", - "parentId": "iw", - "priority": "Low", - "relatedTo": ["afhvxxhkzfivwlvdeankpj"], - "status": "New", - "storageAssetIds": [ - "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example-rg/providers/Microsoft.Discovery/storageContainers/example-storageContainer/storageAssets/example-storageAsset" - ], - "taskResult": { - "storageAssetIds": [ - "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example-rg/providers/Microsoft.Discovery/storageContainers/example-storageContainer/storageAssets/example-storageAsset" - ], - "text": "zwcwetwdeml", - }, - "title": "tarndyeibbgskbrvdhhvenh", - "validationRequirements": ["ssxhggjfhl"], - }, - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Tasks_Update_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tools_cancel_run_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tools_cancel_run_maximum_set_gen.py deleted file mode 100644 index a0924a453469..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tools_cancel_run_maximum_set_gen.py +++ /dev/null @@ -1,41 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python tools_cancel_run_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - client.tools.cancel_run( - project_name="137aa48a7ce8479e4e", - operation_id="ugordhuvuz", - ) - - -# x-ms-original-file: 2026-02-01-preview/Tools_CancelRun_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tools_get_compute_usage_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tools_get_compute_usage_maximum_set_gen.py deleted file mode 100644 index a9176a29500a..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tools_get_compute_usage_maximum_set_gen.py +++ /dev/null @@ -1,41 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python tools_get_compute_usage_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.tools.get_compute_usage( - project_name="5c8aac55a39a521511", - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Tools_GetComputeUsage_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tools_get_operations_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tools_get_operations_maximum_set_gen.py deleted file mode 100644 index 78f6823b489c..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tools_get_operations_maximum_set_gen.py +++ /dev/null @@ -1,41 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python tools_get_operations_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.tools.get_operations( - project_name="62ca7521ad1961d366", - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Tools_GetOperations_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tools_get_run_status_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tools_get_run_status_maximum_set_gen.py deleted file mode 100644 index 9835fe70d4e5..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tools_get_run_status_maximum_set_gen.py +++ /dev/null @@ -1,42 +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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python tools_get_run_status_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.tools.get_run_status( - project_name="29a1a1a39b14927f20", - operation_id="vzaemmlmudvqinvcr", - ) - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Tools_GetRunStatus_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tools_run_maximum_set_gen.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tools_run_maximum_set_gen.py deleted file mode 100644 index 6ffc9ef87511..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_samples/tools_run_maximum_set_gen.py +++ /dev/null @@ -1,238 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# 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 azure.identity import DefaultAzureCredential - -from azure.ai.discovery import WorkspaceClient - -""" -# PREREQUISITES - pip install azure-identity - pip install azure-ai-discovery -# USAGE - python tools_run_maximum_set_gen.py - - Before run the sample, please set the values of the client ID, tenant ID and client secret - of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, - AZURE_CLIENT_SECRET. For more info about how to get the value, please see: - https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal -""" - - -def main(): - client = WorkspaceClient( - endpoint="ENDPOINT", - credential=DefaultAzureCredential(), - ) - - response = client.tools.begin_run( - project_name="8392b621359c32ce80", - body={ - "command": "bvlbtxwberpzlb", - "environmentVariables": [ - { - "name": "ENV_VAR_33afd2a6", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_2006b39f", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_3c5f5314", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_fed8de06", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_c093401f", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_ef6dd9bf", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_dc4ab6a4", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_e64efa8a", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_2bf39b4e", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_59b1f1d1", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_360c4b6f", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_152f6734", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_457f544a", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_2e6a086e", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_80cdafd4", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_6d50ee16", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_43ecb136", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_4b8c05b9", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_ed80dd98", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_09da1016", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_e8a88df7", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_c961d048", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_76bc1ab2", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_3bca9508", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_a17ebaa4", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_e1560112", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_be82143e", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_6acc44d3", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_7c0dd877", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_22e6a0ae", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_e955f55a", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_802f9a9f", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_3f1eb0e5", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_0d6872ce", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_ce27c46d", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_9fbb708c", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_6b8d8a39", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_0cd1f372", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - { - "name": "ENV_VAR_aa0e84d0", - "value": "kleykjuqhupklbwaoknancaapegkmzvkzevdkbmdkbpooeussltrhaepuknsakjiusulgqxacqaxiepzbykyazscelwvsuwopipy", - }, - ], - "infraOverrides": { - "cpu": "vfvn", - "gpu": "ivx", - "imageUri": "etzmjqehjikpkxgvpfizkbpyuirp", - "ram": "om", - "replicaCount": 20, - }, - "inlineFiles": [ - { - "encodedFile": "dagltanovrtrmvzhnwgregntgtsqidbwwretkdhpbcyoxggmurnmxhqzvtoleobekvesnqsfvtrqlvsjkpqrbjpdeppoqxzgmspl", - "mountPath": "/mnt/27b842787bb9bb0243", - }, - { - "encodedFile": "dagltanovrtrmvzhnwgregntgtsqidbwwretkdhpbcyoxggmurnmxhqzvtoleobekvesnqsfvtrqlvsjkpqrbjpdeppoqxzgmspl", - "mountPath": "/mnt/84fb2f6c58b87a4c78", - }, - ], - "inputData": [ - { - "mountPath": "/mnt/d3a0363f8def769e98", - "storageUri": "discovery://storageassets/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example-rg/providers/Microsoft.Discovery/storageContainers/example-storage-container/storageAssets/example-storage-asset/paths/example-file", - } - ], - "nodePoolIds": [ - "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example-rg/providers/Microsoft.Discovery/supercomputers/example-supercomputer/nodePools/example-nodePool" - ], - "outputData": [ - { - "mountPath": "/mnt/0a2507435d99ebea5f", - "storageUri": "discovery://storageassets/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example-rg/providers/Microsoft.Discovery/storageContainers/example-storage-container/storageAssets/example-storage-asset/paths/example-file", - } - ], - "toolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/example-rg/providers/Microsoft.Discovery/tools/example-tool", - }, - tool_id="str", - node_pool_ids=["str"], - ).result() - print(response) - - -# x-ms-original-file: 2026-02-01-preview/Tools_Run_MaximumSet_Gen.json -if __name__ == "__main__": - main() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/conftest.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/conftest.py deleted file mode 100644 index 90769344bd40..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/conftest.py +++ /dev/null @@ -1,35 +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. -# -------------------------------------------------------------------------- -import os -import pytest -from dotenv import load_dotenv -from devtools_testutils import ( - test_proxy, - add_general_regex_sanitizer, - add_body_key_sanitizer, - add_header_regex_sanitizer, -) - -load_dotenv() - - -# For security, please avoid record sensitive identity information in recordings -@pytest.fixture(scope="session", autouse=True) -def add_sanitizers(test_proxy): - workspace_subscription_id = os.environ.get("WORKSPACE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") - workspace_tenant_id = os.environ.get("WORKSPACE_TENANT_ID", "00000000-0000-0000-0000-000000000000") - workspace_client_id = os.environ.get("WORKSPACE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") - workspace_client_secret = os.environ.get("WORKSPACE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=workspace_subscription_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=workspace_tenant_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=workspace_client_id, value="00000000-0000-0000-0000-000000000000") - add_general_regex_sanitizer(regex=workspace_client_secret, value="00000000-0000-0000-0000-000000000000") - - add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") - add_header_regex_sanitizer(key="Cookie", value="cookie;") - add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/testpreparer.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/testpreparer.py deleted file mode 100644 index e28770fa7ebb..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/testpreparer.py +++ /dev/null @@ -1,26 +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 azure.ai.discovery import WorkspaceClient -from devtools_testutils import AzureRecordedTestCase, PowerShellPreparer -import functools - - -class WorkspaceClientTestBase(AzureRecordedTestCase): - - def create_client(self, endpoint): - credential = self.get_credential(WorkspaceClient) - return self.create_client_from_credential( - WorkspaceClient, - credential=credential, - endpoint=endpoint, - ) - - -WorkspacePreparer = functools.partial( - PowerShellPreparer, "workspace", workspace_endpoint="https://fake_workspace_endpoint.com" -) diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/pyproject.toml b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/pyproject.toml deleted file mode 100644 index f843669f0665..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/pyproject.toml +++ /dev/null @@ -1,61 +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. -# -------------------------------------------------------------------------- - -[build-system] -requires = ["setuptools>=77.0.3", "wheel"] -build-backend = "setuptools.build_meta" - -[project] -name = "azure-ai-discovery" -authors = [ - { name = "Microsoft Corporation", email = "azpysdkhelp@microsoft.com" }, -] -description = "Microsoft Corporation Azure Ai Discovery Client Library for Python" -license = "MIT" -classifiers = [ - "Development Status :: 4 - Beta", - "Programming Language :: Python", - "Programming Language :: Python :: 3 :: Only", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", -] -requires-python = ">=3.9" -keywords = ["azure", "azure sdk"] - -dependencies = [ - "isodate>=0.6.1", - "azure-core>=1.37.0", - "typing-extensions>=4.6.0", -] -dynamic = [ -"version", "readme" -] - -[project.urls] -repository = "https://github.com/Azure/azure-sdk-for-python" - -[tool.setuptools.dynamic] -version = {attr = "azure.ai.discovery._version.VERSION"} -readme = {file = ["README.md", "CHANGELOG.md"], content-type = "text/markdown"} - -[tool.setuptools.packages.find] -exclude = [ - "tests*", - "generated_tests*", - "samples*", - "generated_samples*", - "doc*", - "azure", - "azure.ai", -] - -[tool.setuptools.package-data] -pytyped = ["py.typed"] diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/tsp-location.yaml b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/tsp-location.yaml deleted file mode 100644 index 42cef2118abd..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/tsp-location.yaml +++ /dev/null @@ -1,3 +0,0 @@ -directory: specification/discovery/Discovery.Workspace -commit: df74858bfda6128d16c98265db2a6f42e89b20ff -repo: Azure/azure-rest-api-specs diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/__init__.py index adf140815f94..3ba975029ef8 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/__init__.py +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/__init__.py @@ -2,21 +2,30 @@ # -------------------------------------------------------------------------- # 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 -"""Async clients for Azure AI Discovery. +from typing import TYPE_CHECKING -This module mirrors the top-level :mod:`azure.ai.discovery` package and exposes the -asynchronous variants of both ``WorkspaceClient`` and ``BookshelfClient`` from a -single import location:: +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import - from azure.ai.discovery.aio import WorkspaceClient, BookshelfClient -""" +from ._client import WorkspaceClient # type: ignore +from ._client import BookshelfClient # type: ignore -from .._workspace.azure.ai.discovery.aio import WorkspaceClient # type: ignore -from .._bookshelf.azure.ai.discovery.aio import BookshelfClient # type: ignore +try: + from ._patch import __all__ as _patch_all + from ._patch import * +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk __all__ = [ - "BookshelfClient", "WorkspaceClient", + "BookshelfClient", ] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore + +_patch_sdk() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/_client.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/_client.py similarity index 53% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/_client.py rename to sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/_client.py index fd9215f1e695..c69d479b6167 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/_client.py +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/_client.py @@ -7,16 +7,27 @@ # -------------------------------------------------------------------------- from copy import deepcopy +import sys from typing import Any, Awaitable, TYPE_CHECKING -from typing_extensions import Self from azure.core import AsyncPipelineClient from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from .._utils.serialization import Deserializer, Serializer -from ._configuration import WorkspaceClientConfiguration -from .operations import ConversationsOperations, InvestigationsOperations, TasksOperations, ToolsOperations +from ._configuration import BookshelfClientConfiguration, WorkspaceClientConfiguration +from .operations import ( + ConversationsOperations, + InvestigationsOperations, + KnowledgeBasesOperations, + TasksOperations, + ToolsOperations, +) + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing_extensions import Self # type: ignore if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential @@ -38,9 +49,9 @@ class WorkspaceClient: :type endpoint: str :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: The API version to use for this operation. Known values are - "2026-02-01-preview" and None. Default value is "2026-02-01-preview". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: The API version to use for this operation. Known values are "2026-06-01" + and None. Default value is None. If not set, the operation's default API version will be used. + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. @@ -114,3 +125,88 @@ async def __aenter__(self) -> Self: async def __aexit__(self, *exc_details: Any) -> None: await self._client.__aexit__(*exc_details) + + +class BookshelfClient: + """BookshelfClient. + + :ivar knowledge_bases: KnowledgeBasesOperations operations + :vartype knowledge_bases: azure.ai.discovery.aio.operations.KnowledgeBasesOperations + :param endpoint: Supported Microsoft Bookshelf Services endpoints (protocol and hostname, for + example: https://{bookshelfName}.discovery.azure.com). Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Known values are "2026-06-01" + and None. Default value is None. If not set, the operation's default API version will be used. + Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str + :keyword int polling_interval: Default waiting time between two polls for LRO operations if no + Retry-After header is present. + """ + + def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + _endpoint = "{endpoint}" + self._config = BookshelfClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + self._serialize = Serializer() + self._deserialize = Deserializer() + self._serialize.client_side_validation = False + self.knowledge_bases = KnowledgeBasesOperations(self._client, self._config, self._serialize, self._deserialize) + + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = await client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.AsyncHttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + async def close(self) -> None: + await self._client.close() + + async def __aenter__(self) -> Self: + await self._client.__aenter__() + return self + + async def __aexit__(self, *exc_details: Any) -> None: + await self._client.__aexit__(*exc_details) diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/_configuration.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/_configuration.py similarity index 50% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/_configuration.py rename to sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/_configuration.py index cc331037165c..6c520d1ec83b 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/_configuration.py +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/_configuration.py @@ -16,6 +16,55 @@ from azure.core.credentials_async import AsyncTokenCredential +class WorkspaceClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for WorkspaceClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param endpoint: Supported Discovery Workspace Services endpoints (protocol and hostname, for + example: https://{workspaceName}.discovery.azure.com). Required. + :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :keyword api_version: The API version to use for this operation. Known values are "2026-06-01" + and None. Default value is None. If not set, the operation's default API version will be used. + Note that overriding this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2026-06-01") + + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.endpoint = endpoint + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://discovery.azure.com/.default"]) + kwargs.setdefault("sdk_moniker", "ai-discovery/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) + + class BookshelfClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for BookshelfClient. @@ -27,14 +76,14 @@ class BookshelfClientConfiguration: # pylint: disable=too-many-instance-attribu :type endpoint: str :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: The API version to use for this operation. Known values are - "2026-02-01-preview" and None. Default value is "2026-02-01-preview". Note that overriding this - default value may result in unsupported behavior. + :keyword api_version: The API version to use for this operation. Known values are "2026-06-01" + and None. Default value is None. If not set, the operation's default API version will be used. + Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - api_version: str = kwargs.pop("api_version", "2026-02-01-preview") + api_version: str = kwargs.pop("api_version", "2026-06-01") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/_patch.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/_patch.py similarity index 53% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/_patch.py rename to sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/_patch.py index 3070f4908ab3..4952dccddae0 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/aio/_patch.py +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/_patch.py @@ -7,24 +7,51 @@ Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ + from typing import Any, Optional, TYPE_CHECKING from ._client import BookshelfClient as _GeneratedBookshelfClient +from ._client import WorkspaceClient as _GeneratedWorkspaceClient if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential from azure.core.pipeline.transport import AsyncHttpTransport +class WorkspaceClient(_GeneratedWorkspaceClient): + """WorkspaceClient with an explicit ``transport`` keyword-only argument. + + See https://azure.github.io/azure-sdk/python_design.html#python-client-constructor-transport-argument + + :keyword api_version: The API version to use for this operation. Known values are "2026-06-01". + Overriding the default may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + endpoint: str, + credential: "AsyncTokenCredential", + *, + api_version: Optional[str] = None, + transport: Optional["AsyncHttpTransport"] = None, + **kwargs: Any, + ) -> None: + if api_version is not None: + kwargs["api_version"] = api_version + if transport is not None: + kwargs["transport"] = transport + super().__init__(endpoint=endpoint, credential=credential, **kwargs) + + class BookshelfClient(_GeneratedBookshelfClient): - """Async BookshelfClient with explicit ``transport`` keyword-only argument. + """BookshelfClient with an explicit ``transport`` keyword-only argument. See https://azure.github.io/azure-sdk/python_design.html#python-client-constructor-transport-argument - :ivar knowledge_bases: KnowledgeBasesOperations operations - :vartype knowledge_bases: azure.ai.discovery.aio.operations.KnowledgeBasesOperations - :ivar knowledge_base_versions: KnowledgeBaseVersionsOperations operations - :vartype knowledge_base_versions: azure.ai.discovery.aio.operations.KnowledgeBaseVersionsOperations + :keyword api_version: The API version to use for this operation. Known values are "2026-06-01". + Overriding the default may result in unsupported behavior. + :paramtype api_version: str """ def __init__( @@ -36,22 +63,6 @@ def __init__( transport: Optional["AsyncHttpTransport"] = None, **kwargs: Any, ) -> None: - """Create a new asynchronous ``BookshelfClient``. - - :param endpoint: The Discovery service endpoint, in the form - ``https://.services.ai.azure.com``. Required. - :type endpoint: str - :param credential: Credential used to authenticate requests to the service. - Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: The API version to use for the request. Default value - is the latest service version supported by this client. Note that - overriding this default value may result in unsupported behavior. - :paramtype api_version: str - :keyword transport: The async HTTP transport to use. If not specified, the - default ``azure-core`` async transport (``AioHttpTransport``) is used. - :paramtype transport: ~azure.core.pipeline.transport.AsyncHttpTransport - """ if api_version is not None: kwargs["api_version"] = api_version if transport is not None: @@ -59,7 +70,7 @@ def __init__( super().__init__(endpoint=endpoint, credential=credential, **kwargs) -__all__: list[str] = ["BookshelfClient"] +__all__: list[str] = ["WorkspaceClient", "BookshelfClient"] def patch_sdk(): diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/operations/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/operations/__init__.py similarity index 92% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/operations/__init__.py rename to sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/operations/__init__.py index 011818daade0..110360a67296 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/operations/__init__.py +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/operations/__init__.py @@ -16,6 +16,7 @@ from ._operations import ConversationsOperations # type: ignore from ._operations import ToolsOperations # type: ignore from ._operations import TasksOperations # type: ignore +from ._operations import KnowledgeBasesOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -26,6 +27,7 @@ "ConversationsOperations", "ToolsOperations", "TasksOperations", + "KnowledgeBasesOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/operations/_operations.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/operations/_operations.py similarity index 67% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/operations/_operations.py rename to sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/operations/_operations.py index 361fbc00a5ae..94b03418443c 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/operations/_operations.py +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/operations/_operations.py @@ -33,7 +33,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import models as _models +from ... import models as _models, types as _types from ..._utils.model_base import SdkJSONEncoder, _deserialize from ..._utils.serialization import Deserializer, Serializer from ..._validation import api_version_validation @@ -42,9 +42,8 @@ build_conversations_delete_request, build_conversations_get_request, build_conversations_list_request, - build_conversations_update_request, + build_conversations_stable_update_request, build_investigations_create_or_replace_request, - build_investigations_create_or_update_request, build_investigations_delete_request, build_investigations_get_discovery_engine_memory_request, build_investigations_get_discovery_engine_request, @@ -54,25 +53,34 @@ build_investigations_start_discovery_engine_request, build_investigations_stop_discovery_engine_request, build_investigations_update_discovery_engine_request, + build_investigations_update_request, + build_knowledge_bases_cancel_indexing_request, + build_knowledge_bases_create_or_update_request, + build_knowledge_bases_delete_request, + build_knowledge_bases_get_operation_status_request, + build_knowledge_bases_get_request, + build_knowledge_bases_list_request, + build_knowledge_bases_search_request, + build_knowledge_bases_start_indexing_request, build_tasks_add_comment_request, build_tasks_add_execution_history_request, build_tasks_create_request, build_tasks_delete_request, build_tasks_get_request, build_tasks_list_request, + build_tasks_stable_update_request, build_tasks_start_request, - build_tasks_update_request, - build_tools_cancel_run_request, + build_tools_cancel_run_lro_request, build_tools_get_compute_usage_request, build_tools_get_operations_request, build_tools_get_run_status_request, build_tools_run_request, ) -from .._configuration import WorkspaceClientConfiguration +from .._configuration import BookshelfClientConfiguration, WorkspaceClientConfiguration -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] _Unset: Any = object() List = list @@ -160,15 +168,13 @@ async def get(self, project_name: str, investigation_name: str, **kwargs: Any) - @distributed_trace_async @api_version_validation( - method_added_on="2026-02-01-preview", - params_added_on={ - "2026-02-01-preview": ["api_version", "project_name", "investigation_name", "operation_id", "accept"] - }, - api_versions_list=["2026-02-01-preview"], + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "project_name", "investigation_name", "operation_id", "accept"]}, + api_versions_list=["2026-06-01"], ) async def get_operation_status( self, project_name: str, investigation_name: str, operation_id: str, **kwargs: Any - ) -> _models.ResourceOperationStatusInvestigationInvestigationError: + ) -> _models.InvestigationOperationStatus: """Get the status of a long-running operation. :param project_name: The project name. Required. @@ -177,9 +183,9 @@ async def get_operation_status( :type investigation_name: str :param operation_id: The unique ID of the operation. Required. :type operation_id: str - :return: ResourceOperationStatusInvestigationInvestigationError. The - ResourceOperationStatusInvestigationInvestigationError is compatible with MutableMapping - :rtype: ~azure.ai.discovery.models.ResourceOperationStatusInvestigationInvestigationError + :return: InvestigationOperationStatus. The InvestigationOperationStatus is compatible with + MutableMapping + :rtype: ~azure.ai.discovery.models.InvestigationOperationStatus :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -193,7 +199,7 @@ async def get_operation_status( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.ResourceOperationStatusInvestigationInvestigationError] = kwargs.pop("cls", None) + cls: ClsType[_models.InvestigationOperationStatus] = kwargs.pop("cls", None) _request = build_investigations_get_operation_status_request( project_name=project_name, @@ -228,7 +234,7 @@ async def get_operation_status( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.ResourceOperationStatusInvestigationInvestigationError, response.json()) + deserialized = _deserialize(_models.InvestigationOperationStatus, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -266,7 +272,7 @@ async def create_or_replace( self, project_name: str, investigation_name: str, - resource: JSON, + resource: _types.Investigation, *, content_type: str = "application/json", **kwargs: Any @@ -278,7 +284,7 @@ async def create_or_replace( :param investigation_name: The investigation name. Required. :type investigation_name: str :param resource: The resource instance. Required. - :type resource: JSON + :type resource: ~azure.ai.discovery.types.Investigation :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -318,7 +324,7 @@ async def create_or_replace( self, project_name: str, investigation_name: str, - resource: Union[_models.Investigation, JSON, IO[bytes]], + resource: Union[_models.Investigation, _types.Investigation, IO[bytes]], **kwargs: Any ) -> _models.Investigation: """Creates an Investigation. @@ -327,9 +333,10 @@ async def create_or_replace( :type project_name: str :param investigation_name: The investigation name. Required. :type investigation_name: str - :param resource: The resource instance. Is one of the following types: Investigation, JSON, - IO[bytes] Required. - :type resource: ~azure.ai.discovery.models.Investigation or JSON or IO[bytes] + :param resource: The resource instance. Is either a Investigation type or a IO[bytes] type. + Required. + :type resource: ~azure.ai.discovery.models.Investigation or + ~azure.ai.discovery.types.Investigation or IO[bytes] :return: Investigation. The Investigation is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.Investigation :raises ~azure.core.exceptions.HttpResponseError: @@ -397,7 +404,7 @@ async def create_or_replace( return deserialized # type: ignore @overload - async def create_or_update( + async def update( self, project_name: str, investigation_name: str, @@ -423,11 +430,11 @@ async def create_or_update( """ @overload - async def create_or_update( + async def update( self, project_name: str, investigation_name: str, - resource: JSON, + resource: _types.Investigation, *, content_type: str = "application/merge-patch+json", **kwargs: Any @@ -439,7 +446,7 @@ async def create_or_update( :param investigation_name: The investigation name. Required. :type investigation_name: str :param resource: The resource instance. Required. - :type resource: JSON + :type resource: ~azure.ai.discovery.types.Investigation :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -449,7 +456,7 @@ async def create_or_update( """ @overload - async def create_or_update( + async def update( self, project_name: str, investigation_name: str, @@ -475,11 +482,16 @@ async def create_or_update( """ @distributed_trace_async - async def create_or_update( + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "project_name", "investigation_name", "content_type", "accept"]}, + api_versions_list=["2026-06-01"], + ) + async def update( self, project_name: str, investigation_name: str, - resource: Union[_models.Investigation, JSON, IO[bytes]], + resource: Union[_models.Investigation, _types.Investigation, IO[bytes]], **kwargs: Any ) -> _models.Investigation: """Updates an Investigation. @@ -488,9 +500,10 @@ async def create_or_update( :type project_name: str :param investigation_name: The investigation name. Required. :type investigation_name: str - :param resource: The resource instance. Is one of the following types: Investigation, JSON, - IO[bytes] Required. - :type resource: ~azure.ai.discovery.models.Investigation or JSON or IO[bytes] + :param resource: The resource instance. Is either a Investigation type or a IO[bytes] type. + Required. + :type resource: ~azure.ai.discovery.models.Investigation or + ~azure.ai.discovery.types.Investigation or IO[bytes] :return: Investigation. The Investigation is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.Investigation :raises ~azure.core.exceptions.HttpResponseError: @@ -516,7 +529,7 @@ async def create_or_update( else: _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_investigations_create_or_update_request( + _request = build_investigations_update_request( project_name=project_name, investigation_name=investigation_name, content_type=content_type, @@ -538,7 +551,7 @@ async def create_or_update( response = pipeline_response.http_response - if response.status_code not in [200, 201]: + if response.status_code not in [200]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -557,11 +570,6 @@ async def create_or_update( return deserialized # type: ignore - @api_version_validation( - method_added_on="2026-02-01-preview", - params_added_on={"2026-02-01-preview": ["api_version", "project_name", "investigation_name", "accept"]}, - api_versions_list=["2026-02-01-preview"], - ) async def _delete_initial(self, project_name: str, investigation_name: str, **kwargs: Any) -> AsyncIterator[bytes]: error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -615,11 +623,6 @@ async def _delete_initial(self, project_name: str, investigation_name: str, **kw return deserialized # type: ignore @distributed_trace_async - @api_version_validation( - method_added_on="2026-02-01-preview", - params_added_on={"2026-02-01-preview": ["api_version", "project_name", "investigation_name", "accept"]}, - api_versions_list=["2026-02-01-preview"], - ) async def begin_delete( self, project_name: str, investigation_name: str, **kwargs: Any ) -> AsyncLROPoller[_models.Investigation]: @@ -690,17 +693,34 @@ def get_long_running_output(pipeline_response): ) @distributed_trace_async + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={ + "2026-06-01": ["api_version", "project_name", "created_since", "top", "skip", "maxpagesize", "accept"] + }, + api_versions_list=["2026-06-01"], + ) async def list( - self, project_name: str, *, created_since: Optional[datetime.datetime] = None, **kwargs: Any - ) -> List[_models.Investigation]: + self, + project_name: str, + *, + created_since: Optional[datetime.datetime] = None, + top: Optional[int] = None, + skip: Optional[int] = None, + **kwargs: Any + ) -> _models.PagedInvestigation: """List Investigation resources. :param project_name: The project name. Required. :type project_name: str :keyword created_since: The oldest creation timestamp to keep. Default value is None. :paramtype created_since: ~datetime.datetime - :return: list of Investigation - :rtype: list[~azure.ai.discovery.models.Investigation] + :keyword top: The number of result items to return. Default value is None. + :paramtype top: int + :keyword skip: The number of result items to skip. Default value is None. + :paramtype skip: int + :return: PagedInvestigation. The PagedInvestigation is compatible with MutableMapping + :rtype: ~azure.ai.discovery.models.PagedInvestigation :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -714,11 +734,15 @@ async def list( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.Investigation]] = kwargs.pop("cls", None) + maxpagesize = kwargs.pop("maxpagesize", None) + cls: ClsType[_models.PagedInvestigation] = kwargs.pop("cls", None) _request = build_investigations_list_request( project_name=project_name, created_since=created_since, + top=top, + skip=skip, + maxpagesize=maxpagesize, api_version=self._config.api_version, headers=_headers, params=_params, @@ -748,7 +772,7 @@ async def list( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(List[_models.Investigation], response.json()) + deserialized = _deserialize(_models.PagedInvestigation, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -823,28 +847,19 @@ async def get_discovery_engine( @distributed_trace_async @api_version_validation( - method_added_on="2026-02-01-preview", + method_added_on="2026-06-01", params_added_on={ - "2026-02-01-preview": [ - "api_version", - "project_name", - "investigation_name", - "skip", - "top", - "max_page_size", - "accept", - ] + "2026-06-01": ["api_version", "project_name", "investigation_name", "top", "skip", "maxpagesize", "accept"] }, - api_versions_list=["2026-02-01-preview"], + api_versions_list=["2026-06-01"], ) async def get_discovery_engine_memory( self, project_name: str, investigation_name: str, *, - skip: Optional[int] = None, top: Optional[int] = None, - max_page_size: Optional[int] = None, + skip: Optional[int] = None, **kwargs: Any ) -> _models.PagedWorkingMemoryEntry: """List discovery engine working memory entries for an investigation. @@ -853,13 +868,10 @@ async def get_discovery_engine_memory( :type project_name: str :param investigation_name: The investigation name. Required. :type investigation_name: str - :keyword skip: Skip results. Default value is None. - :paramtype skip: int - :keyword top: Query the top results. Default value is None. + :keyword top: The number of result items to return. Default value is None. :paramtype top: int - :keyword max_page_size: Bound the number of results that come back in one response. Default - value is None. - :paramtype max_page_size: int + :keyword skip: The number of result items to skip. Default value is None. + :paramtype skip: int :return: PagedWorkingMemoryEntry. The PagedWorkingMemoryEntry is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.PagedWorkingMemoryEntry :raises ~azure.core.exceptions.HttpResponseError: @@ -875,14 +887,15 @@ async def get_discovery_engine_memory( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} + maxpagesize = kwargs.pop("maxpagesize", None) cls: ClsType[_models.PagedWorkingMemoryEntry] = kwargs.pop("cls", None) _request = build_investigations_get_discovery_engine_memory_request( project_name=project_name, investigation_name=investigation_name, - skip=skip, top=top, - max_page_size=max_page_size, + skip=skip, + maxpagesize=maxpagesize, api_version=self._config.api_version, headers=_headers, params=_params, @@ -1084,7 +1097,7 @@ async def update_discovery_engine( self, project_name: str, investigation_name: str, - body: JSON, + body: _types.DiscoveryEngineUpdate, *, content_type: str = "application/json", **kwargs: Any @@ -1098,7 +1111,7 @@ async def update_discovery_engine( :type investigation_name: str :param body: The discovery engine update request. This will create the discovery engine if it does not already exist. Required. - :type body: JSON + :type body: ~azure.ai.discovery.types.DiscoveryEngineUpdate :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1136,18 +1149,11 @@ async def update_discovery_engine( """ @distributed_trace_async - @api_version_validation( - method_added_on="2025-12-01-preview", - params_added_on={ - "2025-12-01-preview": ["api_version", "project_name", "investigation_name", "content_type", "accept"] - }, - api_versions_list=["2025-12-01-preview", "2026-02-01-preview"], - ) async def update_discovery_engine( self, project_name: str, investigation_name: str, - body: Union[_models.DiscoveryEngineUpdate, JSON, IO[bytes]], + body: Union[_models.DiscoveryEngineUpdate, _types.DiscoveryEngineUpdate, IO[bytes]], **kwargs: Any ) -> _models.DiscoveryEngine: """Update the discovery engine for an investigation. This will create the discovery engine if it @@ -1158,9 +1164,9 @@ async def update_discovery_engine( :param investigation_name: The investigation name. Required. :type investigation_name: str :param body: The discovery engine update request. This will create the discovery engine if it - does not already exist. Is one of the following types: DiscoveryEngineUpdate, JSON, IO[bytes] - Required. - :type body: ~azure.ai.discovery.models.DiscoveryEngineUpdate or JSON or IO[bytes] + does not already exist. Is either a DiscoveryEngineUpdate type or a IO[bytes] type. Required. + :type body: ~azure.ai.discovery.models.DiscoveryEngineUpdate or + ~azure.ai.discovery.types.DiscoveryEngineUpdate or IO[bytes] :return: DiscoveryEngine. The DiscoveryEngine is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.DiscoveryEngine :raises ~azure.core.exceptions.HttpResponseError: @@ -1334,12 +1340,12 @@ async def create( @overload async def create( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, body: _types.CreateRequest, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Conversation: """Creates a Conversation. :param body: Required. - :type body: JSON + :type body: ~azure.ai.discovery.types.CreateRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1367,7 +1373,7 @@ async def create( @distributed_trace_async async def create( self, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.CreateRequest, IO[bytes]] = _Unset, *, project_name: str = _Unset, investigation_name: Optional[str] = None, @@ -1376,8 +1382,8 @@ async def create( ) -> _models.Conversation: """Creates a Conversation. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, CreateRequest, IO[bytes] Required. + :type body: JSON or ~azure.ai.discovery.types.CreateRequest or IO[bytes] :keyword project_name: The name of the associated Project. Required. :paramtype project_name: str :keyword investigation_name: The Name of the associated Investigation. Default value is None. @@ -1454,7 +1460,7 @@ async def create( return deserialized # type: ignore @overload - async def update( + async def stable_update( self, conversation_name: str, resource: _models.Conversation, @@ -1477,10 +1483,10 @@ async def update( """ @overload - async def update( + async def stable_update( self, conversation_name: str, - resource: JSON, + resource: _types.Conversation, *, content_type: str = "application/merge-patch+json", **kwargs: Any @@ -1490,7 +1496,7 @@ async def update( :param conversation_name: The conversation name. Required. :type conversation_name: str :param resource: The resource instance. Required. - :type resource: JSON + :type resource: ~azure.ai.discovery.types.Conversation :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1500,7 +1506,7 @@ async def update( """ @overload - async def update( + async def stable_update( self, conversation_name: str, resource: IO[bytes], @@ -1523,16 +1529,25 @@ async def update( """ @distributed_trace_async - async def update( - self, conversation_name: str, resource: Union[_models.Conversation, JSON, IO[bytes]], **kwargs: Any + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "conversation_name", "content_type", "accept"]}, + api_versions_list=["2026-06-01"], + ) + async def stable_update( + self, + conversation_name: str, + resource: Union[_models.Conversation, _types.Conversation, IO[bytes]], + **kwargs: Any ) -> _models.Conversation: """Updates a Conversation. :param conversation_name: The conversation name. Required. :type conversation_name: str - :param resource: The resource instance. Is one of the following types: Conversation, JSON, - IO[bytes] Required. - :type resource: ~azure.ai.discovery.models.Conversation or JSON or IO[bytes] + :param resource: The resource instance. Is either a Conversation type or a IO[bytes] type. + Required. + :type resource: ~azure.ai.discovery.models.Conversation or + ~azure.ai.discovery.types.Conversation or IO[bytes] :return: Conversation. The Conversation is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.Conversation :raises ~azure.core.exceptions.HttpResponseError: @@ -1558,7 +1573,7 @@ async def update( else: _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_conversations_update_request( + _request = build_conversations_stable_update_request( conversation_name=conversation_name, content_type=content_type, api_version=self._config.api_version, @@ -1579,7 +1594,7 @@ async def update( response = pipeline_response.http_response - if response.status_code not in [200, 201]: + if response.status_code not in [200]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -1647,14 +1662,32 @@ async def delete(self, conversation_name: str, **kwargs: Any) -> None: return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={ + "2026-06-01": [ + "api_version", + "investigation_name", + "project_name", + "created_since", + "top", + "skip", + "maxpagesize", + "accept", + ] + }, + api_versions_list=["2026-06-01"], + ) async def list( self, *, investigation_name: Optional[str] = None, project_name: Optional[str] = None, created_since: Optional[datetime.datetime] = None, + top: Optional[int] = None, + skip: Optional[int] = None, **kwargs: Any - ) -> List[_models.Conversation]: + ) -> _models.PagedConversation: """List Conversation resources. :keyword investigation_name: The name of the associated Investigation. Default value is None. @@ -1663,8 +1696,12 @@ async def list( :paramtype project_name: str :keyword created_since: The oldest creation timestamp to keep. Default value is None. :paramtype created_since: ~datetime.datetime - :return: list of Conversation - :rtype: list[~azure.ai.discovery.models.Conversation] + :keyword top: The number of result items to return. Default value is None. + :paramtype top: int + :keyword skip: The number of result items to skip. Default value is None. + :paramtype skip: int + :return: PagedConversation. The PagedConversation is compatible with MutableMapping + :rtype: ~azure.ai.discovery.models.PagedConversation :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1678,12 +1715,16 @@ async def list( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.Conversation]] = kwargs.pop("cls", None) + maxpagesize = kwargs.pop("maxpagesize", None) + cls: ClsType[_models.PagedConversation] = kwargs.pop("cls", None) _request = build_conversations_list_request( investigation_name=investigation_name, project_name=project_name, created_since=created_since, + top=top, + skip=skip, + maxpagesize=maxpagesize, api_version=self._config.api_version, headers=_headers, params=_params, @@ -1713,7 +1754,7 @@ async def list( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(List[_models.Conversation], response.json()) + deserialized = _deserialize(_models.PagedConversation, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -1739,10 +1780,6 @@ def __init__(self, *args, **kwargs) -> None: self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace_async - @api_version_validation( - params_added_on={"2026-02-01-preview": ["log_count"]}, - api_versions_list=["2025-07-01-preview", "2025-12-01-preview", "2026-02-01-preview"], - ) async def get_run_status( self, project_name: str, operation_id: str, *, log_count: Optional[int] = None, **kwargs: Any ) -> _models.OperationStatusRunResultError: @@ -1815,7 +1852,7 @@ async def get_run_status( async def _run_initial( self, project_name: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.RunRequest, IO[bytes]] = _Unset, *, tool_id: str = _Unset, node_pool_ids: List[str] = _Unset, @@ -1950,25 +1987,26 @@ async def begin_run( Our parsing includes the following limited interpretation of special characters: - * The only special characters are " ' and \\. - * Backslashes `\\` escape the next character if that character is a special character, - preserving its literal value. - * Double quotes `"` preserve everything inside them literally, with the exception of the - characters " and \\, which must be escaped with a backslash `\\`. Unmatched quotes will throw - an error. - * Single quotes `'` preserve everything inside them literally. A single-quote cannot occur - within single-quotes. Unmatched quotes will throw an error. - - If you wish to run a command that relies on shell features such as globbing or output - redirection, you either need to: - - * use a container with an entrypoint that is a shell (e.g. `/bin/sh` or `/bin/bash`) and pass - a command which is valid for that shell e.g. - `-c 'python /code/wrapper.py --input /inputs/abcdef-input-1/* --output - /outputs/abcdef-output-1'` - * use a container which has a shell installed, and include the shell in the command, e.g. - `sh -c "python /code/wrapper.py --input /inputs/abcdef-input-1/* --output - /outputs/abcdef-output-1"`. Default value is None. + * The only special characters are the double-quote, the single-quote, and the + backslash. + * A backslash escapes the next character if that character is a special + character, preserving its literal value. + * Double-quotes preserve everything inside them literally, with the exception of + the double-quote and backslash characters, which must be escaped with a + backslash. Unmatched quotes will throw an error. + * Single-quotes preserve everything inside them literally. A single-quote cannot + occur within single-quotes. Unmatched quotes will throw an error. + + If you wish to run a command that relies on shell features such as globbing or + output redirection, you either need to: + + * use a container with an entrypoint that is a shell (for example, /bin/sh or + /bin/bash) and pass a command which is valid for that shell, for example + -c 'python /code/wrapper.py --input /inputs/abcdef-input-1/* --output + /outputs/abcdef-output-1' + * use a container which has a shell installed, and include the shell in the + command, for example sh -c "python /code/wrapper.py --input + /inputs/abcdef-input-1/* --output /outputs/abcdef-output-1". Default value is None. :paramtype command: str :keyword inline_files: Encoded inline files to be mounted into the container, e.g. for generated code. Default value is None. @@ -1992,14 +2030,14 @@ async def begin_run( @overload async def begin_run( - self, project_name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, project_name: str, body: _types.RunRequest, *, content_type: str = "application/json", **kwargs: Any ) -> AsyncLROPoller[_models.RunResult]: """Run the specified tool in the context of the specified project. :param project_name: Name of the associated Project. Required. :type project_name: str :param body: Required. - :type body: JSON + :type body: ~azure.ai.discovery.types.RunRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2032,7 +2070,7 @@ async def begin_run( async def begin_run( self, project_name: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.RunRequest, IO[bytes]] = _Unset, *, tool_id: str = _Unset, node_pool_ids: List[str] = _Unset, @@ -2048,8 +2086,8 @@ async def begin_run( :param project_name: Name of the associated Project. Required. :type project_name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, RunRequest, IO[bytes] Required. + :type body: JSON or ~azure.ai.discovery.types.RunRequest or IO[bytes] :keyword tool_id: ID of the tool to execute. Required. :paramtype tool_id: str :keyword node_pool_ids: IDs of NodePools to use for this run. Required. @@ -2074,25 +2112,26 @@ async def begin_run( Our parsing includes the following limited interpretation of special characters: - * The only special characters are " ' and \\. - * Backslashes `\\` escape the next character if that character is a special character, - preserving its literal value. - * Double quotes `"` preserve everything inside them literally, with the exception of the - characters " and \\, which must be escaped with a backslash `\\`. Unmatched quotes will throw - an error. - * Single quotes `'` preserve everything inside them literally. A single-quote cannot occur - within single-quotes. Unmatched quotes will throw an error. - - If you wish to run a command that relies on shell features such as globbing or output - redirection, you either need to: - - * use a container with an entrypoint that is a shell (e.g. `/bin/sh` or `/bin/bash`) and pass - a command which is valid for that shell e.g. - `-c 'python /code/wrapper.py --input /inputs/abcdef-input-1/* --output - /outputs/abcdef-output-1'` - * use a container which has a shell installed, and include the shell in the command, e.g. - `sh -c "python /code/wrapper.py --input /inputs/abcdef-input-1/* --output - /outputs/abcdef-output-1"`. Default value is None. + * The only special characters are the double-quote, the single-quote, and the + backslash. + * A backslash escapes the next character if that character is a special + character, preserving its literal value. + * Double-quotes preserve everything inside them literally, with the exception of + the double-quote and backslash characters, which must be escaped with a + backslash. Unmatched quotes will throw an error. + * Single-quotes preserve everything inside them literally. A single-quote cannot + occur within single-quotes. Unmatched quotes will throw an error. + + If you wish to run a command that relies on shell features such as globbing or + output redirection, you either need to: + + * use a container with an entrypoint that is a shell (for example, /bin/sh or + /bin/bash) and pass a command which is valid for that shell, for example + -c 'python /code/wrapper.py --input /inputs/abcdef-input-1/* --output + /outputs/abcdef-output-1' + * use a container which has a shell installed, and include the shell in the + command, for example sh -c "python /code/wrapper.py --input + /inputs/abcdef-input-1/* --output /outputs/abcdef-output-1". Default value is None. :paramtype command: str :keyword inline_files: Encoded inline files to be mounted into the container, e.g. for generated code. Default value is None. @@ -2178,18 +2217,14 @@ def get_long_running_output(pipeline_response): self._client, raw_result, get_long_running_output, polling_method # type: ignore ) - @distributed_trace_async - async def cancel_run(self, project_name: str, operation_id: str, **kwargs: Any) -> None: - """Cancel an ongoing tool run. - - :param project_name: Name of the associated Project. Required. - :type project_name: str - :param operation_id: ID of the operation to cancel. Required. - :type operation_id: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "project_name", "operation_id", "accept"]}, + api_versions_list=["2026-06-01"], + ) + async def _cancel_run_lro_initial( + self, project_name: str, operation_id: str, **kwargs: Any + ) -> AsyncIterator[bytes]: error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -2201,9 +2236,9 @@ async def cancel_run(self, project_name: str, operation_id: str, **kwargs: Any) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) - _request = build_tools_cancel_run_request( + _request = build_tools_cancel_run_lro_request( project_name=project_name, operation_id=operation_id, api_version=self._config.api_version, @@ -2215,7 +2250,8 @@ async def cancel_run(self, project_name: str, operation_id: str, **kwargs: Any) } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -2223,40 +2259,115 @@ async def cancel_run(self, project_name: str, operation_id: str, **kwargs: Any) response = pipeline_response.http_response if response.status_code not in [202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) + response_headers = {} + response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + if cls: - return cls(pipeline_response, None, {}) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace_async @api_version_validation( - method_added_on="2025-12-01-preview", - params_added_on={ - "2025-12-01-preview": ["api_version", "project_name", "skip", "top", "max_page_size", "accept"] - }, - api_versions_list=["2025-12-01-preview", "2026-02-01-preview"], + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "project_name", "operation_id", "accept"]}, + api_versions_list=["2026-06-01"], + ) + async def begin_cancel_run_lro( + self, project_name: str, operation_id: str, **kwargs: Any + ) -> AsyncLROPoller[_models.RunResult]: + """Cancel an ongoing tool run. + + :param project_name: Name of the associated Project. Required. + :type project_name: str + :param operation_id: ID of the operation to cancel. Required. + :type operation_id: str + :return: An instance of AsyncLROPoller that returns RunResult. The RunResult is compatible with + MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.ai.discovery.models.RunResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.RunResult] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._cancel_run_lro_initial( + project_name=project_name, + operation_id=operation_id, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response_headers = {} + response = pipeline_response.http_response + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + deserialized = _deserialize(_models.RunResult, response.json().get("result", {})) + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + return deserialized + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, + AsyncLROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs), + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.RunResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.RunResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace_async + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "project_name", "top", "skip", "maxpagesize", "accept"]}, + api_versions_list=["2026-06-01"], ) async def get_operations( - self, - project_name: str, - *, - skip: Optional[int] = None, - top: Optional[int] = None, - max_page_size: Optional[int] = None, - **kwargs: Any + self, project_name: str, *, top: Optional[int] = None, skip: Optional[int] = None, **kwargs: Any ) -> _models.PagedOperation: """List tool runs. :param project_name: Name of the associated Project. Required. :type project_name: str - :keyword skip: Skip results (pagination control). Default value is None. - :paramtype skip: int - :keyword top: Query the top results (pagination control). Default value is None. + :keyword top: The number of result items to return. Default value is None. :paramtype top: int - :keyword max_page_size: Bound the number of results that come back in one response (pagination - control). Default value is None. - :paramtype max_page_size: int + :keyword skip: The number of result items to skip. Default value is None. + :paramtype skip: int :return: PagedOperation. The PagedOperation is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.PagedOperation :raises ~azure.core.exceptions.HttpResponseError: @@ -2272,13 +2383,14 @@ async def get_operations( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} + maxpagesize = kwargs.pop("maxpagesize", None) cls: ClsType[_models.PagedOperation] = kwargs.pop("cls", None) _request = build_tools_get_operations_request( project_name=project_name, - skip=skip, top=top, - max_page_size=max_page_size, + skip=skip, + maxpagesize=maxpagesize, api_version=self._config.api_version, headers=_headers, params=_params, @@ -2316,11 +2428,6 @@ async def get_operations( return deserialized # type: ignore @distributed_trace_async - @api_version_validation( - method_added_on="2025-12-01-preview", - params_added_on={"2025-12-01-preview": ["api_version", "project_name", "accept"]}, - api_versions_list=["2025-12-01-preview", "2026-02-01-preview"], - ) async def get_compute_usage(self, project_name: str, **kwargs: Any) -> _models.ComputeUsage: """Examine compute usage. @@ -2526,7 +2633,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -2595,7 +2705,7 @@ async def create( self, project_name: str, investigation_name: str, - body: JSON, + body: _types.Task, *, content_type: str = "application/json", **kwargs: Any @@ -2607,7 +2717,7 @@ async def create( :param investigation_name: The investigation name. Required. :type investigation_name: str :param body: Task creation request. Required. - :type body: JSON + :type body: ~azure.ai.discovery.types.Task :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2644,7 +2754,11 @@ async def create( @distributed_trace_async async def create( - self, project_name: str, investigation_name: str, body: Union[_models.Task, JSON, IO[bytes]], **kwargs: Any + self, + project_name: str, + investigation_name: str, + body: Union[_models.Task, _types.Task, IO[bytes]], + **kwargs: Any ) -> _models.Task: """Create a new task. @@ -2652,9 +2766,8 @@ async def create( :type project_name: str :param investigation_name: The investigation name. Required. :type investigation_name: str - :param body: Task creation request. Is one of the following types: Task, JSON, IO[bytes] - Required. - :type body: ~azure.ai.discovery.models.Task or JSON or IO[bytes] + :param body: Task creation request. Is either a Task type or a IO[bytes] type. Required. + :type body: ~azure.ai.discovery.models.Task or ~azure.ai.discovery.types.Task or IO[bytes] :return: Task. The Task is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.Task :raises ~azure.core.exceptions.HttpResponseError: @@ -2722,7 +2835,7 @@ async def create( return deserialized # type: ignore @overload - async def update( + async def stable_update( self, project_name: str, investigation_name: str, @@ -2752,12 +2865,12 @@ async def update( """ @overload - async def update( + async def stable_update( self, project_name: str, investigation_name: str, task_name: str, - resource: JSON, + resource: _types.Task, *, content_type: str = "application/merge-patch+json", **kwargs: Any @@ -2772,7 +2885,7 @@ async def update( :param task_name: The unique identifier of the task. Required. :type task_name: str :param resource: The resource instance. Required. - :type resource: JSON + :type resource: ~azure.ai.discovery.types.Task :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -2782,7 +2895,7 @@ async def update( """ @overload - async def update( + async def stable_update( self, project_name: str, investigation_name: str, @@ -2812,12 +2925,19 @@ async def update( """ @distributed_trace_async - async def update( + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={ + "2026-06-01": ["api_version", "project_name", "investigation_name", "task_name", "content_type", "accept"] + }, + api_versions_list=["2026-06-01"], + ) + async def stable_update( self, project_name: str, investigation_name: str, task_name: str, - resource: Union[_models.Task, JSON, IO[bytes]], + resource: Union[_models.Task, _types.Task, IO[bytes]], **kwargs: Any ) -> _models.Task: """Patch (partial update) a task (e.g. status, description, validation requirements, dependencies, @@ -2829,9 +2949,8 @@ async def update( :type investigation_name: str :param task_name: The unique identifier of the task. Required. :type task_name: str - :param resource: The resource instance. Is one of the following types: Task, JSON, IO[bytes] - Required. - :type resource: ~azure.ai.discovery.models.Task or JSON or IO[bytes] + :param resource: The resource instance. Is either a Task type or a IO[bytes] type. Required. + :type resource: ~azure.ai.discovery.models.Task or ~azure.ai.discovery.types.Task or IO[bytes] :return: Task. The Task is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.Task :raises ~azure.core.exceptions.HttpResponseError: @@ -2857,7 +2976,7 @@ async def update( else: _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_tasks_update_request( + _request = build_tasks_stable_update_request( project_name=project_name, investigation_name=investigation_name, task_name=task_name, @@ -2880,7 +2999,7 @@ async def update( response = pipeline_response.http_response - if response.status_code not in [200, 201]: + if response.status_code not in [200]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -2988,7 +3107,7 @@ async def start( project_name: str, investigation_name: str, task_name: str, - body: Optional[JSON] = None, + body: Optional[_types.StartTaskRequest] = None, *, content_type: str = "application/json", **kwargs: Any @@ -3002,7 +3121,7 @@ async def start( :param task_name: The task name. Required. :type task_name: str :param body: Start task request body. Default value is None. - :type body: JSON + :type body: ~azure.ai.discovery.types.StartTaskRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3046,7 +3165,7 @@ async def start( project_name: str, investigation_name: str, task_name: str, - body: Optional[Union[_models.StartTaskRequest, JSON, IO[bytes]]] = None, + body: Optional[Union[_models.StartTaskRequest, _types.StartTaskRequest, IO[bytes]]] = None, **kwargs: Any ) -> _models.Task: """Start execution of a task. @@ -3057,9 +3176,10 @@ async def start( :type investigation_name: str :param task_name: The task name. Required. :type task_name: str - :param body: Start task request body. Is one of the following types: StartTaskRequest, JSON, - IO[bytes] Default value is None. - :type body: ~azure.ai.discovery.models.StartTaskRequest or JSON or IO[bytes] + :param body: Start task request body. Is either a StartTaskRequest type or a IO[bytes] type. + Default value is None. + :type body: ~azure.ai.discovery.models.StartTaskRequest or + ~azure.ai.discovery.types.StartTaskRequest or IO[bytes] :return: Task. The Task is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.Task :raises ~azure.core.exceptions.HttpResponseError: @@ -3134,9 +3254,9 @@ async def start( @overload async def add_comment( self, - task_name: str, project_name: str, investigation_name: str, + task_name: str, body: _models.TaskComment, *, content_type: str = "application/json", @@ -3144,12 +3264,12 @@ async def add_comment( ) -> _models.Task: """Add a comment to a task. - :param task_name: The task name. Required. - :type task_name: str :param project_name: The project name. Required. :type project_name: str :param investigation_name: The investigation name. Required. :type investigation_name: str + :param task_name: The task name. Required. + :type task_name: str :param body: Comment to add. Required. :type body: ~azure.ai.discovery.models.TaskComment :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -3163,24 +3283,24 @@ async def add_comment( @overload async def add_comment( self, - task_name: str, project_name: str, investigation_name: str, - body: JSON, + task_name: str, + body: _types.TaskComment, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Task: """Add a comment to a task. - :param task_name: The task name. Required. - :type task_name: str :param project_name: The project name. Required. :type project_name: str :param investigation_name: The investigation name. Required. :type investigation_name: str + :param task_name: The task name. Required. + :type task_name: str :param body: Comment to add. Required. - :type body: JSON + :type body: ~azure.ai.discovery.types.TaskComment :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3192,9 +3312,9 @@ async def add_comment( @overload async def add_comment( self, - task_name: str, project_name: str, investigation_name: str, + task_name: str, body: IO[bytes], *, content_type: str = "application/json", @@ -3202,12 +3322,12 @@ async def add_comment( ) -> _models.Task: """Add a comment to a task. - :param task_name: The task name. Required. - :type task_name: str :param project_name: The project name. Required. :type project_name: str :param investigation_name: The investigation name. Required. :type investigation_name: str + :param task_name: The task name. Required. + :type task_name: str :param body: Comment to add. Required. :type body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. @@ -3221,23 +3341,23 @@ async def add_comment( @distributed_trace_async async def add_comment( self, - task_name: str, project_name: str, investigation_name: str, - body: Union[_models.TaskComment, JSON, IO[bytes]], + task_name: str, + body: Union[_models.TaskComment, _types.TaskComment, IO[bytes]], **kwargs: Any ) -> _models.Task: """Add a comment to a task. - :param task_name: The task name. Required. - :type task_name: str :param project_name: The project name. Required. :type project_name: str :param investigation_name: The investigation name. Required. :type investigation_name: str - :param body: Comment to add. Is one of the following types: TaskComment, JSON, IO[bytes] - Required. - :type body: ~azure.ai.discovery.models.TaskComment or JSON or IO[bytes] + :param task_name: The task name. Required. + :type task_name: str + :param body: Comment to add. Is either a TaskComment type or a IO[bytes] type. Required. + :type body: ~azure.ai.discovery.models.TaskComment or ~azure.ai.discovery.types.TaskComment or + IO[bytes] :return: Task. The Task is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.Task :raises ~azure.core.exceptions.HttpResponseError: @@ -3264,9 +3384,9 @@ async def add_comment( _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_tasks_add_comment_request( - task_name=task_name, project_name=project_name, investigation_name=investigation_name, + task_name=task_name, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -3340,7 +3460,7 @@ async def add_execution_history( project_name: str, investigation_name: str, task_name: str, - body: JSON, + body: _types.ExecutionHistoryEntry, *, content_type: str = "application/json", **kwargs: Any @@ -3354,7 +3474,7 @@ async def add_execution_history( :param task_name: The task name. Required. :type task_name: str :param body: Execution history entry to add. Required. - :type body: JSON + :type body: ~azure.ai.discovery.types.ExecutionHistoryEntry :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3398,7 +3518,7 @@ async def add_execution_history( project_name: str, investigation_name: str, task_name: str, - body: Union[_models.ExecutionHistoryEntry, JSON, IO[bytes]], + body: Union[_models.ExecutionHistoryEntry, _types.ExecutionHistoryEntry, IO[bytes]], **kwargs: Any ) -> _models.Task: """Add an execution history entry to a task. @@ -3409,9 +3529,10 @@ async def add_execution_history( :type investigation_name: str :param task_name: The task name. Required. :type task_name: str - :param body: Execution history entry to add. Is one of the following types: - ExecutionHistoryEntry, JSON, IO[bytes] Required. - :type body: ~azure.ai.discovery.models.ExecutionHistoryEntry or JSON or IO[bytes] + :param body: Execution history entry to add. Is either a ExecutionHistoryEntry type or a + IO[bytes] type. Required. + :type body: ~azure.ai.discovery.models.ExecutionHistoryEntry or + ~azure.ai.discovery.types.ExecutionHistoryEntry or IO[bytes] :return: Task. The Task is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.Task :raises ~azure.core.exceptions.HttpResponseError: @@ -3478,3 +3599,1200 @@ async def add_execution_history( return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + + +class KnowledgeBasesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.discovery.aio.BookshelfClient`'s + :attr:`knowledge_bases` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: AsyncPipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: BookshelfClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "knowledge_base_name", "content_type", "accept"]}, + api_versions_list=["2026-06-01"], + ) + async def _create_or_update_initial( + self, + knowledge_base_name: str, + resource: Union[_models.KnowledgeBase, _types.KnowledgeBase, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/merge-patch+json" + _content = None + if isinstance(resource, (IOBase, bytes)): + _content = resource + else: + _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_knowledge_bases_create_or_update_request( + knowledge_base_name=knowledge_base_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_create_or_update( + self, + knowledge_base_name: str, + resource: _models.KnowledgeBase, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> AsyncLROPoller[_models.KnowledgeBase]: + """Creates or updates a KnowledgeBase. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param resource: The resource instance. Required. + :type resource: ~azure.ai.discovery.models.KnowledgeBase + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/merge-patch+json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns KnowledgeBase. The KnowledgeBase is + compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.ai.discovery.models.KnowledgeBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + knowledge_base_name: str, + resource: _types.KnowledgeBase, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> AsyncLROPoller[_models.KnowledgeBase]: + """Creates or updates a KnowledgeBase. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param resource: The resource instance. Required. + :type resource: ~azure.ai.discovery.types.KnowledgeBase + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/merge-patch+json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns KnowledgeBase. The KnowledgeBase is + compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.ai.discovery.models.KnowledgeBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_create_or_update( + self, + knowledge_base_name: str, + resource: IO[bytes], + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> AsyncLROPoller[_models.KnowledgeBase]: + """Creates or updates a KnowledgeBase. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param resource: The resource instance. Required. + :type resource: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/merge-patch+json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns KnowledgeBase. The KnowledgeBase is + compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.ai.discovery.models.KnowledgeBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "knowledge_base_name", "content_type", "accept"]}, + api_versions_list=["2026-06-01"], + ) + async def begin_create_or_update( + self, + knowledge_base_name: str, + resource: Union[_models.KnowledgeBase, _types.KnowledgeBase, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[_models.KnowledgeBase]: + """Creates or updates a KnowledgeBase. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param resource: The resource instance. Is either a KnowledgeBase type or a IO[bytes] type. + Required. + :type resource: ~azure.ai.discovery.models.KnowledgeBase or + ~azure.ai.discovery.types.KnowledgeBase or IO[bytes] + :return: An instance of AsyncLROPoller that returns KnowledgeBase. The KnowledgeBase is + compatible with MutableMapping + :rtype: ~azure.core.polling.AsyncLROPoller[~azure.ai.discovery.models.KnowledgeBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.KnowledgeBase] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._create_or_update_initial( + knowledge_base_name=knowledge_base_name, + resource=resource, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response_headers = {} + response = pipeline_response.http_response + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + deserialized = _deserialize(_models.KnowledgeBase, response.json()) + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + return deserialized + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, + AsyncLROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs), + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[_models.KnowledgeBase].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.KnowledgeBase]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace_async + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "knowledge_base_name", "accept"]}, + api_versions_list=["2026-06-01"], + ) + async def get(self, knowledge_base_name: str, **kwargs: Any) -> _models.KnowledgeBase: + """Fetch a KnowledgeBase by name. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.ai.discovery.models.KnowledgeBase + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.KnowledgeBase] = kwargs.pop("cls", None) + + _request = build_knowledge_bases_get_request( + knowledge_base_name=knowledge_base_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.KnowledgeBase, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncItemPaged["_models.KnowledgeBase"]: + """List KnowledgeBase resources. + + :return: An iterator like instance of KnowledgeBase + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.discovery.models.KnowledgeBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.KnowledgeBase]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_knowledge_bases_list_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.KnowledgeBase], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "knowledge_base_name", "operation_id", "accept"]}, + api_versions_list=["2026-06-01"], + ) + async def get_operation_status( + self, knowledge_base_name: str, operation_id: str, **kwargs: Any + ) -> _models.KnowledgeBaseOperationResponse: + """Get the status of a long-running operation. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param operation_id: The unique ID of the operation. Required. + :type operation_id: str + :return: KnowledgeBaseOperationResponse. The KnowledgeBaseOperationResponse is compatible with + MutableMapping + :rtype: ~azure.ai.discovery.models.KnowledgeBaseOperationResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.KnowledgeBaseOperationResponse] = kwargs.pop("cls", None) + + _request = build_knowledge_bases_get_operation_status_request( + knowledge_base_name=knowledge_base_name, + operation_id=operation_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.KnowledgeBaseOperationResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={ + "2026-06-01": [ + "api_version", + "knowledge_base_name", + "repeatability_request_id", + "repeatability_first_sent", + "client_request_id", + "content_type", + "accept", + ] + }, + api_versions_list=["2026-06-01"], + ) + async def _start_indexing_initial( + self, + knowledge_base_name: str, + body: Union[JSON, _types.StartIndexingRequest, IO[bytes]] = _Unset, + *, + node_pool_id: Optional[str] = None, + project_id: Optional[str] = None, + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + if body is _Unset: + body = {"nodePoolId": node_pool_id, "projectId": project_id} + body = {k: v for k, v in body.items() if v is not None} + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_knowledge_bases_start_indexing_request( + knowledge_base_name=knowledge_base_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) + response_headers["Repeatability-Result"] = self._deserialize( + "str", response.headers.get("Repeatability-Result") + ) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_start_indexing( + self, + knowledge_base_name: str, + *, + content_type: str = "application/json", + node_pool_id: Optional[str] = None, + project_id: Optional[str] = None, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Start indexing. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword node_pool_id: Node pool ID. Default value is None. + :paramtype node_pool_id: str + :keyword project_id: Project ID. Default value is None. + :paramtype project_id: str + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_start_indexing( + self, + knowledge_base_name: str, + body: _types.StartIndexingRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Start indexing. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param body: Required. + :type body: ~azure.ai.discovery.types.StartIndexingRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_start_indexing( + self, knowledge_base_name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[None]: + """Start indexing. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={ + "2026-06-01": [ + "api_version", + "knowledge_base_name", + "repeatability_request_id", + "repeatability_first_sent", + "client_request_id", + "content_type", + "accept", + ] + }, + api_versions_list=["2026-06-01"], + ) + async def begin_start_indexing( + self, + knowledge_base_name: str, + body: Union[JSON, _types.StartIndexingRequest, IO[bytes]] = _Unset, + *, + node_pool_id: Optional[str] = None, + project_id: Optional[str] = None, + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Start indexing. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param body: Is one of the following types: JSON, StartIndexingRequest, IO[bytes] Required. + :type body: JSON or ~azure.ai.discovery.types.StartIndexingRequest or IO[bytes] + :keyword node_pool_id: Node pool ID. Default value is None. + :paramtype node_pool_id: str + :keyword project_id: Project ID. Default value is None. + :paramtype project_id: str + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._start_indexing_initial( + knowledge_base_name=knowledge_base_name, + body=body, + node_pool_id=node_pool_id, + project_id=project_id, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, + AsyncLROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs), + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={ + "2026-06-01": [ + "api_version", + "knowledge_base_name", + "repeatability_request_id", + "repeatability_first_sent", + "client_request_id", + "accept", + ] + }, + api_versions_list=["2026-06-01"], + ) + async def _cancel_indexing_initial(self, knowledge_base_name: str, **kwargs: Any) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_knowledge_bases_cancel_indexing_request( + knowledge_base_name=knowledge_base_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) + response_headers["Repeatability-Result"] = self._deserialize( + "str", response.headers.get("Repeatability-Result") + ) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={ + "2026-06-01": [ + "api_version", + "knowledge_base_name", + "repeatability_request_id", + "repeatability_first_sent", + "client_request_id", + "accept", + ] + }, + api_versions_list=["2026-06-01"], + ) + async def begin_cancel_indexing(self, knowledge_base_name: str, **kwargs: Any) -> AsyncLROPoller[None]: + """Cancel indexing. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._cancel_indexing_initial( + knowledge_base_name=knowledge_base_name, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, + AsyncLROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs), + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={ + "2026-06-01": [ + "api_version", + "knowledge_base_name", + "repeatability_request_id", + "repeatability_first_sent", + "client_request_id", + "content_type", + "accept", + ] + }, + api_versions_list=["2026-06-01"], + ) + async def _search_initial( + self, + knowledge_base_name: str, + body: Union[_models.SearchRequest, _types.SearchRequest, IO[bytes]], + **kwargs: Any + ) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_knowledge_bases_search_request( + knowledge_base_name=knowledge_base_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def begin_search( + self, + knowledge_base_name: str, + body: _models.SearchRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Search the knowledge base. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param body: The search request body. Required. + :type body: ~azure.ai.discovery.models.SearchRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_search( + self, + knowledge_base_name: str, + body: _types.SearchRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Search the knowledge base. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param body: The search request body. Required. + :type body: ~azure.ai.discovery.types.SearchRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def begin_search( + self, knowledge_base_name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[None]: + """Search the knowledge base. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param body: The search request body. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={ + "2026-06-01": [ + "api_version", + "knowledge_base_name", + "repeatability_request_id", + "repeatability_first_sent", + "client_request_id", + "content_type", + "accept", + ] + }, + api_versions_list=["2026-06-01"], + ) + async def begin_search( + self, + knowledge_base_name: str, + body: Union[_models.SearchRequest, _types.SearchRequest, IO[bytes]], + **kwargs: Any + ) -> AsyncLROPoller[None]: + """Search the knowledge base. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param body: The search request body. Is either a SearchRequest type or a IO[bytes] type. + Required. + :type body: ~azure.ai.discovery.models.SearchRequest or ~azure.ai.discovery.types.SearchRequest + or IO[bytes] + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._search_initial( + knowledge_base_name=knowledge_base_name, + body=body, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, + AsyncLROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs), + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "knowledge_base_name", "accept"]}, + api_versions_list=["2026-06-01"], + ) + async def _delete_initial(self, knowledge_base_name: str, **kwargs: Any) -> AsyncIterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[AsyncIterator[bytes]] = kwargs.pop("cls", None) + + _request = build_knowledge_bases_delete_request( + knowledge_base_name=knowledge_base_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "knowledge_base_name", "accept"]}, + api_versions_list=["2026-06-01"], + ) + async def begin_delete(self, knowledge_base_name: str, **kwargs: Any) -> AsyncLROPoller[None]: + """Delete a KnowledgeBase. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :return: An instance of AsyncLROPoller that returns None + :rtype: ~azure.core.polling.AsyncLROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, AsyncPollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = await self._delete_initial( + knowledge_base_name=knowledge_base_name, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + await raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + if polling is True: + polling_method: AsyncPollingMethod = cast( + AsyncPollingMethod, + AsyncLROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs), + ) + elif polling is False: + polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + else: + polling_method = polling + if cont_token: + return AsyncLROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/operations/_patch.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/operations/_patch.py new file mode 100644 index 000000000000..c0ae50a82c4d --- /dev/null +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/aio/operations/_patch.py @@ -0,0 +1,115 @@ +# 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 +""" + +from typing import Any, IO, Union + +from azure.core.polling import AsyncLROPoller +from azure.core.polling.async_base_polling import AsyncLROBasePolling +from azure.core.polling.base_polling import ( + BadResponse, + OperationResourcePolling, + _as_json, + _is_empty, +) + +from ... import models as _models +from ._operations import KnowledgeBasesOperations as _GeneratedKnowledgeBasesOperations + + +class _ProvisioningStatePolling(OperationResourcePolling): + """LRO polling that terminates on ``provisioningState`` instead of ``status``. + + See the sync ``operations/_patch.py`` for the full rationale: the Bookshelf + create/update LRO returns the ``KnowledgeBase`` resource, whose ``status`` + field is the *indexing* lifecycle (``NotStarted`` for a new KB and never + create-terminal). The correct create/update completion signal is + ``provisioningState`` (``Accepted`` -> ``Succeeded``). The polling algorithm + is transport-agnostic, so the same class is reused by the async poller. + """ + + def get_status(self, pipeline_response: Any) -> str: + response = pipeline_response.http_response + if _is_empty(response): + raise BadResponse("The response from long running operation does not contain a body.") + body = _as_json(response) + status = body.get("provisioningState") or body.get("status") + if not status: + raise BadResponse("No provisioningState or status found in long running operation response.") + return status + + +class _AsyncCreateOrUpdatePolling(AsyncLROBasePolling): + """Async create/update poller that tolerates a synchronous completion. + + See the sync ``operations/_patch.py`` for the rationale: creating a new KB is + an LRO (``201`` + ``Operation-Location``), but updating an existing KB can + complete synchronously (``200`` with no ``Operation-Location``), which the + default poller rejects with ``BadResponse: Unable to find status link for + polling``. This poller treats a missing status link as immediate success. + """ + + _synchronous: bool = False + + def initialize(self, client: Any, initial_response: Any, deserialization_callback: Any) -> None: + headers = initial_response.http_response.headers + if not (headers.get("Operation-Location") or headers.get("operation-location")): + self._client = client + self._pipeline_response = initial_response + self._initial_response = initial_response + self._deserialization_callback = deserialization_callback + self._operation = _ProvisioningStatePolling() + self._status = "Succeeded" + self._synchronous = True + return + self._synchronous = False + super().initialize(client, initial_response, deserialization_callback) + + async def run(self) -> None: + if getattr(self, "_synchronous", False): + return + await super().run() + + +class KnowledgeBasesOperations(_GeneratedKnowledgeBasesOperations): + """Async KnowledgeBases operations with a corrected create/update LRO poller.""" + + async def begin_create_or_update( # type: ignore[override] + self, + knowledge_base_name: str, + resource: Union[_models.KnowledgeBase, "dict[str, Any]", IO[bytes]], + **kwargs: Any, + ) -> AsyncLROPoller[_models.KnowledgeBase]: + # Only override the default poller; honor an explicitly supplied + # ``polling`` value (``False`` or a custom ``AsyncPollingMethod``). + if kwargs.get("polling", True) is True: + lro_delay = kwargs.get("polling_interval", self._config.polling_interval) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + kwargs["polling"] = _AsyncCreateOrUpdatePolling( + lro_delay, + lro_algorithms=[_ProvisioningStatePolling()], + path_format_arguments=path_format_arguments, + ) + return await super().begin_create_or_update(knowledge_base_name, resource, **kwargs) # type: ignore[arg-type] + + +__all__: list[str] = [ + "KnowledgeBasesOperations", +] # 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/discovery/azure-ai-discovery/azure/ai/discovery/models.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/models.py deleted file mode 100644 index 59527eec6f03..000000000000 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/models.py +++ /dev/null @@ -1,103 +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. -# -------------------------------------------------------------------------- - -"""Merged models from both Workspace and Bookshelf sub-clients.""" - -from ._workspace.azure.ai.discovery.models import ( # type: ignore - ByType, - ComputeUsage, - Conversation, - DiscoveryEngine, - DiscoveryEngineStatus, - DiscoveryEngineUpdate, - ExecutionHistoryEntry, - InfraOverrides, - InlineFile, - InputDataMount, - Investigation, - InvestigationStatus, - NodepoolUsage, - Operation, - OperationState, - OperationStatusRunResultError, - OutputDataMount, - OutputDataUri, - PagedOperation, - PagedWorkingMemoryEntry, - ResourceOperationStatusInvestigationInvestigationError, - RunRequestEnvironmentVariable, - RunResult, - RunResultToolReport, - RunStatus, - StartTaskRequest, - SupercomputerUsage, - Tag, - Task, - TaskAssignee, - TaskComment, - TaskPriority, - TaskResult, - TaskStatus, - WorkingMemoryEntry, - WorkingMemoryEntryType, -) -from ._bookshelf.azure.ai.discovery.models import ( # type: ignore - IndexingStatus, - KnowledgeBase, - KnowledgeBaseOperationStatus, - KnowledgeBaseVersion, - ProvisioningState, - RepeatabilityResult, - StorageAssetReference, -) - -__all__ = [ - # Workspace models - "ByType", - "ComputeUsage", - "Conversation", - "DiscoveryEngine", - "DiscoveryEngineStatus", - "DiscoveryEngineUpdate", - "ExecutionHistoryEntry", - "InfraOverrides", - "InlineFile", - "InputDataMount", - "Investigation", - "InvestigationStatus", - "NodepoolUsage", - "Operation", - "OperationState", - "OperationStatusRunResultError", - "OutputDataMount", - "OutputDataUri", - "PagedOperation", - "PagedWorkingMemoryEntry", - "ResourceOperationStatusInvestigationInvestigationError", - "RunRequestEnvironmentVariable", - "RunResult", - "RunResultToolReport", - "RunStatus", - "StartTaskRequest", - "SupercomputerUsage", - "Tag", - "Task", - "TaskAssignee", - "TaskComment", - "TaskPriority", - "TaskResult", - "TaskStatus", - "WorkingMemoryEntry", - "WorkingMemoryEntryType", - # Bookshelf models - "IndexingStatus", - "KnowledgeBase", - "KnowledgeBaseOperationStatus", - "KnowledgeBaseVersion", - "ProvisioningState", - "RepeatabilityResult", - "StorageAssetReference", -] diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/models/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/models/__init__.py similarity index 68% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/models/__init__.py rename to sdk/discovery/azure-ai-discovery/azure/ai/discovery/models/__init__.py index 4e70dd80ecf2..ad68a7c0e6cc 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/models/__init__.py +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/models/__init__.py @@ -14,27 +14,41 @@ from ._models import ( # type: ignore + Citation, ComputeUsage, Conversation, DiscoveryEngine, DiscoveryEngineUpdate, ExecutionHistoryEntry, + IndexingMetrics, + IndexingOperationResult, InfraOverrides, InlineFile, InputDataMount, Investigation, + InvestigationOperationStatus, + KnowledgeBase, + KnowledgeBaseIndexingOperationResponse, + KnowledgeBaseOperationResponse, + KnowledgeBaseSearchOperationResponse, + LastIndexingRun, NodepoolUsage, Operation, OperationStatusRunResultError, OutputDataMount, OutputDataUri, + PagedConversation, + PagedInvestigation, PagedOperation, PagedWorkingMemoryEntry, - ResourceOperationStatusInvestigationInvestigationError, RunRequestEnvironmentVariable, RunResult, RunResultToolReport, + SearchRequest, + SearchResponse, + SearchResultItem, StartTaskRequest, + StorageAssetReference, SupercomputerUsage, Tag, Task, @@ -46,10 +60,16 @@ from ._enums import ( # type: ignore ByType, + CitationType, DiscoveryEngineStatus, + IndexingStatus, InvestigationStatus, + KnowledgeBaseOperationType, OperationState, + ProvisioningState, + RepeatabilityResult, RunStatus, + StorageMountProtocol, TaskPriority, TaskStatus, WorkingMemoryEntryType, @@ -59,27 +79,41 @@ from ._patch import patch_sdk as _patch_sdk __all__ = [ + "Citation", "ComputeUsage", "Conversation", "DiscoveryEngine", "DiscoveryEngineUpdate", "ExecutionHistoryEntry", + "IndexingMetrics", + "IndexingOperationResult", "InfraOverrides", "InlineFile", "InputDataMount", "Investigation", + "InvestigationOperationStatus", + "KnowledgeBase", + "KnowledgeBaseIndexingOperationResponse", + "KnowledgeBaseOperationResponse", + "KnowledgeBaseSearchOperationResponse", + "LastIndexingRun", "NodepoolUsage", "Operation", "OperationStatusRunResultError", "OutputDataMount", "OutputDataUri", + "PagedConversation", + "PagedInvestigation", "PagedOperation", "PagedWorkingMemoryEntry", - "ResourceOperationStatusInvestigationInvestigationError", "RunRequestEnvironmentVariable", "RunResult", "RunResultToolReport", + "SearchRequest", + "SearchResponse", + "SearchResultItem", "StartTaskRequest", + "StorageAssetReference", "SupercomputerUsage", "Tag", "Task", @@ -88,10 +122,16 @@ "TaskResult", "WorkingMemoryEntry", "ByType", + "CitationType", "DiscoveryEngineStatus", + "IndexingStatus", "InvestigationStatus", + "KnowledgeBaseOperationType", "OperationState", + "ProvisioningState", + "RepeatabilityResult", "RunStatus", + "StorageMountProtocol", "TaskPriority", "TaskStatus", "WorkingMemoryEntryType", diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/models/_enums.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/models/_enums.py similarity index 57% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/models/_enums.py rename to sdk/discovery/azure-ai-discovery/azure/ai/discovery/models/_enums.py index dfce262e6c18..b6150af2e015 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/models/_enums.py +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/models/_enums.py @@ -21,6 +21,13 @@ class ByType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The backend system.""" +class CitationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of citation.""" + + FILE_CITATION = "file_citation" + """A file citation.""" + + class DiscoveryEngineStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Discovery Engine Status.""" @@ -30,6 +37,21 @@ class DiscoveryEngineStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Discovery Engine Active.""" +class IndexingStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum for IndexingStatus.""" + + NOT_STARTED = "NotStarted" + """Indexing Not started.""" + RUNNING = "Running" + """Running.""" + SUCCEEDED = "Succeeded" + """Succeeded.""" + CANCELED = "Canceled" + """Canceled.""" + FAILED = "Failed" + """Failed.""" + + class InvestigationStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Status.""" @@ -41,6 +63,19 @@ class InvestigationStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Investigation Failed.""" +class KnowledgeBaseOperationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Status indicating the KnowledgeBase operation.""" + + INDEXING = "Indexing" + """An indexing operation.""" + CANCEL_INDEXING = "CancelIndexing" + """A cancel indexing operation.""" + SEARCH = "Search" + """A search operation.""" + DELETE = "Delete" + """A delete operation.""" + + class OperationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Enum describing allowed operation states.""" @@ -56,6 +91,37 @@ class OperationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The operation has been canceled by the user.""" +class ProvisioningState(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The resource provisioning state.""" + + SUCCEEDED = "Succeeded" + """Resource has been created.""" + FAILED = "Failed" + """Resource creation failed.""" + CANCELED = "Canceled" + """Resource creation was canceled.""" + ACCEPTED = "Accepted" + """The resource create request has been accepted.""" + PROVISIONING = "Provisioning" + """The resource is being provisioned.""" + UPDATING = "Updating" + """The resource is updating.""" + DELETING = "Deleting" + """The resource is being deleted.""" + + +class RepeatabilityResult(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Repeatability Result header options.""" + + ACCEPTED = "accepted" + """If the request was accepted and the server guarantees that the server state reflects a single + execution of the operation.""" + REJECTED = "rejected" + """If the request was rejected because the combination of Repeatability-First-Sent and + Repeatability-Request-ID were invalid or because the Repeatability-First-Sent value was outside + the range of values held by the server.""" + + class RunStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Enum for run status.""" @@ -71,6 +137,15 @@ class RunStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Failed.""" +class StorageMountProtocol(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The protocol to use for mounting an storage container.""" + + NFS = "NFS" + """NFS protocol. Version of NFS used may vary based on storage type.""" + BLOBFUSE_CACHING = "BlobfuseCaching" + """Blobfuse in file cache mode.""" + + class TaskPriority(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Task priority level.""" @@ -112,5 +187,5 @@ class TaskStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): class WorkingMemoryEntryType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Working memory entry type.""" - THOUGHT = "thought" + THOUGHT = "Thought" """Thought.""" diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/models/_models.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/models/_models.py similarity index 63% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/models/_models.py rename to sdk/discovery/azure-ai-discovery/azure/ai/discovery/models/_models.py index 7dd2ae199332..a2d1ad497b81 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/models/_models.py +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/models/_models.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -9,16 +9,67 @@ # pylint: disable=useless-super-delegation import datetime -from typing import Any, Mapping, Optional, TYPE_CHECKING, Union, overload +from typing import Any, Literal, Mapping, Optional, TYPE_CHECKING, Union, overload from azure.core.exceptions import ODataV4Format -from .._utils.model_base import Model as _Model, rest_field +from .._utils.model_base import Model as _Model, rest_discriminator, rest_field +from ._enums import KnowledgeBaseOperationType if TYPE_CHECKING: from .. import models as _models +class Citation(_Model): + """A citation for a generated result. + + :ivar type: The type of citation. Required. "file_citation" + :vartype type: str or ~azure.ai.discovery.models.CitationType + :ivar index: Zero-based index of the citation in the result. + :vartype index: int + :ivar file_name: The source file name. Required. + :vartype file_name: str + :ivar start_offset: Character offset where the cited passage begins. + :vartype start_offset: int + :ivar end_offset: Character offset where the cited passage ends. + :vartype end_offset: int + """ + + type: Union[str, "_models.CitationType"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The type of citation. Required. \"file_citation\"""" + index: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Zero-based index of the citation in the result.""" + file_name: str = rest_field(name="fileName", visibility=["read", "create", "update", "delete", "query"]) + """The source file name. Required.""" + start_offset: Optional[int] = rest_field( + name="startOffset", visibility=["read", "create", "update", "delete", "query"] + ) + """Character offset where the cited passage begins.""" + end_offset: Optional[int] = rest_field(name="endOffset", visibility=["read", "create", "update", "delete", "query"]) + """Character offset where the cited passage ends.""" + + @overload + def __init__( + self, + *, + type: Union[str, "_models.CitationType"], + file_name: str, + index: Optional[int] = None, + start_offset: Optional[int] = None, + end_offset: 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 ComputeUsage(_Model): """Overview of compute usage for a project. @@ -80,21 +131,27 @@ class Conversation(_Model): name: str = rest_field(visibility=["read"]) """The conversation name. Required.""" - created_at: Optional[datetime.datetime] = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + created_at: Optional[datetime.datetime] = rest_field( + name="createdAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) """The timestamp when the resource was created.""" - created_by: Optional[str] = rest_field(name="createdBy", visibility=["read"]) + created_by: Optional[str] = rest_field(name="createdBy", visibility=["read", "create", "update", "delete", "query"]) """The ID of the user who created this resource.""" - created_by_type: Optional[Union[str, "_models.ByType"]] = rest_field(name="createdByType", visibility=["read"]) + created_by_type: Optional[Union[str, "_models.ByType"]] = rest_field( + name="createdByType", visibility=["read", "create", "update", "delete", "query"] + ) """The type of user who created this resource. Known values are: \"User\", \"Application\", and \"System\".""" last_modified_at: Optional[datetime.datetime] = rest_field( - name="lastModifiedAt", visibility=["read"], format="rfc3339" + name="lastModifiedAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" ) """The timestamp when the resource was last updated.""" - last_modified_by: Optional[str] = rest_field(name="lastModifiedBy", visibility=["read"]) + last_modified_by: Optional[str] = rest_field( + name="lastModifiedBy", visibility=["read", "create", "update", "delete", "query"] + ) """The ID of the user who updated this resource.""" last_modified_by_type: Optional[Union[str, "_models.ByType"]] = rest_field( - name="lastModifiedByType", visibility=["read"] + name="lastModifiedByType", visibility=["read", "create", "update", "delete", "query"] ) """The type of user who updated this resource. Known values are: \"User\", \"Application\", and \"System\".""" @@ -109,6 +166,12 @@ class Conversation(_Model): def __init__( self, *, + created_at: Optional[datetime.datetime] = None, + created_by: Optional[str] = None, + created_by_type: Optional[Union[str, "_models.ByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "_models.ByType"]] = None, display_name: Optional[str] = None, investigation_name: Optional[str] = None, project_name: Optional[str] = None, @@ -161,21 +224,27 @@ class DiscoveryEngine(_Model): """The system prompt.""" configuration: Optional[dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The Discovery Engine configuration.""" - created_at: Optional[datetime.datetime] = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + created_at: Optional[datetime.datetime] = rest_field( + name="createdAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) """The timestamp when the resource was created.""" - created_by: Optional[str] = rest_field(name="createdBy", visibility=["read"]) + created_by: Optional[str] = rest_field(name="createdBy", visibility=["read", "create", "update", "delete", "query"]) """The ID of the user who created this resource.""" - created_by_type: Optional[Union[str, "_models.ByType"]] = rest_field(name="createdByType", visibility=["read"]) + created_by_type: Optional[Union[str, "_models.ByType"]] = rest_field( + name="createdByType", visibility=["read", "create", "update", "delete", "query"] + ) """The type of user who created this resource. Known values are: \"User\", \"Application\", and \"System\".""" last_modified_at: Optional[datetime.datetime] = rest_field( - name="lastModifiedAt", visibility=["read"], format="rfc3339" + name="lastModifiedAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" ) """The timestamp when the resource was last updated.""" - last_modified_by: Optional[str] = rest_field(name="lastModifiedBy", visibility=["read"]) + last_modified_by: Optional[str] = rest_field( + name="lastModifiedBy", visibility=["read", "create", "update", "delete", "query"] + ) """The ID of the user who updated this resource.""" last_modified_by_type: Optional[Union[str, "_models.ByType"]] = rest_field( - name="lastModifiedByType", visibility=["read"] + name="lastModifiedByType", visibility=["read", "create", "update", "delete", "query"] ) """The type of user who updated this resource. Known values are: \"User\", \"Application\", and \"System\".""" @@ -187,6 +256,12 @@ def __init__( discovery_engine_status: Union[str, "_models.DiscoveryEngineStatus"], system_prompt: Optional[str] = None, configuration: Optional[dict[str, Any]] = None, + created_at: Optional[datetime.datetime] = None, + created_by: Optional[str] = None, + created_by_type: Optional[Union[str, "_models.ByType"]] = None, + last_modified_at: Optional[datetime.datetime] = None, + last_modified_by: Optional[str] = None, + last_modified_by_type: Optional[Union[str, "_models.ByType"]] = None, ) -> None: ... @overload @@ -204,19 +279,12 @@ class DiscoveryEngineUpdate(_Model): """Discovery Engine Update Request. This will create the discovery engine if it does not already exist. - :ivar discovery_engine_status: The Discovery Engine status. Known values are: "Inactive" and - "Active". - :vartype discovery_engine_status: str or ~azure.ai.discovery.models.DiscoveryEngineStatus :ivar system_prompt: The system prompt. :vartype system_prompt: str :ivar configuration: The Discovery Engine configuration. :vartype configuration: dict[str, any] """ - discovery_engine_status: Optional[Union[str, "_models.DiscoveryEngineStatus"]] = rest_field( - name="discoveryEngineStatus", visibility=["read", "create", "update", "delete", "query"] - ) - """The Discovery Engine status. Known values are: \"Inactive\" and \"Active\".""" system_prompt: Optional[str] = rest_field( name="systemPrompt", visibility=["read", "create", "update", "delete", "query"] ) @@ -228,7 +296,6 @@ class DiscoveryEngineUpdate(_Model): def __init__( self, *, - discovery_engine_status: Optional[Union[str, "_models.DiscoveryEngineStatus"]] = None, system_prompt: Optional[str] = None, configuration: Optional[dict[str, Any]] = None, ) -> None: ... @@ -321,6 +388,118 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class IndexingMetrics(_Model): + """Indexing metrics for a run. + + :ivar documents_processed: The number of documents that were successfully processed. Required. + :vartype documents_processed: int + :ivar documents_failed: The number of documents that failed during indexing. Required. + :vartype documents_failed: int + :ivar documents_total: The total number of documents considered for indexing. Required. + :vartype documents_total: int + :ivar indexing_percentage_complete: The indexing completion percentage from 0 to 100. Required. + :vartype indexing_percentage_complete: int + :ivar enrichment_start_time_utc: The UTC timestamp when enrichment started. + :vartype enrichment_start_time_utc: ~datetime.datetime + :ivar enrichment_end_time_utc: The UTC timestamp when enrichment ended. + :vartype enrichment_end_time_utc: ~datetime.datetime + :ivar indexing_start_time_utc: The UTC timestamp when indexing started. + :vartype indexing_start_time_utc: ~datetime.datetime + :ivar indexing_end_time_utc: The UTC timestamp when indexing ended. + :vartype indexing_end_time_utc: ~datetime.datetime + """ + + documents_processed: int = rest_field( + name="documentsProcessed", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of documents that were successfully processed. Required.""" + documents_failed: int = rest_field( + name="documentsFailed", visibility=["read", "create", "update", "delete", "query"] + ) + """The number of documents that failed during indexing. Required.""" + documents_total: int = rest_field(name="documentsTotal", visibility=["read", "create", "update", "delete", "query"]) + """The total number of documents considered for indexing. Required.""" + indexing_percentage_complete: int = rest_field( + name="indexingPercentageComplete", visibility=["read", "create", "update", "delete", "query"] + ) + """The indexing completion percentage from 0 to 100. Required.""" + enrichment_start_time_utc: Optional[datetime.datetime] = rest_field( + name="enrichmentStartTimeUtc", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The UTC timestamp when enrichment started.""" + enrichment_end_time_utc: Optional[datetime.datetime] = rest_field( + name="enrichmentEndTimeUtc", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The UTC timestamp when enrichment ended.""" + indexing_start_time_utc: Optional[datetime.datetime] = rest_field( + name="indexingStartTimeUtc", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The UTC timestamp when indexing started.""" + indexing_end_time_utc: Optional[datetime.datetime] = rest_field( + name="indexingEndTimeUtc", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) + """The UTC timestamp when indexing ended.""" + + @overload + def __init__( + self, + *, + documents_processed: int, + documents_failed: int, + documents_total: int, + indexing_percentage_complete: int, + enrichment_start_time_utc: Optional[datetime.datetime] = None, + enrichment_end_time_utc: Optional[datetime.datetime] = None, + indexing_start_time_utc: Optional[datetime.datetime] = None, + indexing_end_time_utc: Optional[datetime.datetime] = 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 IndexingOperationResult(_Model): + """Result details for an indexing operation. + + :ivar run_id: The operation run identifier. Required. + :vartype run_id: str + :ivar metrics: Indexing run metrics. + :vartype metrics: ~azure.ai.discovery.models.IndexingMetrics + """ + + run_id: str = rest_field(name="runId", visibility=["read", "create", "update", "delete", "query"]) + """The operation run identifier. Required.""" + metrics: Optional["_models.IndexingMetrics"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Indexing run metrics.""" + + @overload + def __init__( + self, + *, + run_id: str, + metrics: Optional["_models.IndexingMetrics"] = 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 InfraOverrides(_Model): """Explicitly set tool run requirements - overrides the tool definition. @@ -334,6 +513,13 @@ class InfraOverrides(_Model): :vartype replica_count: int :ivar image_uri: Override the image to use for this tool run. :vartype image_uri: str + :ivar max_cpu: Override the maximum CPU allowed for the tool run (e.g. 1, or 500m for 500 + milli-CPUs). + :vartype max_cpu: str + :ivar max_ram: Override the maximum RAM allowed for the tool run (e.g. 500Mi or 1Gi). + :vartype max_ram: str + :ivar max_gpu: Override the maximum GPU count allowed for the tool run. + :vartype max_gpu: str """ cpu: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -348,6 +534,12 @@ class InfraOverrides(_Model): """Override the number of replicas of the tool image to run.""" image_uri: Optional[str] = rest_field(name="imageUri", visibility=["read", "create", "update", "delete", "query"]) """Override the image to use for this tool run.""" + max_cpu: Optional[str] = rest_field(name="maxCpu", visibility=["read", "create", "update", "delete", "query"]) + """Override the maximum CPU allowed for the tool run (e.g. 1, or 500m for 500 milli-CPUs).""" + max_ram: Optional[str] = rest_field(name="maxRam", visibility=["read", "create", "update", "delete", "query"]) + """Override the maximum RAM allowed for the tool run (e.g. 500Mi or 1Gi).""" + max_gpu: Optional[str] = rest_field(name="maxGpu", visibility=["read", "create", "update", "delete", "query"]) + """Override the maximum GPU count allowed for the tool run.""" @overload def __init__( @@ -358,6 +550,9 @@ def __init__( gpu: Optional[str] = None, replica_count: Optional[int] = None, image_uri: Optional[str] = None, + max_cpu: Optional[str] = None, + max_ram: Optional[str] = None, + max_gpu: Optional[str] = None, ) -> None: ... @overload @@ -412,19 +607,420 @@ class InputDataMount(_Model): :vartype storage_uri: str :ivar mount_path: Absolute path within the container at which to mount this input. Required. :vartype mount_path: str + :ivar mount_protocol: The protocol to use for mounting this storage. Overrides any value + specified on the storage container. Known values are: "NFS" and "BlobfuseCaching". + :vartype mount_protocol: str or ~azure.ai.discovery.models.StorageMountProtocol + """ + + storage_uri: str = rest_field(name="storageUri", visibility=["read", "create", "update", "delete", "query"]) + """URI of input data to mount. Required.""" + mount_path: str = rest_field(name="mountPath", visibility=["read", "create", "update", "delete", "query"]) + """Absolute path within the container at which to mount this input. Required.""" + mount_protocol: Optional[Union[str, "_models.StorageMountProtocol"]] = rest_field( + name="mountProtocol", visibility=["read", "create", "update", "delete", "query"] + ) + """The protocol to use for mounting this storage. Overrides any value specified on the storage + container. Known values are: \"NFS\" and \"BlobfuseCaching\".""" + + @overload + def __init__( + self, + *, + storage_uri: str, + mount_path: str, + mount_protocol: Optional[Union[str, "_models.StorageMountProtocol"]] = 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 Investigation(_Model): + """A investigation list item. + + :ivar name: The investigation name. Required. + :vartype name: str + :ivar project_name: The parent project name. Required. + :vartype project_name: str + :ivar created_at: The timestamp when the resource was created. + :vartype created_at: ~datetime.datetime + :ivar created_by: The ID of the user who created this resource. + :vartype created_by: str + :ivar created_by_type: The type of user who created this resource. Known values are: "User", + "Application", and "System". + :vartype created_by_type: str or ~azure.ai.discovery.models.ByType + :ivar last_modified_at: The timestamp when the resource was last updated. + :vartype last_modified_at: ~datetime.datetime + :ivar last_modified_by: The ID of the user who updated this resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of user who updated this resource. Known values are: + "User", "Application", and "System". + :vartype last_modified_by_type: str or ~azure.ai.discovery.models.ByType + :ivar status: The status. Known values are: "Created", "Validated", and "Failed". + :vartype status: str or ~azure.ai.discovery.models.InvestigationStatus + :ivar description: The description. + :vartype description: str + :ivar tags: The tags. + :vartype tags: list[~azure.ai.discovery.models.Tag] + :ivar display_name: The title. + :vartype display_name: str + """ + + name: str = rest_field(visibility=["read"]) + """The investigation name. Required.""" + project_name: str = rest_field(name="projectName", visibility=["read"]) + """The parent project name. Required.""" + created_at: Optional[datetime.datetime] = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """The timestamp when the resource was created.""" + created_by: Optional[str] = rest_field(name="createdBy", visibility=["read"]) + """The ID of the user who created this resource.""" + created_by_type: Optional[Union[str, "_models.ByType"]] = rest_field(name="createdByType", visibility=["read"]) + """The type of user who created this resource. Known values are: \"User\", \"Application\", and + \"System\".""" + last_modified_at: Optional[datetime.datetime] = rest_field( + name="lastModifiedAt", visibility=["read"], format="rfc3339" + ) + """The timestamp when the resource was last updated.""" + last_modified_by: Optional[str] = rest_field(name="lastModifiedBy", visibility=["read"]) + """The ID of the user who updated this resource.""" + last_modified_by_type: Optional[Union[str, "_models.ByType"]] = rest_field( + name="lastModifiedByType", visibility=["read"] + ) + """The type of user who updated this resource. Known values are: \"User\", \"Application\", and + \"System\".""" + status: Optional[Union[str, "_models.InvestigationStatus"]] = rest_field(visibility=["read"]) + """The status. Known values are: \"Created\", \"Validated\", and \"Failed\".""" + description: Optional[str] = rest_field(visibility=["read", "create", "update"]) + """The description.""" + tags: Optional[list["_models.Tag"]] = rest_field(visibility=["read", "create", "update"]) + """The tags.""" + display_name: Optional[str] = rest_field(name="displayName", visibility=["read", "create", "update"]) + """The title.""" + + @overload + def __init__( + self, + *, + description: Optional[str] = None, + tags: Optional[list["_models.Tag"]] = None, + display_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) + + +class InvestigationOperationStatus(_Model): + """The status of a long-running Investigation operation. + + :ivar id: The unique ID of the operation. Required. + :vartype id: str + :ivar status: The status of the operation. Required. Known values are: "NotStarted", "Running", + "Succeeded", "Failed", and "Canceled". + :vartype status: str or ~azure.ai.discovery.models.OperationState + :ivar error: Error object that describes the error when status is "Failed". + :vartype error: ~azure.core.ODataV4Format + :ivar result: The result of the operation. + :vartype result: ~azure.ai.discovery.models.Investigation + """ + + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The unique ID of the operation. Required.""" + status: Union[str, "_models.OperationState"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The status of the operation. Required. Known values are: \"NotStarted\", \"Running\", + \"Succeeded\", \"Failed\", and \"Canceled\".""" + error: Optional[ODataV4Format] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Error object that describes the error when status is \"Failed\".""" + result: Optional["_models.Investigation"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The result of the operation.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + status: Union[str, "_models.OperationState"], + error: Optional[ODataV4Format] = None, + result: Optional["_models.Investigation"] = 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 KnowledgeBase(_Model): + """A knowledgeBase. + + :ivar name: The knowledgeBase name. Required. + :vartype name: str + :ivar id: The ID for the resource. + :vartype id: str + :ivar bookshelf_name: The name of the associated Bookshelf tracked resource. Required. + :vartype bookshelf_name: str + :ivar storage_asset_references: Storage asset references to index. + :vartype storage_asset_references: list[~azure.ai.discovery.models.StorageAssetReference] + :ivar knowledge_base_url: URL to access the knowledge base. + :vartype knowledge_base_url: str + :ivar provisioning_state: Provisioning state. Known values are: "Succeeded", "Failed", + "Canceled", "Accepted", "Provisioning", "Updating", and "Deleting". + :vartype provisioning_state: str or ~azure.ai.discovery.models.ProvisioningState + :ivar error: Error details if provisioning failed. + :vartype error: ~azure.core.ODataV4Format + :ivar status: The status. Known values are: "NotStarted", "Running", "Succeeded", "Canceled", + and "Failed". + :vartype status: str or ~azure.ai.discovery.models.IndexingStatus + :ivar created_by_api_version: The API version used to create this knowledge base. + :vartype created_by_api_version: str + :ivar last_indexing_run: The details of the most recent indexing run. + :vartype last_indexing_run: ~azure.ai.discovery.models.LastIndexingRun + :ivar created_at: The timestamp when the resource was created. + :vartype created_at: ~datetime.datetime + :ivar created_by: The ID of the user who created this resource. + :vartype created_by: str + :ivar created_by_type: The type of user who created this resource. Known values are: "User", + "Application", and "System". + :vartype created_by_type: str or ~azure.ai.discovery.models.ByType + :ivar last_modified_at: The timestamp when the resource was last updated. + :vartype last_modified_at: ~datetime.datetime + :ivar last_modified_by: The ID of the user who updated this resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of user who updated this resource. Known values are: + "User", "Application", and "System". + :vartype last_modified_by_type: str or ~azure.ai.discovery.models.ByType + :ivar tags: The tags. + :vartype tags: list[~azure.ai.discovery.models.Tag] + :ivar description: The description. Required. + :vartype description: str + :ivar copilot_instruction: The copilot instruction. Required. + :vartype copilot_instruction: str + """ + + name: str = rest_field(visibility=["read"]) + """The knowledgeBase name. Required.""" + id: Optional[str] = rest_field(visibility=["read"]) + """The ID for the resource.""" + bookshelf_name: str = rest_field(name="bookshelfName", visibility=["read"]) + """The name of the associated Bookshelf tracked resource. Required.""" + storage_asset_references: Optional[list["_models.StorageAssetReference"]] = rest_field( + name="storageAssetReferences", visibility=["read", "create", "update"] + ) + """Storage asset references to index.""" + knowledge_base_url: Optional[str] = rest_field(name="knowledgeBaseUrl", visibility=["read"]) + """URL to access the knowledge base.""" + provisioning_state: Optional[Union[str, "_models.ProvisioningState"]] = rest_field( + name="provisioningState", visibility=["read"] + ) + """Provisioning state. Known values are: \"Succeeded\", \"Failed\", \"Canceled\", \"Accepted\", + \"Provisioning\", \"Updating\", and \"Deleting\".""" + error: Optional[ODataV4Format] = rest_field(visibility=["read"]) + """Error details if provisioning failed.""" + status: Optional[Union[str, "_models.IndexingStatus"]] = rest_field(visibility=["read"]) + """The status. Known values are: \"NotStarted\", \"Running\", \"Succeeded\", \"Canceled\", and + \"Failed\".""" + created_by_api_version: Optional[str] = rest_field(name="createdByApiVersion", visibility=["read"]) + """The API version used to create this knowledge base.""" + last_indexing_run: Optional["_models.LastIndexingRun"] = rest_field(name="lastIndexingRun", visibility=["read"]) + """The details of the most recent indexing run.""" + created_at: Optional[datetime.datetime] = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """The timestamp when the resource was created.""" + created_by: Optional[str] = rest_field(name="createdBy", visibility=["read"]) + """The ID of the user who created this resource.""" + created_by_type: Optional[Union[str, "_models.ByType"]] = rest_field(name="createdByType", visibility=["read"]) + """The type of user who created this resource. Known values are: \"User\", \"Application\", and + \"System\".""" + last_modified_at: Optional[datetime.datetime] = rest_field( + name="lastModifiedAt", visibility=["read"], format="rfc3339" + ) + """The timestamp when the resource was last updated.""" + last_modified_by: Optional[str] = rest_field(name="lastModifiedBy", visibility=["read"]) + """The ID of the user who updated this resource.""" + last_modified_by_type: Optional[Union[str, "_models.ByType"]] = rest_field( + name="lastModifiedByType", visibility=["read"] + ) + """The type of user who updated this resource. Known values are: \"User\", \"Application\", and + \"System\".""" + tags: Optional[list["_models.Tag"]] = rest_field(visibility=["read", "create", "update"]) + """The tags.""" + description: str = rest_field(visibility=["read", "create", "update"]) + """The description. Required.""" + copilot_instruction: str = rest_field(name="copilotInstruction", visibility=["read", "create", "update"]) + """The copilot instruction. Required.""" + + @overload + def __init__( + self, + *, + description: str, + copilot_instruction: str, + storage_asset_references: Optional[list["_models.StorageAssetReference"]] = None, + tags: Optional[list["_models.Tag"]] = 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 KnowledgeBaseOperationResponse(_Model): + """Response indicating the KnowledgeBase operation. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + KnowledgeBaseIndexingOperationResponse, KnowledgeBaseSearchOperationResponse + + :ivar id: The unique ID of the operation. Required. + :vartype id: str + :ivar status: The status of the operation. Required. Known values are: "NotStarted", "Running", + "Succeeded", "Failed", and "Canceled". + :vartype status: str or ~azure.ai.discovery.models.OperationState + :ivar error: Error object that describes the error when status is 'Failed'. + :vartype error: ~azure.core.ODataV4Format + :ivar operation_type: The type of operation. Required. Known values are: "Indexing", + "CancelIndexing", "Search", and "Delete". + :vartype operation_type: str or ~azure.ai.discovery.models.KnowledgeBaseOperationType + """ + + __mapping__: dict[str, _Model] = {} + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The unique ID of the operation. Required.""" + status: Union[str, "_models.OperationState"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The status of the operation. Required. Known values are: \"NotStarted\", \"Running\", + \"Succeeded\", \"Failed\", and \"Canceled\".""" + error: Optional[ODataV4Format] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Error object that describes the error when status is 'Failed'.""" + operation_type: str = rest_discriminator( + name="operationType", visibility=["read", "create", "update", "delete", "query"] + ) + """The type of operation. Required. Known values are: \"Indexing\", \"CancelIndexing\", + \"Search\", and \"Delete\".""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + status: Union[str, "_models.OperationState"], + operation_type: str, + error: Optional[ODataV4Format] = 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 KnowledgeBaseIndexingOperationResponse(KnowledgeBaseOperationResponse, discriminator="Indexing"): + """Response for indexing operations. + + :ivar id: The unique ID of the operation. Required. + :vartype id: str + :ivar status: The status of the operation. Required. Known values are: "NotStarted", "Running", + "Succeeded", "Failed", and "Canceled". + :vartype status: str or ~azure.ai.discovery.models.OperationState + :ivar error: Error object that describes the error when status is 'Failed'. + :vartype error: ~azure.core.ODataV4Format + :ivar operation_type: The type of operation. Required. An indexing operation. + :vartype operation_type: str or ~azure.ai.discovery.models.INDEXING + :ivar indexing_result: Result details for indexing operations. + :vartype indexing_result: ~azure.ai.discovery.models.IndexingOperationResult + """ + + operation_type: Literal[KnowledgeBaseOperationType.INDEXING] = rest_discriminator(name="operationType", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The type of operation. Required. An indexing operation.""" + indexing_result: Optional["_models.IndexingOperationResult"] = rest_field( + name="indexingResult", visibility=["read", "create", "update", "delete", "query"] + ) + """Result details for indexing operations.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + status: Union[str, "_models.OperationState"], + error: Optional[ODataV4Format] = None, + indexing_result: Optional["_models.IndexingOperationResult"] = 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.operation_type = KnowledgeBaseOperationType.INDEXING # type: ignore + + +class KnowledgeBaseSearchOperationResponse(KnowledgeBaseOperationResponse, discriminator="Search"): + """Response for search operations. + + :ivar id: The unique ID of the operation. Required. + :vartype id: str + :ivar status: The status of the operation. Required. Known values are: "NotStarted", "Running", + "Succeeded", "Failed", and "Canceled". + :vartype status: str or ~azure.ai.discovery.models.OperationState + :ivar error: Error object that describes the error when status is 'Failed'. + :vartype error: ~azure.core.ODataV4Format + :ivar operation_type: The type of operation. Required. A search operation. + :vartype operation_type: str or ~azure.ai.discovery.models.SEARCH + :ivar search_result: Result details for search operations. + :vartype search_result: ~azure.ai.discovery.models.SearchResponse """ - storage_uri: str = rest_field(name="storageUri", visibility=["read", "create", "update", "delete", "query"]) - """URI of input data to mount. Required.""" - mount_path: str = rest_field(name="mountPath", visibility=["read", "create", "update", "delete", "query"]) - """Absolute path within the container at which to mount this input. Required.""" + operation_type: Literal[KnowledgeBaseOperationType.SEARCH] = rest_discriminator(name="operationType", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The type of operation. Required. A search operation.""" + search_result: Optional["_models.SearchResponse"] = rest_field( + name="searchResult", visibility=["read", "create", "update", "delete", "query"] + ) + """Result details for search operations.""" @overload def __init__( self, *, - storage_uri: str, - mount_path: str, + id: str, # pylint: disable=redefined-builtin + status: Union[str, "_models.OperationState"], + error: Optional[ODataV4Format] = None, + search_result: Optional["_models.SearchResponse"] = None, ) -> None: ... @overload @@ -436,77 +1032,45 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) + self.operation_type = KnowledgeBaseOperationType.SEARCH # type: ignore -class Investigation(_Model): - """A investigation list item. +class LastIndexingRun(_Model): + """The details of the last indexing run. - :ivar name: The investigation name. Required. - :vartype name: str - :ivar project_name: The parent project name. Required. - :vartype project_name: str - :ivar created_at: The timestamp when the resource was created. - :vartype created_at: ~datetime.datetime - :ivar created_by: The ID of the user who created this resource. - :vartype created_by: str - :ivar created_by_type: The type of user who created this resource. Known values are: "User", - "Application", and "System". - :vartype created_by_type: str or ~azure.ai.discovery.models.ByType - :ivar last_modified_at: The timestamp when the resource was last updated. - :vartype last_modified_at: ~datetime.datetime - :ivar last_modified_by: The ID of the user who updated this resource. - :vartype last_modified_by: str - :ivar last_modified_by_type: The type of user who updated this resource. Known values are: - "User", "Application", and "System". - :vartype last_modified_by_type: str or ~azure.ai.discovery.models.ByType - :ivar status: The status. Known values are: "Created", "Validated", and "Failed". - :vartype status: str or ~azure.ai.discovery.models.InvestigationStatus - :ivar description: The description. - :vartype description: str - :ivar tags: The tags. - :vartype tags: list[~azure.ai.discovery.models.Tag] - :ivar display_name: The title. - :vartype display_name: str + :ivar run_id: The operation run identifier. + :vartype run_id: str + :ivar status: The status of the indexing run. Known values are: "NotStarted", "Running", + "Succeeded", "Canceled", and "Failed". + :vartype status: str or ~azure.ai.discovery.models.IndexingStatus + :ivar error: Error object that describes the error when status is 'Failed'. + :vartype error: ~azure.core.ODataV4Format + :ivar indexing_metrics: Indexing metrics for the run. + :vartype indexing_metrics: ~azure.ai.discovery.models.IndexingMetrics """ - name: str = rest_field(visibility=["read"]) - """The investigation name. Required.""" - project_name: str = rest_field(name="projectName", visibility=["read"]) - """The parent project name. Required.""" - created_at: Optional[datetime.datetime] = rest_field(name="createdAt", visibility=["read"], format="rfc3339") - """The timestamp when the resource was created.""" - created_by: Optional[str] = rest_field(name="createdBy", visibility=["read"]) - """The ID of the user who created this resource.""" - created_by_type: Optional[Union[str, "_models.ByType"]] = rest_field(name="createdByType", visibility=["read"]) - """The type of user who created this resource. Known values are: \"User\", \"Application\", and - \"System\".""" - last_modified_at: Optional[datetime.datetime] = rest_field( - name="lastModifiedAt", visibility=["read"], format="rfc3339" + run_id: Optional[str] = rest_field(name="runId", visibility=["read", "create", "update", "delete", "query"]) + """The operation run identifier.""" + status: Optional[Union[str, "_models.IndexingStatus"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] ) - """The timestamp when the resource was last updated.""" - last_modified_by: Optional[str] = rest_field(name="lastModifiedBy", visibility=["read"]) - """The ID of the user who updated this resource.""" - last_modified_by_type: Optional[Union[str, "_models.ByType"]] = rest_field( - name="lastModifiedByType", visibility=["read"] + """The status of the indexing run. Known values are: \"NotStarted\", \"Running\", \"Succeeded\", + \"Canceled\", and \"Failed\".""" + error: Optional[ODataV4Format] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Error object that describes the error when status is 'Failed'.""" + indexing_metrics: Optional["_models.IndexingMetrics"] = rest_field( + name="indexingMetrics", visibility=["read", "create", "update", "delete", "query"] ) - """The type of user who updated this resource. Known values are: \"User\", \"Application\", and - \"System\".""" - status: Optional[Union[str, "_models.InvestigationStatus"]] = rest_field(visibility=["read"]) - """The status. Known values are: \"Created\", \"Validated\", and \"Failed\".""" - description: Optional[str] = rest_field(visibility=["read", "create", "update"]) - """The description.""" - tags: Optional[list["_models.Tag"]] = rest_field(visibility=["read", "create", "update"]) - """The tags.""" - display_name: Optional[str] = rest_field(name="displayName", visibility=["read", "create", "update"]) - """The title.""" + """Indexing metrics for the run.""" @overload def __init__( self, *, - description: Optional[str] = None, - tags: Optional[list["_models.Tag"]] = None, - display_name: Optional[str] = None, + run_id: Optional[str] = None, + status: Optional[Union[str, "_models.IndexingStatus"]] = None, + error: Optional[ODataV4Format] = None, + indexing_metrics: Optional["_models.IndexingMetrics"] = None, ) -> None: ... @overload @@ -701,12 +1265,20 @@ class OutputDataMount(_Model): :ivar mount_path: Absolute path within the container from which to collect output data. Required. :vartype mount_path: str + :ivar mount_protocol: The protocol to use for mounting this storage. Overrides any value + specified on the storage container. Known values are: "NFS" and "BlobfuseCaching". + :vartype mount_protocol: str or ~azure.ai.discovery.models.StorageMountProtocol """ storage_uri: str = rest_field(name="storageUri", visibility=["read", "create", "update", "delete", "query"]) """URI of location to persist output to. Required.""" mount_path: str = rest_field(name="mountPath", visibility=["read", "create", "update", "delete", "query"]) """Absolute path within the container from which to collect output data. Required.""" + mount_protocol: Optional[Union[str, "_models.StorageMountProtocol"]] = rest_field( + name="mountProtocol", visibility=["read", "create", "update", "delete", "query"] + ) + """The protocol to use for mounting this storage. Overrides any value specified on the storage + container. Known values are: \"NFS\" and \"BlobfuseCaching\".""" @overload def __init__( @@ -714,6 +1286,7 @@ def __init__( *, storage_uri: str, mount_path: str, + mount_protocol: Optional[Union[str, "_models.StorageMountProtocol"]] = None, ) -> None: ... @overload @@ -760,17 +1333,17 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class PagedOperation(_Model): - """Paged collection of Operation items. +class PagedConversation(_Model): + """Paged collection of Conversation items. - :ivar value: The Operation items on this page. Required. - :vartype value: list[~azure.ai.discovery.models.Operation] + :ivar value: The Conversation items on this page. Required. + :vartype value: list[~azure.ai.discovery.models.Conversation] :ivar next_link: The link to the next page of items. :vartype next_link: str """ - value: list["_models.Operation"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The Operation items on this page. Required.""" + value: list["_models.Conversation"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The Conversation items on this page. Required.""" next_link: Optional[str] = rest_field(name="nextLink", visibility=["read", "create", "update", "delete", "query"]) """The link to the next page of items.""" @@ -778,7 +1351,7 @@ class PagedOperation(_Model): def __init__( self, *, - value: list["_models.Operation"], + value: list["_models.Conversation"], next_link: Optional[str] = None, ) -> None: ... @@ -793,17 +1366,17 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class PagedWorkingMemoryEntry(_Model): - """Paged collection of WorkingMemoryEntry items. +class PagedInvestigation(_Model): + """Paged collection of Investigation items. - :ivar value: The WorkingMemoryEntry items on this page. Required. - :vartype value: list[~azure.ai.discovery.models.WorkingMemoryEntry] + :ivar value: The Investigation items on this page. Required. + :vartype value: list[~azure.ai.discovery.models.Investigation] :ivar next_link: The link to the next page of items. :vartype next_link: str """ - value: list["_models.WorkingMemoryEntry"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The WorkingMemoryEntry items on this page. Required.""" + value: list["_models.Investigation"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The Investigation items on this page. Required.""" next_link: Optional[str] = rest_field(name="nextLink", visibility=["read", "create", "update", "delete", "query"]) """The link to the next page of items.""" @@ -811,7 +1384,7 @@ class PagedWorkingMemoryEntry(_Model): def __init__( self, *, - value: list["_models.WorkingMemoryEntry"], + value: list["_models.Investigation"], next_link: Optional[str] = None, ) -> None: ... @@ -826,40 +1399,59 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ResourceOperationStatusInvestigationInvestigationError(_Model): # pylint: disable=name-too-long - """Provides status details for long running operations. +class PagedOperation(_Model): + """Paged collection of Operation items. - :ivar id: The unique ID of the operation. Required. - :vartype id: str - :ivar status: The status of the operation. Required. Known values are: "NotStarted", "Running", - "Succeeded", "Failed", and "Canceled". - :vartype status: str or ~azure.ai.discovery.models.OperationState - :ivar error: Error object that describes the error when status is "Failed". - :vartype error: ~azure.core.ODataV4Format - :ivar result: The result of the operation. - :vartype result: ~azure.ai.discovery.models.Investigation + :ivar value: The Operation items on this page. Required. + :vartype value: list[~azure.ai.discovery.models.Operation] + :ivar next_link: The link to the next page of items. + :vartype next_link: str """ - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of the operation. Required.""" - status: Union[str, "_models.OperationState"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the operation. Required. Known values are: \"NotStarted\", \"Running\", - \"Succeeded\", \"Failed\", and \"Canceled\".""" - error: Optional[ODataV4Format] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Error object that describes the error when status is \"Failed\".""" - result: Optional["_models.Investigation"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The result of the operation.""" + value: list["_models.Operation"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The Operation items on this page. Required.""" + next_link: Optional[str] = rest_field(name="nextLink", visibility=["read", "create", "update", "delete", "query"]) + """The link to the next page of items.""" @overload def __init__( self, *, - id: str, # pylint: disable=redefined-builtin - status: Union[str, "_models.OperationState"], - error: Optional[ODataV4Format] = None, - result: Optional["_models.Investigation"] = None, + value: list["_models.Operation"], + next_link: 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 PagedWorkingMemoryEntry(_Model): + """Paged collection of WorkingMemoryEntry items. + + :ivar value: The WorkingMemoryEntry items on this page. Required. + :vartype value: list[~azure.ai.discovery.models.WorkingMemoryEntry] + :ivar next_link: The link to the next page of items. + :vartype next_link: str + """ + + value: list["_models.WorkingMemoryEntry"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The WorkingMemoryEntry items on this page. Required.""" + next_link: Optional[str] = rest_field(name="nextLink", visibility=["read", "create", "update", "delete", "query"]) + """The link to the next page of items.""" + + @overload + def __init__( + self, + *, + value: list["_models.WorkingMemoryEntry"], + next_link: Optional[str] = None, ) -> None: ... @overload @@ -1012,6 +1604,99 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class SearchRequest(_Model): + """The search action request body. + + :ivar query: The query text to search against the knowledge base. Required. + :vartype query: str + """ + + query: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The query text to search against the knowledge base. Required.""" + + @overload + def __init__( + self, + *, + query: 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 SearchResponse(_Model): + """Results of a knowledge base search. + + :ivar search_results: The search results. Required. + :vartype search_results: list[~azure.ai.discovery.models.SearchResultItem] + """ + + search_results: list["_models.SearchResultItem"] = rest_field( + name="searchResults", visibility=["read", "create", "update", "delete", "query"] + ) + """The search results. Required.""" + + @overload + def __init__( + self, + *, + search_results: list["_models.SearchResultItem"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param 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 SearchResultItem(_Model): + """A single search result item. + + :ivar text: The generated response text for this result. Required. + :vartype text: str + :ivar citations: Source citations for this result. + :vartype citations: list[~azure.ai.discovery.models.Citation] + """ + + text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The generated response text for this result. Required.""" + citations: Optional[list["_models.Citation"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Source citations for this result.""" + + @overload + def __init__( + self, + *, + text: str, + citations: Optional[list["_models.Citation"]] = 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 StartTaskRequest(_Model): """Request body for starting a task. @@ -1040,6 +1725,42 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class StorageAssetReference(_Model): + """Reference to a storage asset with identity information. + + :ivar id: The ARM resource ID of the storage asset. Required. + :vartype id: str + :ivar user_assigned_identity: The ARM resource ID of the User Assigned Managed Identity to + access the storage asset. + :vartype user_assigned_identity: str + """ + + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The ARM resource ID of the storage asset. Required.""" + user_assigned_identity: Optional[str] = rest_field( + name="userAssignedIdentity", visibility=["read", "create", "update", "delete", "query"] + ) + """The ARM resource ID of the User Assigned Managed Identity to access the storage asset.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + user_assigned_identity: 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 SupercomputerUsage(_Model): """Overview of compute usage for a supercomputer. @@ -1378,7 +2099,7 @@ class WorkingMemoryEntry(_Model): :ivar content: The content of the working memory entry. Required. :vartype content: str - :ivar type: The type of the working memory entry. Required. "thought" + :ivar type: The type of the working memory entry. Required. "Thought" :vartype type: str or ~azure.ai.discovery.models.WorkingMemoryEntryType :ivar created_at: The timestamp when the resource was created. :vartype created_at: ~datetime.datetime @@ -1389,8 +2110,10 @@ class WorkingMemoryEntry(_Model): type: Union[str, "_models.WorkingMemoryEntryType"] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) - """The type of the working memory entry. Required. \"thought\"""" - created_at: Optional[datetime.datetime] = rest_field(name="createdAt", visibility=["read"], format="rfc3339") + """The type of the working memory entry. Required. \"Thought\"""" + created_at: Optional[datetime.datetime] = rest_field( + name="createdAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) """The timestamp when the resource was created.""" @overload @@ -1399,6 +2122,7 @@ def __init__( *, content: str, type: Union[str, "_models.WorkingMemoryEntryType"], + created_at: Optional[datetime.datetime] = None, ) -> None: ... @overload diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/models/_patch.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/models/_patch.py similarity index 99% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/models/_patch.py rename to sdk/discovery/azure-ai-discovery/azure/ai/discovery/models/_patch.py index 87676c65a8f0..ea765788358a 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/azure/ai/discovery/models/_patch.py +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/models/_patch.py @@ -8,7 +8,6 @@ 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 diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/operations/__init__.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/operations/__init__.py similarity index 92% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/operations/__init__.py rename to sdk/discovery/azure-ai-discovery/azure/ai/discovery/operations/__init__.py index 011818daade0..110360a67296 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/aio/operations/__init__.py +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/operations/__init__.py @@ -16,6 +16,7 @@ from ._operations import ConversationsOperations # type: ignore from ._operations import ToolsOperations # type: ignore from ._operations import TasksOperations # type: ignore +from ._operations import KnowledgeBasesOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * @@ -26,6 +27,7 @@ "ConversationsOperations", "ToolsOperations", "TasksOperations", + "KnowledgeBasesOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/operations/_operations.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/operations/_operations.py similarity index 68% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/operations/_operations.py rename to sdk/discovery/azure-ai-discovery/azure/ai/discovery/operations/_operations.py index b18b4968a5ca..d99671341ea6 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/azure/ai/discovery/operations/_operations.py +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/operations/_operations.py @@ -12,6 +12,7 @@ import json from typing import Any, Callable, IO, Iterator, Optional, TypeVar, Union, cast, overload import urllib.parse +import uuid from azure.core import PipelineClient from azure.core.exceptions import ( @@ -32,15 +33,15 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import models as _models -from .._configuration import WorkspaceClientConfiguration +from .. import models as _models, types as _types +from .._configuration import BookshelfClientConfiguration, WorkspaceClientConfiguration from .._utils.model_base import SdkJSONEncoder, _deserialize from .._utils.serialization import Deserializer, Serializer from .._validation import api_version_validation -JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] _Unset: Any = object() List = list @@ -52,7 +53,7 @@ def build_investigations_get_request(project_name: str, investigation_name: str, _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -79,7 +80,7 @@ def build_investigations_get_operation_status_request( # pylint: disable=name-t _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -108,7 +109,7 @@ def build_investigations_create_or_replace_request( # pylint: disable=name-too- _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -131,14 +132,12 @@ def build_investigations_create_or_replace_request( # pylint: disable=name-too- return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_investigations_create_or_update_request( # pylint: disable=name-too-long - project_name: str, investigation_name: str, **kwargs: Any -) -> HttpRequest: +def build_investigations_update_request(project_name: str, investigation_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -165,7 +164,7 @@ def build_investigations_delete_request(project_name: str, investigation_name: s _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -187,12 +186,18 @@ def build_investigations_delete_request(project_name: str, investigation_name: s def build_investigations_list_request( - project_name: str, *, created_since: Optional[datetime.datetime] = None, **kwargs: Any + project_name: str, + *, + created_since: Optional[datetime.datetime] = None, + top: Optional[int] = None, + skip: Optional[int] = None, + maxpagesize: Optional[int] = None, + **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -207,6 +212,12 @@ def build_investigations_list_request( _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") if created_since is not None: _params["createdSince"] = _SERIALIZER.query("created_since", created_since, "iso-8601") + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + if skip is not None: + _params["skip"] = _SERIALIZER.query("skip", skip, "int") + if maxpagesize is not None: + _params["maxpagesize"] = _SERIALIZER.query("maxpagesize", maxpagesize, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -220,7 +231,7 @@ def build_investigations_get_discovery_engine_request( # pylint: disable=name-t _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -245,15 +256,15 @@ def build_investigations_get_discovery_engine_memory_request( # pylint: disable project_name: str, investigation_name: str, *, - skip: Optional[int] = None, top: Optional[int] = None, - max_page_size: Optional[int] = None, + skip: Optional[int] = None, + maxpagesize: Optional[int] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -267,12 +278,12 @@ def build_investigations_get_discovery_engine_memory_request( # pylint: disable # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if skip is not None: - _params["skip"] = _SERIALIZER.query("skip", skip, "int") if top is not None: _params["top"] = _SERIALIZER.query("top", top, "int") - if max_page_size is not None: - _params["maxPageSize"] = _SERIALIZER.query("max_page_size", max_page_size, "int") + if skip is not None: + _params["skip"] = _SERIALIZER.query("skip", skip, "int") + if maxpagesize is not None: + _params["maxpagesize"] = _SERIALIZER.query("maxpagesize", maxpagesize, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -286,7 +297,7 @@ def build_investigations_start_discovery_engine_request( # pylint: disable=name _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -313,7 +324,7 @@ def build_investigations_stop_discovery_engine_request( # pylint: disable=name- _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -341,7 +352,7 @@ def build_investigations_update_discovery_engine_request( # pylint: disable=nam _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -368,7 +379,7 @@ def build_conversations_get_request(conversation_name: str, **kwargs: Any) -> Ht _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -393,7 +404,7 @@ def build_conversations_create_request(**kwargs: Any) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -410,12 +421,14 @@ def build_conversations_create_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_conversations_update_request(conversation_name: str, **kwargs: Any) -> HttpRequest: +def build_conversations_stable_update_request( # pylint: disable=name-too-long + conversation_name: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -440,7 +453,7 @@ def build_conversations_update_request(conversation_name: str, **kwargs: Any) -> def build_conversations_delete_request(conversation_name: str, **kwargs: Any) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) # Construct URL _url = "/conversations/{conversationName}" path_format_arguments = { @@ -460,12 +473,15 @@ def build_conversations_list_request( investigation_name: Optional[str] = None, project_name: Optional[str] = None, created_since: Optional[datetime.datetime] = None, + top: Optional[int] = None, + skip: Optional[int] = None, + maxpagesize: Optional[int] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -479,6 +495,12 @@ def build_conversations_list_request( _params["projectName"] = _SERIALIZER.query("project_name", project_name, "str") if created_since is not None: _params["createdSince"] = _SERIALIZER.query("created_since", created_since, "iso-8601") + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + if skip is not None: + _params["skip"] = _SERIALIZER.query("skip", skip, "int") + if maxpagesize is not None: + _params["maxpagesize"] = _SERIALIZER.query("maxpagesize", maxpagesize, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -492,7 +514,7 @@ def build_tools_get_run_status_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -520,7 +542,7 @@ def build_tools_run_request(project_name: str, **kwargs: Any) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -542,10 +564,13 @@ def build_tools_run_request(project_name: str, **kwargs: Any) -> HttpRequest: return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_tools_cancel_run_request(project_name: str, operation_id: str, **kwargs: Any) -> HttpRequest: +def build_tools_cancel_run_lro_request(project_name: str, operation_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = "/tools/projects/{projectName}/operations/{operationId}:cancel" path_format_arguments = { @@ -558,21 +583,24 @@ def build_tools_cancel_run_request(project_name: str, operation_id: str, **kwarg # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - return HttpRequest(method="POST", url=_url, params=_params, **kwargs) + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) def build_tools_get_operations_request( project_name: str, *, - skip: Optional[int] = None, top: Optional[int] = None, - max_page_size: Optional[int] = None, + skip: Optional[int] = None, + maxpagesize: Optional[int] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -585,12 +613,12 @@ def build_tools_get_operations_request( # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if skip is not None: - _params["skip"] = _SERIALIZER.query("skip", skip, "int") if top is not None: _params["top"] = _SERIALIZER.query("top", top, "int") - if max_page_size is not None: - _params["maxPageSize"] = _SERIALIZER.query("max_page_size", max_page_size, "int") + if skip is not None: + _params["skip"] = _SERIALIZER.query("skip", skip, "int") + if maxpagesize is not None: + _params["maxpagesize"] = _SERIALIZER.query("maxpagesize", maxpagesize, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -602,7 +630,7 @@ def build_tools_get_compute_usage_request(project_name: str, **kwargs: Any) -> H _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -626,7 +654,7 @@ def build_tasks_get_request(project_name: str, investigation_name: str, task_nam _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -654,7 +682,7 @@ def build_tasks_list_request( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -682,7 +710,7 @@ def build_tasks_create_request(project_name: str, investigation_name: str, **kwa _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -705,14 +733,14 @@ def build_tasks_create_request(project_name: str, investigation_name: str, **kwa return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_tasks_update_request( +def build_tasks_stable_update_request( project_name: str, investigation_name: str, task_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -741,7 +769,7 @@ def build_tasks_delete_request( ) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) # Construct URL _url = "/projects/{projectName}/investigations/{investigationName}/tasks/{taskName}" path_format_arguments = { @@ -763,7 +791,7 @@ def build_tasks_start_request(project_name: str, investigation_name: str, task_n _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -788,21 +816,21 @@ def build_tasks_start_request(project_name: str, investigation_name: str, task_n def build_tasks_add_comment_request( - task_name: str, project_name: str, investigation_name: str, **kwargs: Any + project_name: str, investigation_name: str, task_name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL _url = "/projects/{projectName}/investigations/{investigationName}/tasks/{taskName}:addComment" path_format_arguments = { - "taskName": _SERIALIZER.url("task_name", task_name, "str"), "projectName": _SERIALIZER.url("project_name", project_name, "str"), "investigationName": _SERIALIZER.url("investigation_name", investigation_name, "str"), + "taskName": _SERIALIZER.url("task_name", task_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -825,7 +853,7 @@ def build_tasks_add_execution_history_request( # pylint: disable=name-too-long _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-02-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -849,6 +877,229 @@ def build_tasks_add_execution_history_request( # pylint: disable=name-too-long return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) +def build_knowledge_bases_create_or_update_request( # pylint: disable=name-too-long + knowledge_base_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/knowledgeBases/{knowledgeBaseName}" + path_format_arguments = { + "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_knowledge_bases_get_request(knowledge_base_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/knowledgeBases/{knowledgeBaseName}" + path_format_arguments = { + "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_knowledge_bases_list_request(**kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/knowledgeBases" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_knowledge_bases_get_operation_status_request( # pylint: disable=name-too-long + knowledge_base_name: str, operation_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/knowledgeBases/{knowledgeBaseName}/operations/{operationId}" + path_format_arguments = { + "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), + "operationId": _SERIALIZER.url("operation_id", operation_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_knowledge_bases_start_indexing_request( # pylint: disable=name-too-long + knowledge_base_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/knowledgeBases/{knowledgeBaseName}:startIndexing" + path_format_arguments = { + "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if "Repeatability-Request-ID" not in _headers: + _headers["Repeatability-Request-ID"] = str(uuid.uuid4()) + if "Repeatability-First-Sent" not in _headers: + _headers["Repeatability-First-Sent"] = _SERIALIZER.serialize_data( + datetime.datetime.now(datetime.timezone.utc), "rfc-1123" + ) + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_knowledge_bases_cancel_indexing_request( # pylint: disable=name-too-long + knowledge_base_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/knowledgeBases/{knowledgeBaseName}:cancelIndexing" + path_format_arguments = { + "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if "Repeatability-Request-ID" not in _headers: + _headers["Repeatability-Request-ID"] = str(uuid.uuid4()) + if "Repeatability-First-Sent" not in _headers: + _headers["Repeatability-First-Sent"] = _SERIALIZER.serialize_data( + datetime.datetime.now(datetime.timezone.utc), "rfc-1123" + ) + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_knowledge_bases_search_request(knowledge_base_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/knowledgeBases/{knowledgeBaseName}:search" + path_format_arguments = { + "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if "Repeatability-Request-ID" not in _headers: + _headers["Repeatability-Request-ID"] = str(uuid.uuid4()) + if "Repeatability-First-Sent" not in _headers: + _headers["Repeatability-First-Sent"] = _SERIALIZER.serialize_data( + datetime.datetime.now(datetime.timezone.utc), "rfc-1123" + ) + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_knowledge_bases_delete_request(knowledge_base_name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2026-06-01")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/knowledgeBases/{knowledgeBaseName}" + path_format_arguments = { + "knowledgeBaseName": _SERIALIZER.url("knowledge_base_name", knowledge_base_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + class InvestigationsOperations: """ .. warning:: @@ -932,15 +1183,13 @@ def get(self, project_name: str, investigation_name: str, **kwargs: Any) -> _mod @distributed_trace @api_version_validation( - method_added_on="2026-02-01-preview", - params_added_on={ - "2026-02-01-preview": ["api_version", "project_name", "investigation_name", "operation_id", "accept"] - }, - api_versions_list=["2026-02-01-preview"], + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "project_name", "investigation_name", "operation_id", "accept"]}, + api_versions_list=["2026-06-01"], ) def get_operation_status( self, project_name: str, investigation_name: str, operation_id: str, **kwargs: Any - ) -> _models.ResourceOperationStatusInvestigationInvestigationError: + ) -> _models.InvestigationOperationStatus: """Get the status of a long-running operation. :param project_name: The project name. Required. @@ -949,9 +1198,9 @@ def get_operation_status( :type investigation_name: str :param operation_id: The unique ID of the operation. Required. :type operation_id: str - :return: ResourceOperationStatusInvestigationInvestigationError. The - ResourceOperationStatusInvestigationInvestigationError is compatible with MutableMapping - :rtype: ~azure.ai.discovery.models.ResourceOperationStatusInvestigationInvestigationError + :return: InvestigationOperationStatus. The InvestigationOperationStatus is compatible with + MutableMapping + :rtype: ~azure.ai.discovery.models.InvestigationOperationStatus :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -965,7 +1214,7 @@ def get_operation_status( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.ResourceOperationStatusInvestigationInvestigationError] = kwargs.pop("cls", None) + cls: ClsType[_models.InvestigationOperationStatus] = kwargs.pop("cls", None) _request = build_investigations_get_operation_status_request( project_name=project_name, @@ -1000,7 +1249,7 @@ def get_operation_status( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.ResourceOperationStatusInvestigationInvestigationError, response.json()) + deserialized = _deserialize(_models.InvestigationOperationStatus, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -1038,7 +1287,7 @@ def create_or_replace( self, project_name: str, investigation_name: str, - resource: JSON, + resource: _types.Investigation, *, content_type: str = "application/json", **kwargs: Any @@ -1050,7 +1299,7 @@ def create_or_replace( :param investigation_name: The investigation name. Required. :type investigation_name: str :param resource: The resource instance. Required. - :type resource: JSON + :type resource: ~azure.ai.discovery.types.Investigation :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1090,7 +1339,7 @@ def create_or_replace( self, project_name: str, investigation_name: str, - resource: Union[_models.Investigation, JSON, IO[bytes]], + resource: Union[_models.Investigation, _types.Investigation, IO[bytes]], **kwargs: Any ) -> _models.Investigation: """Creates an Investigation. @@ -1099,9 +1348,10 @@ def create_or_replace( :type project_name: str :param investigation_name: The investigation name. Required. :type investigation_name: str - :param resource: The resource instance. Is one of the following types: Investigation, JSON, - IO[bytes] Required. - :type resource: ~azure.ai.discovery.models.Investigation or JSON or IO[bytes] + :param resource: The resource instance. Is either a Investigation type or a IO[bytes] type. + Required. + :type resource: ~azure.ai.discovery.models.Investigation or + ~azure.ai.discovery.types.Investigation or IO[bytes] :return: Investigation. The Investigation is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.Investigation :raises ~azure.core.exceptions.HttpResponseError: @@ -1169,7 +1419,7 @@ def create_or_replace( return deserialized # type: ignore @overload - def create_or_update( + def update( self, project_name: str, investigation_name: str, @@ -1195,11 +1445,11 @@ def create_or_update( """ @overload - def create_or_update( + def update( self, project_name: str, investigation_name: str, - resource: JSON, + resource: _types.Investigation, *, content_type: str = "application/merge-patch+json", **kwargs: Any @@ -1211,7 +1461,7 @@ def create_or_update( :param investigation_name: The investigation name. Required. :type investigation_name: str :param resource: The resource instance. Required. - :type resource: JSON + :type resource: ~azure.ai.discovery.types.Investigation :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -1221,7 +1471,7 @@ def create_or_update( """ @overload - def create_or_update( + def update( self, project_name: str, investigation_name: str, @@ -1247,11 +1497,16 @@ def create_or_update( """ @distributed_trace - def create_or_update( + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "project_name", "investigation_name", "content_type", "accept"]}, + api_versions_list=["2026-06-01"], + ) + def update( self, project_name: str, investigation_name: str, - resource: Union[_models.Investigation, JSON, IO[bytes]], + resource: Union[_models.Investigation, _types.Investigation, IO[bytes]], **kwargs: Any ) -> _models.Investigation: """Updates an Investigation. @@ -1260,9 +1515,10 @@ def create_or_update( :type project_name: str :param investigation_name: The investigation name. Required. :type investigation_name: str - :param resource: The resource instance. Is one of the following types: Investigation, JSON, - IO[bytes] Required. - :type resource: ~azure.ai.discovery.models.Investigation or JSON or IO[bytes] + :param resource: The resource instance. Is either a Investigation type or a IO[bytes] type. + Required. + :type resource: ~azure.ai.discovery.models.Investigation or + ~azure.ai.discovery.types.Investigation or IO[bytes] :return: Investigation. The Investigation is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.Investigation :raises ~azure.core.exceptions.HttpResponseError: @@ -1288,7 +1544,7 @@ def create_or_update( else: _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_investigations_create_or_update_request( + _request = build_investigations_update_request( project_name=project_name, investigation_name=investigation_name, content_type=content_type, @@ -1310,7 +1566,7 @@ def create_or_update( response = pipeline_response.http_response - if response.status_code not in [200, 201]: + if response.status_code not in [200]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -1329,11 +1585,6 @@ def create_or_update( return deserialized # type: ignore - @api_version_validation( - method_added_on="2026-02-01-preview", - params_added_on={"2026-02-01-preview": ["api_version", "project_name", "investigation_name", "accept"]}, - api_versions_list=["2026-02-01-preview"], - ) def _delete_initial(self, project_name: str, investigation_name: str, **kwargs: Any) -> Iterator[bytes]: error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -1387,11 +1638,6 @@ def _delete_initial(self, project_name: str, investigation_name: str, **kwargs: return deserialized # type: ignore @distributed_trace - @api_version_validation( - method_added_on="2026-02-01-preview", - params_added_on={"2026-02-01-preview": ["api_version", "project_name", "investigation_name", "accept"]}, - api_versions_list=["2026-02-01-preview"], - ) def begin_delete( self, project_name: str, investigation_name: str, **kwargs: Any ) -> LROPoller[_models.Investigation]: @@ -1461,17 +1707,34 @@ def get_long_running_output(pipeline_response): ) @distributed_trace + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={ + "2026-06-01": ["api_version", "project_name", "created_since", "top", "skip", "maxpagesize", "accept"] + }, + api_versions_list=["2026-06-01"], + ) def list( - self, project_name: str, *, created_since: Optional[datetime.datetime] = None, **kwargs: Any - ) -> List[_models.Investigation]: + self, + project_name: str, + *, + created_since: Optional[datetime.datetime] = None, + top: Optional[int] = None, + skip: Optional[int] = None, + **kwargs: Any + ) -> _models.PagedInvestigation: """List Investigation resources. :param project_name: The project name. Required. :type project_name: str :keyword created_since: The oldest creation timestamp to keep. Default value is None. :paramtype created_since: ~datetime.datetime - :return: list of Investigation - :rtype: list[~azure.ai.discovery.models.Investigation] + :keyword top: The number of result items to return. Default value is None. + :paramtype top: int + :keyword skip: The number of result items to skip. Default value is None. + :paramtype skip: int + :return: PagedInvestigation. The PagedInvestigation is compatible with MutableMapping + :rtype: ~azure.ai.discovery.models.PagedInvestigation :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1485,11 +1748,15 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.Investigation]] = kwargs.pop("cls", None) + maxpagesize = kwargs.pop("maxpagesize", None) + cls: ClsType[_models.PagedInvestigation] = kwargs.pop("cls", None) _request = build_investigations_list_request( project_name=project_name, created_since=created_since, + top=top, + skip=skip, + maxpagesize=maxpagesize, api_version=self._config.api_version, headers=_headers, params=_params, @@ -1519,7 +1786,7 @@ def list( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(List[_models.Investigation], response.json()) + deserialized = _deserialize(_models.PagedInvestigation, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -1594,28 +1861,19 @@ def get_discovery_engine( @distributed_trace @api_version_validation( - method_added_on="2026-02-01-preview", + method_added_on="2026-06-01", params_added_on={ - "2026-02-01-preview": [ - "api_version", - "project_name", - "investigation_name", - "skip", - "top", - "max_page_size", - "accept", - ] + "2026-06-01": ["api_version", "project_name", "investigation_name", "top", "skip", "maxpagesize", "accept"] }, - api_versions_list=["2026-02-01-preview"], + api_versions_list=["2026-06-01"], ) def get_discovery_engine_memory( self, project_name: str, investigation_name: str, *, - skip: Optional[int] = None, top: Optional[int] = None, - max_page_size: Optional[int] = None, + skip: Optional[int] = None, **kwargs: Any ) -> _models.PagedWorkingMemoryEntry: """List discovery engine working memory entries for an investigation. @@ -1624,13 +1882,10 @@ def get_discovery_engine_memory( :type project_name: str :param investigation_name: The investigation name. Required. :type investigation_name: str - :keyword skip: Skip results. Default value is None. - :paramtype skip: int - :keyword top: Query the top results. Default value is None. + :keyword top: The number of result items to return. Default value is None. :paramtype top: int - :keyword max_page_size: Bound the number of results that come back in one response. Default - value is None. - :paramtype max_page_size: int + :keyword skip: The number of result items to skip. Default value is None. + :paramtype skip: int :return: PagedWorkingMemoryEntry. The PagedWorkingMemoryEntry is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.PagedWorkingMemoryEntry :raises ~azure.core.exceptions.HttpResponseError: @@ -1646,14 +1901,15 @@ def get_discovery_engine_memory( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} + maxpagesize = kwargs.pop("maxpagesize", None) cls: ClsType[_models.PagedWorkingMemoryEntry] = kwargs.pop("cls", None) _request = build_investigations_get_discovery_engine_memory_request( project_name=project_name, investigation_name=investigation_name, - skip=skip, top=top, - max_page_size=max_page_size, + skip=skip, + maxpagesize=maxpagesize, api_version=self._config.api_version, headers=_headers, params=_params, @@ -1855,7 +2111,7 @@ def update_discovery_engine( self, project_name: str, investigation_name: str, - body: JSON, + body: _types.DiscoveryEngineUpdate, *, content_type: str = "application/json", **kwargs: Any @@ -1869,7 +2125,7 @@ def update_discovery_engine( :type investigation_name: str :param body: The discovery engine update request. This will create the discovery engine if it does not already exist. Required. - :type body: JSON + :type body: ~azure.ai.discovery.types.DiscoveryEngineUpdate :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -1907,18 +2163,11 @@ def update_discovery_engine( """ @distributed_trace - @api_version_validation( - method_added_on="2025-12-01-preview", - params_added_on={ - "2025-12-01-preview": ["api_version", "project_name", "investigation_name", "content_type", "accept"] - }, - api_versions_list=["2025-12-01-preview", "2026-02-01-preview"], - ) def update_discovery_engine( self, project_name: str, investigation_name: str, - body: Union[_models.DiscoveryEngineUpdate, JSON, IO[bytes]], + body: Union[_models.DiscoveryEngineUpdate, _types.DiscoveryEngineUpdate, IO[bytes]], **kwargs: Any ) -> _models.DiscoveryEngine: """Update the discovery engine for an investigation. This will create the discovery engine if it @@ -1929,9 +2178,9 @@ def update_discovery_engine( :param investigation_name: The investigation name. Required. :type investigation_name: str :param body: The discovery engine update request. This will create the discovery engine if it - does not already exist. Is one of the following types: DiscoveryEngineUpdate, JSON, IO[bytes] - Required. - :type body: ~azure.ai.discovery.models.DiscoveryEngineUpdate or JSON or IO[bytes] + does not already exist. Is either a DiscoveryEngineUpdate type or a IO[bytes] type. Required. + :type body: ~azure.ai.discovery.models.DiscoveryEngineUpdate or + ~azure.ai.discovery.types.DiscoveryEngineUpdate or IO[bytes] :return: DiscoveryEngine. The DiscoveryEngine is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.DiscoveryEngine :raises ~azure.core.exceptions.HttpResponseError: @@ -2104,11 +2353,13 @@ def create( """ @overload - def create(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Conversation: + def create( + self, body: _types.CreateRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Conversation: """Creates a Conversation. :param body: Required. - :type body: JSON + :type body: ~azure.ai.discovery.types.CreateRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2134,7 +2385,7 @@ def create(self, body: IO[bytes], *, content_type: str = "application/json", **k @distributed_trace def create( self, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.CreateRequest, IO[bytes]] = _Unset, *, project_name: str = _Unset, investigation_name: Optional[str] = None, @@ -2143,8 +2394,8 @@ def create( ) -> _models.Conversation: """Creates a Conversation. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, CreateRequest, IO[bytes] Required. + :type body: JSON or ~azure.ai.discovery.types.CreateRequest or IO[bytes] :keyword project_name: The name of the associated Project. Required. :paramtype project_name: str :keyword investigation_name: The Name of the associated Investigation. Default value is None. @@ -2221,7 +2472,7 @@ def create( return deserialized # type: ignore @overload - def update( + def stable_update( self, conversation_name: str, resource: _models.Conversation, @@ -2244,10 +2495,10 @@ def update( """ @overload - def update( + def stable_update( self, conversation_name: str, - resource: JSON, + resource: _types.Conversation, *, content_type: str = "application/merge-patch+json", **kwargs: Any @@ -2257,7 +2508,7 @@ def update( :param conversation_name: The conversation name. Required. :type conversation_name: str :param resource: The resource instance. Required. - :type resource: JSON + :type resource: ~azure.ai.discovery.types.Conversation :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -2267,7 +2518,7 @@ def update( """ @overload - def update( + def stable_update( self, conversation_name: str, resource: IO[bytes], @@ -2290,16 +2541,25 @@ def update( """ @distributed_trace - def update( - self, conversation_name: str, resource: Union[_models.Conversation, JSON, IO[bytes]], **kwargs: Any + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "conversation_name", "content_type", "accept"]}, + api_versions_list=["2026-06-01"], + ) + def stable_update( + self, + conversation_name: str, + resource: Union[_models.Conversation, _types.Conversation, IO[bytes]], + **kwargs: Any ) -> _models.Conversation: """Updates a Conversation. :param conversation_name: The conversation name. Required. :type conversation_name: str - :param resource: The resource instance. Is one of the following types: Conversation, JSON, - IO[bytes] Required. - :type resource: ~azure.ai.discovery.models.Conversation or JSON or IO[bytes] + :param resource: The resource instance. Is either a Conversation type or a IO[bytes] type. + Required. + :type resource: ~azure.ai.discovery.models.Conversation or + ~azure.ai.discovery.types.Conversation or IO[bytes] :return: Conversation. The Conversation is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.Conversation :raises ~azure.core.exceptions.HttpResponseError: @@ -2325,7 +2585,7 @@ def update( else: _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_conversations_update_request( + _request = build_conversations_stable_update_request( conversation_name=conversation_name, content_type=content_type, api_version=self._config.api_version, @@ -2346,7 +2606,7 @@ def update( response = pipeline_response.http_response - if response.status_code not in [200, 201]: + if response.status_code not in [200]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -2414,14 +2674,32 @@ def delete(self, conversation_name: str, **kwargs: Any) -> None: # pylint: disa return cls(pipeline_response, None, {}) # type: ignore @distributed_trace + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={ + "2026-06-01": [ + "api_version", + "investigation_name", + "project_name", + "created_since", + "top", + "skip", + "maxpagesize", + "accept", + ] + }, + api_versions_list=["2026-06-01"], + ) def list( self, *, investigation_name: Optional[str] = None, project_name: Optional[str] = None, created_since: Optional[datetime.datetime] = None, + top: Optional[int] = None, + skip: Optional[int] = None, **kwargs: Any - ) -> List[_models.Conversation]: + ) -> _models.PagedConversation: """List Conversation resources. :keyword investigation_name: The name of the associated Investigation. Default value is None. @@ -2430,8 +2708,12 @@ def list( :paramtype project_name: str :keyword created_since: The oldest creation timestamp to keep. Default value is None. :paramtype created_since: ~datetime.datetime - :return: list of Conversation - :rtype: list[~azure.ai.discovery.models.Conversation] + :keyword top: The number of result items to return. Default value is None. + :paramtype top: int + :keyword skip: The number of result items to skip. Default value is None. + :paramtype skip: int + :return: PagedConversation. The PagedConversation is compatible with MutableMapping + :rtype: ~azure.ai.discovery.models.PagedConversation :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -2445,12 +2727,16 @@ def list( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.Conversation]] = kwargs.pop("cls", None) + maxpagesize = kwargs.pop("maxpagesize", None) + cls: ClsType[_models.PagedConversation] = kwargs.pop("cls", None) _request = build_conversations_list_request( investigation_name=investigation_name, project_name=project_name, created_since=created_since, + top=top, + skip=skip, + maxpagesize=maxpagesize, api_version=self._config.api_version, headers=_headers, params=_params, @@ -2480,7 +2766,7 @@ def list( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(List[_models.Conversation], response.json()) + deserialized = _deserialize(_models.PagedConversation, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -2506,10 +2792,6 @@ def __init__(self, *args, **kwargs) -> None: self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - @api_version_validation( - params_added_on={"2026-02-01-preview": ["log_count"]}, - api_versions_list=["2025-07-01-preview", "2025-12-01-preview", "2026-02-01-preview"], - ) def get_run_status( self, project_name: str, operation_id: str, *, log_count: Optional[int] = None, **kwargs: Any ) -> _models.OperationStatusRunResultError: @@ -2582,7 +2864,7 @@ def get_run_status( def _run_initial( self, project_name: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.RunRequest, IO[bytes]] = _Unset, *, tool_id: str = _Unset, node_pool_ids: List[str] = _Unset, @@ -2717,25 +2999,26 @@ def begin_run( Our parsing includes the following limited interpretation of special characters: - * The only special characters are " ' and \\. - * Backslashes `\\` escape the next character if that character is a special character, - preserving its literal value. - * Double quotes `"` preserve everything inside them literally, with the exception of the - characters " and \\, which must be escaped with a backslash `\\`. Unmatched quotes will throw - an error. - * Single quotes `'` preserve everything inside them literally. A single-quote cannot occur - within single-quotes. Unmatched quotes will throw an error. - - If you wish to run a command that relies on shell features such as globbing or output - redirection, you either need to: - - * use a container with an entrypoint that is a shell (e.g. `/bin/sh` or `/bin/bash`) and pass - a command which is valid for that shell e.g. - `-c 'python /code/wrapper.py --input /inputs/abcdef-input-1/* --output - /outputs/abcdef-output-1'` - * use a container which has a shell installed, and include the shell in the command, e.g. - `sh -c "python /code/wrapper.py --input /inputs/abcdef-input-1/* --output - /outputs/abcdef-output-1"`. Default value is None. + * The only special characters are the double-quote, the single-quote, and the + backslash. + * A backslash escapes the next character if that character is a special + character, preserving its literal value. + * Double-quotes preserve everything inside them literally, with the exception of + the double-quote and backslash characters, which must be escaped with a + backslash. Unmatched quotes will throw an error. + * Single-quotes preserve everything inside them literally. A single-quote cannot + occur within single-quotes. Unmatched quotes will throw an error. + + If you wish to run a command that relies on shell features such as globbing or + output redirection, you either need to: + + * use a container with an entrypoint that is a shell (for example, /bin/sh or + /bin/bash) and pass a command which is valid for that shell, for example + -c 'python /code/wrapper.py --input /inputs/abcdef-input-1/* --output + /outputs/abcdef-output-1' + * use a container which has a shell installed, and include the shell in the + command, for example sh -c "python /code/wrapper.py --input + /inputs/abcdef-input-1/* --output /outputs/abcdef-output-1". Default value is None. :paramtype command: str :keyword inline_files: Encoded inline files to be mounted into the container, e.g. for generated code. Default value is None. @@ -2759,14 +3042,14 @@ def begin_run( @overload def begin_run( - self, project_name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + self, project_name: str, body: _types.RunRequest, *, content_type: str = "application/json", **kwargs: Any ) -> LROPoller[_models.RunResult]: """Run the specified tool in the context of the specified project. :param project_name: Name of the associated Project. Required. :type project_name: str :param body: Required. - :type body: JSON + :type body: ~azure.ai.discovery.types.RunRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -2799,7 +3082,7 @@ def begin_run( def begin_run( self, project_name: str, - body: Union[JSON, IO[bytes]] = _Unset, + body: Union[JSON, _types.RunRequest, IO[bytes]] = _Unset, *, tool_id: str = _Unset, node_pool_ids: List[str] = _Unset, @@ -2815,8 +3098,8 @@ def begin_run( :param project_name: Name of the associated Project. Required. :type project_name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] + :param body: Is one of the following types: JSON, RunRequest, IO[bytes] Required. + :type body: JSON or ~azure.ai.discovery.types.RunRequest or IO[bytes] :keyword tool_id: ID of the tool to execute. Required. :paramtype tool_id: str :keyword node_pool_ids: IDs of NodePools to use for this run. Required. @@ -2841,25 +3124,26 @@ def begin_run( Our parsing includes the following limited interpretation of special characters: - * The only special characters are " ' and \\. - * Backslashes `\\` escape the next character if that character is a special character, - preserving its literal value. - * Double quotes `"` preserve everything inside them literally, with the exception of the - characters " and \\, which must be escaped with a backslash `\\`. Unmatched quotes will throw - an error. - * Single quotes `'` preserve everything inside them literally. A single-quote cannot occur - within single-quotes. Unmatched quotes will throw an error. - - If you wish to run a command that relies on shell features such as globbing or output - redirection, you either need to: - - * use a container with an entrypoint that is a shell (e.g. `/bin/sh` or `/bin/bash`) and pass - a command which is valid for that shell e.g. - `-c 'python /code/wrapper.py --input /inputs/abcdef-input-1/* --output - /outputs/abcdef-output-1'` - * use a container which has a shell installed, and include the shell in the command, e.g. - `sh -c "python /code/wrapper.py --input /inputs/abcdef-input-1/* --output - /outputs/abcdef-output-1"`. Default value is None. + * The only special characters are the double-quote, the single-quote, and the + backslash. + * A backslash escapes the next character if that character is a special + character, preserving its literal value. + * Double-quotes preserve everything inside them literally, with the exception of + the double-quote and backslash characters, which must be escaped with a + backslash. Unmatched quotes will throw an error. + * Single-quotes preserve everything inside them literally. A single-quote cannot + occur within single-quotes. Unmatched quotes will throw an error. + + If you wish to run a command that relies on shell features such as globbing or + output redirection, you either need to: + + * use a container with an entrypoint that is a shell (for example, /bin/sh or + /bin/bash) and pass a command which is valid for that shell, for example + -c 'python /code/wrapper.py --input /inputs/abcdef-input-1/* --output + /outputs/abcdef-output-1' + * use a container which has a shell installed, and include the shell in the + command, for example sh -c "python /code/wrapper.py --input + /inputs/abcdef-input-1/* --output /outputs/abcdef-output-1". Default value is None. :paramtype command: str :keyword inline_files: Encoded inline files to be mounted into the container, e.g. for generated code. Default value is None. @@ -2944,20 +3228,12 @@ def get_long_running_output(pipeline_response): self._client, raw_result, get_long_running_output, polling_method # type: ignore ) - @distributed_trace - def cancel_run( # pylint: disable=inconsistent-return-statements - self, project_name: str, operation_id: str, **kwargs: Any - ) -> None: - """Cancel an ongoing tool run. - - :param project_name: Name of the associated Project. Required. - :type project_name: str - :param operation_id: ID of the operation to cancel. Required. - :type operation_id: str - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "project_name", "operation_id", "accept"]}, + api_versions_list=["2026-06-01"], + ) + def _cancel_run_lro_initial(self, project_name: str, operation_id: str, **kwargs: Any) -> Iterator[bytes]: error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -2969,9 +3245,9 @@ def cancel_run( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - _request = build_tools_cancel_run_request( + _request = build_tools_cancel_run_lro_request( project_name=project_name, operation_id=operation_id, api_version=self._config.api_version, @@ -2983,7 +3259,8 @@ def cancel_run( # pylint: disable=inconsistent-return-statements } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _decompress = kwargs.pop("decompress", True) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -2991,40 +3268,112 @@ def cancel_run( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response if response.status_code not in [202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) + response_headers = {} + response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + if cls: - return cls(pipeline_response, None, {}) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace @api_version_validation( - method_added_on="2025-12-01-preview", - params_added_on={ - "2025-12-01-preview": ["api_version", "project_name", "skip", "top", "max_page_size", "accept"] - }, - api_versions_list=["2025-12-01-preview", "2026-02-01-preview"], + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "project_name", "operation_id", "accept"]}, + api_versions_list=["2026-06-01"], + ) + def begin_cancel_run_lro(self, project_name: str, operation_id: str, **kwargs: Any) -> LROPoller[_models.RunResult]: + """Cancel an ongoing tool run. + + :param project_name: Name of the associated Project. Required. + :type project_name: str + :param operation_id: ID of the operation to cancel. Required. + :type operation_id: str + :return: An instance of LROPoller that returns RunResult. The RunResult is compatible with + MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.ai.discovery.models.RunResult] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.RunResult] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._cancel_run_lro_initial( + project_name=project_name, + operation_id=operation_id, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response_headers = {} + response = pipeline_response.http_response + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + deserialized = _deserialize(_models.RunResult, response.json().get("result", {})) + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + return deserialized + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.RunResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.RunResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "project_name", "top", "skip", "maxpagesize", "accept"]}, + api_versions_list=["2026-06-01"], ) def get_operations( - self, - project_name: str, - *, - skip: Optional[int] = None, - top: Optional[int] = None, - max_page_size: Optional[int] = None, - **kwargs: Any + self, project_name: str, *, top: Optional[int] = None, skip: Optional[int] = None, **kwargs: Any ) -> _models.PagedOperation: """List tool runs. :param project_name: Name of the associated Project. Required. :type project_name: str - :keyword skip: Skip results (pagination control). Default value is None. - :paramtype skip: int - :keyword top: Query the top results (pagination control). Default value is None. + :keyword top: The number of result items to return. Default value is None. :paramtype top: int - :keyword max_page_size: Bound the number of results that come back in one response (pagination - control). Default value is None. - :paramtype max_page_size: int + :keyword skip: The number of result items to skip. Default value is None. + :paramtype skip: int :return: PagedOperation. The PagedOperation is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.PagedOperation :raises ~azure.core.exceptions.HttpResponseError: @@ -3040,13 +3389,14 @@ def get_operations( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} + maxpagesize = kwargs.pop("maxpagesize", None) cls: ClsType[_models.PagedOperation] = kwargs.pop("cls", None) _request = build_tools_get_operations_request( project_name=project_name, - skip=skip, top=top, - max_page_size=max_page_size, + skip=skip, + maxpagesize=maxpagesize, api_version=self._config.api_version, headers=_headers, params=_params, @@ -3084,11 +3434,6 @@ def get_operations( return deserialized # type: ignore @distributed_trace - @api_version_validation( - method_added_on="2025-12-01-preview", - params_added_on={"2025-12-01-preview": ["api_version", "project_name", "accept"]}, - api_versions_list=["2025-12-01-preview", "2026-02-01-preview"], - ) def get_compute_usage(self, project_name: str, **kwargs: Any) -> _models.ComputeUsage: """Examine compute usage. @@ -3294,7 +3639,10 @@ def prepare_request(next_link=None): ) _next_request_params["api-version"] = self._config.api_version _request = HttpRequest( - "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, ) path_format_arguments = { "endpoint": self._serialize.url( @@ -3363,7 +3711,7 @@ def create( self, project_name: str, investigation_name: str, - body: JSON, + body: _types.Task, *, content_type: str = "application/json", **kwargs: Any @@ -3375,7 +3723,7 @@ def create( :param investigation_name: The investigation name. Required. :type investigation_name: str :param body: Task creation request. Required. - :type body: JSON + :type body: ~azure.ai.discovery.types.Task :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3412,7 +3760,11 @@ def create( @distributed_trace def create( - self, project_name: str, investigation_name: str, body: Union[_models.Task, JSON, IO[bytes]], **kwargs: Any + self, + project_name: str, + investigation_name: str, + body: Union[_models.Task, _types.Task, IO[bytes]], + **kwargs: Any ) -> _models.Task: """Create a new task. @@ -3420,9 +3772,8 @@ def create( :type project_name: str :param investigation_name: The investigation name. Required. :type investigation_name: str - :param body: Task creation request. Is one of the following types: Task, JSON, IO[bytes] - Required. - :type body: ~azure.ai.discovery.models.Task or JSON or IO[bytes] + :param body: Task creation request. Is either a Task type or a IO[bytes] type. Required. + :type body: ~azure.ai.discovery.models.Task or ~azure.ai.discovery.types.Task or IO[bytes] :return: Task. The Task is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.Task :raises ~azure.core.exceptions.HttpResponseError: @@ -3490,7 +3841,7 @@ def create( return deserialized # type: ignore @overload - def update( + def stable_update( self, project_name: str, investigation_name: str, @@ -3520,12 +3871,12 @@ def update( """ @overload - def update( + def stable_update( self, project_name: str, investigation_name: str, task_name: str, - resource: JSON, + resource: _types.Task, *, content_type: str = "application/merge-patch+json", **kwargs: Any @@ -3540,7 +3891,7 @@ def update( :param task_name: The unique identifier of the task. Required. :type task_name: str :param resource: The resource instance. Required. - :type resource: JSON + :type resource: ~azure.ai.discovery.types.Task :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/merge-patch+json". :paramtype content_type: str @@ -3550,7 +3901,7 @@ def update( """ @overload - def update( + def stable_update( self, project_name: str, investigation_name: str, @@ -3580,12 +3931,19 @@ def update( """ @distributed_trace - def update( + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={ + "2026-06-01": ["api_version", "project_name", "investigation_name", "task_name", "content_type", "accept"] + }, + api_versions_list=["2026-06-01"], + ) + def stable_update( self, project_name: str, investigation_name: str, task_name: str, - resource: Union[_models.Task, JSON, IO[bytes]], + resource: Union[_models.Task, _types.Task, IO[bytes]], **kwargs: Any ) -> _models.Task: """Patch (partial update) a task (e.g. status, description, validation requirements, dependencies, @@ -3597,9 +3955,8 @@ def update( :type investigation_name: str :param task_name: The unique identifier of the task. Required. :type task_name: str - :param resource: The resource instance. Is one of the following types: Task, JSON, IO[bytes] - Required. - :type resource: ~azure.ai.discovery.models.Task or JSON or IO[bytes] + :param resource: The resource instance. Is either a Task type or a IO[bytes] type. Required. + :type resource: ~azure.ai.discovery.models.Task or ~azure.ai.discovery.types.Task or IO[bytes] :return: Task. The Task is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.Task :raises ~azure.core.exceptions.HttpResponseError: @@ -3625,7 +3982,7 @@ def update( else: _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_tasks_update_request( + _request = build_tasks_stable_update_request( project_name=project_name, investigation_name=investigation_name, task_name=task_name, @@ -3648,7 +4005,7 @@ def update( response = pipeline_response.http_response - if response.status_code not in [200, 201]: + if response.status_code not in [200]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -3758,7 +4115,7 @@ def start( project_name: str, investigation_name: str, task_name: str, - body: Optional[JSON] = None, + body: Optional[_types.StartTaskRequest] = None, *, content_type: str = "application/json", **kwargs: Any @@ -3772,7 +4129,7 @@ def start( :param task_name: The task name. Required. :type task_name: str :param body: Start task request body. Default value is None. - :type body: JSON + :type body: ~azure.ai.discovery.types.StartTaskRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3816,7 +4173,7 @@ def start( project_name: str, investigation_name: str, task_name: str, - body: Optional[Union[_models.StartTaskRequest, JSON, IO[bytes]]] = None, + body: Optional[Union[_models.StartTaskRequest, _types.StartTaskRequest, IO[bytes]]] = None, **kwargs: Any ) -> _models.Task: """Start execution of a task. @@ -3827,9 +4184,10 @@ def start( :type investigation_name: str :param task_name: The task name. Required. :type task_name: str - :param body: Start task request body. Is one of the following types: StartTaskRequest, JSON, - IO[bytes] Default value is None. - :type body: ~azure.ai.discovery.models.StartTaskRequest or JSON or IO[bytes] + :param body: Start task request body. Is either a StartTaskRequest type or a IO[bytes] type. + Default value is None. + :type body: ~azure.ai.discovery.models.StartTaskRequest or + ~azure.ai.discovery.types.StartTaskRequest or IO[bytes] :return: Task. The Task is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.Task :raises ~azure.core.exceptions.HttpResponseError: @@ -3904,9 +4262,9 @@ def start( @overload def add_comment( self, - task_name: str, project_name: str, investigation_name: str, + task_name: str, body: _models.TaskComment, *, content_type: str = "application/json", @@ -3914,12 +4272,12 @@ def add_comment( ) -> _models.Task: """Add a comment to a task. - :param task_name: The task name. Required. - :type task_name: str :param project_name: The project name. Required. :type project_name: str :param investigation_name: The investigation name. Required. :type investigation_name: str + :param task_name: The task name. Required. + :type task_name: str :param body: Comment to add. Required. :type body: ~azure.ai.discovery.models.TaskComment :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. @@ -3933,24 +4291,24 @@ def add_comment( @overload def add_comment( self, - task_name: str, project_name: str, investigation_name: str, - body: JSON, + task_name: str, + body: _types.TaskComment, *, content_type: str = "application/json", **kwargs: Any ) -> _models.Task: """Add a comment to a task. - :param task_name: The task name. Required. - :type task_name: str :param project_name: The project name. Required. :type project_name: str :param investigation_name: The investigation name. Required. :type investigation_name: str + :param task_name: The task name. Required. + :type task_name: str :param body: Comment to add. Required. - :type body: JSON + :type body: ~azure.ai.discovery.types.TaskComment :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -3962,9 +4320,9 @@ def add_comment( @overload def add_comment( self, - task_name: str, project_name: str, investigation_name: str, + task_name: str, body: IO[bytes], *, content_type: str = "application/json", @@ -3972,12 +4330,12 @@ def add_comment( ) -> _models.Task: """Add a comment to a task. - :param task_name: The task name. Required. - :type task_name: str :param project_name: The project name. Required. :type project_name: str :param investigation_name: The investigation name. Required. :type investigation_name: str + :param task_name: The task name. Required. + :type task_name: str :param body: Comment to add. Required. :type body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. @@ -3991,23 +4349,23 @@ def add_comment( @distributed_trace def add_comment( self, - task_name: str, project_name: str, investigation_name: str, - body: Union[_models.TaskComment, JSON, IO[bytes]], + task_name: str, + body: Union[_models.TaskComment, _types.TaskComment, IO[bytes]], **kwargs: Any ) -> _models.Task: """Add a comment to a task. - :param task_name: The task name. Required. - :type task_name: str :param project_name: The project name. Required. :type project_name: str :param investigation_name: The investigation name. Required. :type investigation_name: str - :param body: Comment to add. Is one of the following types: TaskComment, JSON, IO[bytes] - Required. - :type body: ~azure.ai.discovery.models.TaskComment or JSON or IO[bytes] + :param task_name: The task name. Required. + :type task_name: str + :param body: Comment to add. Is either a TaskComment type or a IO[bytes] type. Required. + :type body: ~azure.ai.discovery.models.TaskComment or ~azure.ai.discovery.types.TaskComment or + IO[bytes] :return: Task. The Task is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.Task :raises ~azure.core.exceptions.HttpResponseError: @@ -4034,9 +4392,9 @@ def add_comment( _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore _request = build_tasks_add_comment_request( - task_name=task_name, project_name=project_name, investigation_name=investigation_name, + task_name=task_name, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -4110,7 +4468,7 @@ def add_execution_history( project_name: str, investigation_name: str, task_name: str, - body: JSON, + body: _types.ExecutionHistoryEntry, *, content_type: str = "application/json", **kwargs: Any @@ -4124,7 +4482,7 @@ def add_execution_history( :param task_name: The task name. Required. :type task_name: str :param body: Execution history entry to add. Required. - :type body: JSON + :type body: ~azure.ai.discovery.types.ExecutionHistoryEntry :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -4168,7 +4526,7 @@ def add_execution_history( project_name: str, investigation_name: str, task_name: str, - body: Union[_models.ExecutionHistoryEntry, JSON, IO[bytes]], + body: Union[_models.ExecutionHistoryEntry, _types.ExecutionHistoryEntry, IO[bytes]], **kwargs: Any ) -> _models.Task: """Add an execution history entry to a task. @@ -4179,9 +4537,10 @@ def add_execution_history( :type investigation_name: str :param task_name: The task name. Required. :type task_name: str - :param body: Execution history entry to add. Is one of the following types: - ExecutionHistoryEntry, JSON, IO[bytes] Required. - :type body: ~azure.ai.discovery.models.ExecutionHistoryEntry or JSON or IO[bytes] + :param body: Execution history entry to add. Is either a ExecutionHistoryEntry type or a + IO[bytes] type. Required. + :type body: ~azure.ai.discovery.models.ExecutionHistoryEntry or + ~azure.ai.discovery.types.ExecutionHistoryEntry or IO[bytes] :return: Task. The Task is compatible with MutableMapping :rtype: ~azure.ai.discovery.models.Task :raises ~azure.core.exceptions.HttpResponseError: @@ -4248,3 +4607,1195 @@ def add_execution_history( return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + + +class KnowledgeBasesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.discovery.BookshelfClient`'s + :attr:`knowledge_bases` attribute. + """ + + def __init__(self, *args, **kwargs) -> None: + input_args = list(args) + self._client: PipelineClient = input_args.pop(0) if input_args else kwargs.pop("client") + self._config: BookshelfClientConfiguration = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize: Serializer = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "knowledge_base_name", "content_type", "accept"]}, + api_versions_list=["2026-06-01"], + ) + def _create_or_update_initial( + self, + knowledge_base_name: str, + resource: Union[_models.KnowledgeBase, _types.KnowledgeBase, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/merge-patch+json" + _content = None + if isinstance(resource, (IOBase, bytes)): + _content = resource + else: + _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_knowledge_bases_create_or_update_request( + knowledge_base_name=knowledge_base_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_create_or_update( + self, + knowledge_base_name: str, + resource: _models.KnowledgeBase, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> LROPoller[_models.KnowledgeBase]: + """Creates or updates a KnowledgeBase. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param resource: The resource instance. Required. + :type resource: ~azure.ai.discovery.models.KnowledgeBase + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/merge-patch+json". + :paramtype content_type: str + :return: An instance of LROPoller that returns KnowledgeBase. The KnowledgeBase is compatible + with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.ai.discovery.models.KnowledgeBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + knowledge_base_name: str, + resource: _types.KnowledgeBase, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> LROPoller[_models.KnowledgeBase]: + """Creates or updates a KnowledgeBase. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param resource: The resource instance. Required. + :type resource: ~azure.ai.discovery.types.KnowledgeBase + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/merge-patch+json". + :paramtype content_type: str + :return: An instance of LROPoller that returns KnowledgeBase. The KnowledgeBase is compatible + with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.ai.discovery.models.KnowledgeBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_create_or_update( + self, + knowledge_base_name: str, + resource: IO[bytes], + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> LROPoller[_models.KnowledgeBase]: + """Creates or updates a KnowledgeBase. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param resource: The resource instance. Required. + :type resource: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/merge-patch+json". + :paramtype content_type: str + :return: An instance of LROPoller that returns KnowledgeBase. The KnowledgeBase is compatible + with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.ai.discovery.models.KnowledgeBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "knowledge_base_name", "content_type", "accept"]}, + api_versions_list=["2026-06-01"], + ) + def begin_create_or_update( + self, + knowledge_base_name: str, + resource: Union[_models.KnowledgeBase, _types.KnowledgeBase, IO[bytes]], + **kwargs: Any + ) -> LROPoller[_models.KnowledgeBase]: + """Creates or updates a KnowledgeBase. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param resource: The resource instance. Is either a KnowledgeBase type or a IO[bytes] type. + Required. + :type resource: ~azure.ai.discovery.models.KnowledgeBase or + ~azure.ai.discovery.types.KnowledgeBase or IO[bytes] + :return: An instance of LROPoller that returns KnowledgeBase. The KnowledgeBase is compatible + with MutableMapping + :rtype: ~azure.core.polling.LROPoller[~azure.ai.discovery.models.KnowledgeBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.KnowledgeBase] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._create_or_update_initial( + knowledge_base_name=knowledge_base_name, + resource=resource, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): + response_headers = {} + response = pipeline_response.http_response + response_headers["Operation-Location"] = self._deserialize( + "str", response.headers.get("Operation-Location") + ) + + deserialized = _deserialize(_models.KnowledgeBase, response.json()) + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + return deserialized + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[_models.KnowledgeBase].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.KnowledgeBase]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @distributed_trace + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "knowledge_base_name", "accept"]}, + api_versions_list=["2026-06-01"], + ) + def get(self, knowledge_base_name: str, **kwargs: Any) -> _models.KnowledgeBase: + """Fetch a KnowledgeBase by name. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :return: KnowledgeBase. The KnowledgeBase is compatible with MutableMapping + :rtype: ~azure.ai.discovery.models.KnowledgeBase + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.KnowledgeBase] = kwargs.pop("cls", None) + + _request = build_knowledge_bases_get_request( + knowledge_base_name=knowledge_base_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.KnowledgeBase, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, **kwargs: Any) -> ItemPaged["_models.KnowledgeBase"]: + """List KnowledgeBase resources. + + :return: An iterator like instance of KnowledgeBase + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.discovery.models.KnowledgeBase] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.KnowledgeBase]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_knowledge_bases_list_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + headers=_headers, + params=_next_request_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.KnowledgeBase], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "knowledge_base_name", "operation_id", "accept"]}, + api_versions_list=["2026-06-01"], + ) + def get_operation_status( + self, knowledge_base_name: str, operation_id: str, **kwargs: Any + ) -> _models.KnowledgeBaseOperationResponse: + """Get the status of a long-running operation. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param operation_id: The unique ID of the operation. Required. + :type operation_id: str + :return: KnowledgeBaseOperationResponse. The KnowledgeBaseOperationResponse is compatible with + MutableMapping + :rtype: ~azure.ai.discovery.models.KnowledgeBaseOperationResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.KnowledgeBaseOperationResponse] = kwargs.pop("cls", None) + + _request = build_knowledge_bases_get_operation_status_request( + knowledge_base_name=knowledge_base_name, + operation_id=operation_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.KnowledgeBaseOperationResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={ + "2026-06-01": [ + "api_version", + "knowledge_base_name", + "repeatability_request_id", + "repeatability_first_sent", + "client_request_id", + "content_type", + "accept", + ] + }, + api_versions_list=["2026-06-01"], + ) + def _start_indexing_initial( + self, + knowledge_base_name: str, + body: Union[JSON, _types.StartIndexingRequest, IO[bytes]] = _Unset, + *, + node_pool_id: Optional[str] = None, + project_id: Optional[str] = None, + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + if body is _Unset: + body = {"nodePoolId": node_pool_id, "projectId": project_id} + body = {k: v for k, v in body.items() if v is not None} + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_knowledge_bases_start_indexing_request( + knowledge_base_name=knowledge_base_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) + response_headers["Repeatability-Result"] = self._deserialize( + "str", response.headers.get("Repeatability-Result") + ) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_start_indexing( + self, + knowledge_base_name: str, + *, + content_type: str = "application/json", + node_pool_id: Optional[str] = None, + project_id: Optional[str] = None, + **kwargs: Any + ) -> LROPoller[None]: + """Start indexing. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword node_pool_id: Node pool ID. Default value is None. + :paramtype node_pool_id: str + :keyword project_id: Project ID. Default value is None. + :paramtype project_id: str + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_start_indexing( + self, + knowledge_base_name: str, + body: _types.StartIndexingRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Start indexing. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param body: Required. + :type body: ~azure.ai.discovery.types.StartIndexingRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_start_indexing( + self, knowledge_base_name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[None]: + """Start indexing. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param body: Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={ + "2026-06-01": [ + "api_version", + "knowledge_base_name", + "repeatability_request_id", + "repeatability_first_sent", + "client_request_id", + "content_type", + "accept", + ] + }, + api_versions_list=["2026-06-01"], + ) + def begin_start_indexing( + self, + knowledge_base_name: str, + body: Union[JSON, _types.StartIndexingRequest, IO[bytes]] = _Unset, + *, + node_pool_id: Optional[str] = None, + project_id: Optional[str] = None, + **kwargs: Any + ) -> LROPoller[None]: + """Start indexing. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param body: Is one of the following types: JSON, StartIndexingRequest, IO[bytes] Required. + :type body: JSON or ~azure.ai.discovery.types.StartIndexingRequest or IO[bytes] + :keyword node_pool_id: Node pool ID. Default value is None. + :paramtype node_pool_id: str + :keyword project_id: Project ID. Default value is None. + :paramtype project_id: str + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._start_indexing_initial( + knowledge_base_name=knowledge_base_name, + body=body, + node_pool_id=node_pool_id, + project_id=project_id, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={ + "2026-06-01": [ + "api_version", + "knowledge_base_name", + "repeatability_request_id", + "repeatability_first_sent", + "client_request_id", + "accept", + ] + }, + api_versions_list=["2026-06-01"], + ) + def _cancel_indexing_initial(self, knowledge_base_name: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_knowledge_bases_cancel_indexing_request( + knowledge_base_name=knowledge_base_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) + response_headers["Repeatability-Result"] = self._deserialize( + "str", response.headers.get("Repeatability-Result") + ) + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={ + "2026-06-01": [ + "api_version", + "knowledge_base_name", + "repeatability_request_id", + "repeatability_first_sent", + "client_request_id", + "accept", + ] + }, + api_versions_list=["2026-06-01"], + ) + def begin_cancel_indexing(self, knowledge_base_name: str, **kwargs: Any) -> LROPoller[None]: + """Cancel indexing. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._cancel_indexing_initial( + knowledge_base_name=knowledge_base_name, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={ + "2026-06-01": [ + "api_version", + "knowledge_base_name", + "repeatability_request_id", + "repeatability_first_sent", + "client_request_id", + "content_type", + "accept", + ] + }, + api_versions_list=["2026-06-01"], + ) + def _search_initial( + self, + knowledge_base_name: str, + body: Union[_models.SearchRequest, _types.SearchRequest, IO[bytes]], + **kwargs: Any + ) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_knowledge_bases_search_request( + knowledge_base_name=knowledge_base_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + def begin_search( + self, + knowledge_base_name: str, + body: _models.SearchRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Search the knowledge base. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param body: The search request body. Required. + :type body: ~azure.ai.discovery.models.SearchRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_search( + self, + knowledge_base_name: str, + body: _types.SearchRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> LROPoller[None]: + """Search the knowledge base. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param body: The search request body. Required. + :type body: ~azure.ai.discovery.types.SearchRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def begin_search( + self, knowledge_base_name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[None]: + """Search the knowledge base. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param body: The search request body. Required. + :type body: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={ + "2026-06-01": [ + "api_version", + "knowledge_base_name", + "repeatability_request_id", + "repeatability_first_sent", + "client_request_id", + "content_type", + "accept", + ] + }, + api_versions_list=["2026-06-01"], + ) + def begin_search( + self, + knowledge_base_name: str, + body: Union[_models.SearchRequest, _types.SearchRequest, IO[bytes]], + **kwargs: Any + ) -> LROPoller[None]: + """Search the knowledge base. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :param body: The search request body. Is either a SearchRequest type or a IO[bytes] type. + Required. + :type body: ~azure.ai.discovery.models.SearchRequest or ~azure.ai.discovery.types.SearchRequest + or IO[bytes] + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._search_initial( + knowledge_base_name=knowledge_base_name, + body=body, + content_type=content_type, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore + + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "knowledge_base_name", "accept"]}, + api_versions_list=["2026-06-01"], + ) + def _delete_initial(self, knowledge_base_name: str, **kwargs: Any) -> Iterator[bytes]: + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_knowledge_bases_delete_request( + knowledge_base_name=knowledge_base_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _decompress = kwargs.pop("decompress", True) + _stream = True + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [202]: + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + @api_version_validation( + method_added_on="2026-06-01", + params_added_on={"2026-06-01": ["api_version", "knowledge_base_name", "accept"]}, + api_versions_list=["2026-06-01"], + ) + def begin_delete(self, knowledge_base_name: str, **kwargs: Any) -> LROPoller[None]: + """Delete a KnowledgeBase. + + :param knowledge_base_name: The knowledgeBase name. Required. + :type knowledge_base_name: str + :return: An instance of LROPoller that returns None + :rtype: ~azure.core.polling.LROPoller[None] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + polling: Union[bool, PollingMethod] = kwargs.pop("polling", True) + lro_delay = kwargs.pop("polling_interval", self._config.polling_interval) + cont_token: Optional[str] = kwargs.pop("continuation_token", None) + if cont_token is None: + raw_result = self._delete_initial( + knowledge_base_name=knowledge_base_name, + cls=lambda x, y, z: x, + headers=_headers, + params=_params, + **kwargs + ) + raw_result.http_response.read() # type: ignore + kwargs.pop("error_map", None) + + def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + + if polling is True: + polling_method: PollingMethod = cast( + PollingMethod, LROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs) + ) + elif polling is False: + polling_method = cast(PollingMethod, NoPolling()) + else: + polling_method = polling + if cont_token: + return LROPoller[None].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[None](self._client, raw_result, get_long_running_output, polling_method) # type: ignore diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/operations/_patch.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/operations/_patch.py new file mode 100644 index 000000000000..40a2e549b483 --- /dev/null +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/operations/_patch.py @@ -0,0 +1,131 @@ +# 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 +""" + +from typing import Any, IO, Union + +from azure.core.polling import LROPoller +from azure.core.polling.base_polling import ( + BadResponse, + LROBasePolling, + OperationResourcePolling, + _as_json, + _is_empty, +) + +from .. import models as _models +from ._operations import KnowledgeBasesOperations as _GeneratedKnowledgeBasesOperations + + +class _ProvisioningStatePolling(OperationResourcePolling): + """LRO polling that terminates on ``provisioningState`` instead of ``status``. + + The Bookshelf create/update LRO returns the ``KnowledgeBase`` resource as the + ``Operation-Location`` body. That body carries two status-like fields: + + * ``status`` -> the *indexing* lifecycle (``IndexingStatus``); for a freshly + created KB this stays ``NotStarted`` until indexing is separately started. + * ``provisioningState`` -> the create/update lifecycle (``Accepted`` -> + ``Succeeded``). + + Azure Core's default poller keys off ``status``, which never reaches a + create-terminal value during provisioning, so ``begin_create_or_update(...)`` + would poll forever even though the resource provisions successfully. This + override reads ``provisioningState`` (falling back to ``status`` only when + ``provisioningState`` is absent). + """ + + def get_status(self, pipeline_response: Any) -> str: + response = pipeline_response.http_response + if _is_empty(response): + raise BadResponse("The response from long running operation does not contain a body.") + body = _as_json(response) + status = body.get("provisioningState") or body.get("status") + if not status: + raise BadResponse("No provisioningState or status found in long running operation response.") + return status + + +class _CreateOrUpdatePolling(LROBasePolling): + """Create/update poller that tolerates a synchronous completion. + + ``begin_create_or_update`` is an upsert. Creating a new KnowledgeBase returns + ``201`` + ``Operation-Location`` -- a genuine LRO polled on + ``provisioningState`` via :class:`_ProvisioningStatePolling`. Updating an + *existing* KnowledgeBase can instead complete synchronously with ``200`` and + *no* ``Operation-Location`` header, and the default poller raises + ``BadResponse: Unable to find status link for polling`` in that case. This + poller treats a missing status link as an immediate success and returns the + resource from the initial response. + """ + + _synchronous: bool = False + + def initialize(self, client: Any, initial_response: Any, deserialization_callback: Any) -> None: + headers = initial_response.http_response.headers + if not (headers.get("Operation-Location") or headers.get("operation-location")): + # Synchronous completion: there is no long-running operation to poll. + self._client = client + self._pipeline_response = initial_response + self._initial_response = initial_response + self._deserialization_callback = deserialization_callback + # A (non-polling) operation instance keeps status()/resource() happy. + self._operation = _ProvisioningStatePolling() + self._status = "Succeeded" + self._synchronous = True + return + self._synchronous = False + super().initialize(client, initial_response, deserialization_callback) + + def run(self) -> None: + if getattr(self, "_synchronous", False): + return + super().run() + + +class KnowledgeBasesOperations(_GeneratedKnowledgeBasesOperations): + """KnowledgeBases operations with a corrected create/update LRO poller. + + See :class:`_ProvisioningStatePolling` and :class:`_CreateOrUpdatePolling` + for why the default poller is replaced. + """ + + def begin_create_or_update( # type: ignore[override] + self, + knowledge_base_name: str, + resource: Union[_models.KnowledgeBase, "dict[str, Any]", IO[bytes]], + **kwargs: Any, + ) -> LROPoller[_models.KnowledgeBase]: + # Only override the default poller; honor an explicitly supplied + # ``polling`` value (``False`` or a custom ``PollingMethod``). + if kwargs.get("polling", True) is True: + lro_delay = kwargs.get("polling_interval", self._config.polling_interval) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + kwargs["polling"] = _CreateOrUpdatePolling( + lro_delay, + lro_algorithms=[_ProvisioningStatePolling()], + path_format_arguments=path_format_arguments, + ) + return super().begin_create_or_update(knowledge_base_name, resource, **kwargs) # type: ignore[arg-type] + + +__all__: list[str] = [ + "KnowledgeBasesOperations", +] # 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/discovery/azure-ai-discovery/azure/ai/discovery/py.typed b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/py.typed index e69de29bb2d1..e5aff4f83af8 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/py.typed +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/types.py b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/types.py new file mode 100644 index 000000000000..21a8cd8ebf1a --- /dev/null +++ b/sdk/discovery/azure-ai-discovery/azure/ai/discovery/types.py @@ -0,0 +1,806 @@ +# pylint: disable=anomalous-backslash-in-string +# 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 +from typing_extensions import Required, TypedDict + +from azure.core.exceptions import ODataV4Format + +if TYPE_CHECKING: + from .models import ( + ByType, + IndexingStatus, + InvestigationStatus, + ProvisioningState, + StorageMountProtocol, + TaskPriority, + TaskStatus, + ) + + +class Conversation(TypedDict, total=False): + """A conversation. + + :ivar name: The conversation name. Required. + :vartype name: str + :ivar created_at: The timestamp when the resource was created. + :vartype created_at: str + :ivar created_by: The ID of the user who created this resource. + :vartype created_by: str + :ivar created_by_type: The type of user who created this resource. Known values are: "User", + "Application", and "System". + :vartype created_by_type: Union[str, "ByType"] + :ivar last_modified_at: The timestamp when the resource was last updated. + :vartype last_modified_at: str + :ivar last_modified_by: The ID of the user who updated this resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of user who updated this resource. Known values are: + "User", "Application", and "System". + :vartype last_modified_by_type: Union[str, "ByType"] + :ivar display_name: The title. + :vartype display_name: str + :ivar investigation_name: The Name of the associated Investigation. + :vartype investigation_name: str + :ivar project_name: The name of the associated Project. + :vartype project_name: str + """ + + name: Required[str] + """The conversation name. Required.""" + createdAt: str + """The timestamp when the resource was created.""" + createdBy: str + """The ID of the user who created this resource.""" + createdByType: Union[str, "ByType"] + """The type of user who created this resource. Known values are: \"User\", \"Application\", and + \"System\".""" + lastModifiedAt: str + """The timestamp when the resource was last updated.""" + lastModifiedBy: str + """The ID of the user who updated this resource.""" + lastModifiedByType: Union[str, "ByType"] + """The type of user who updated this resource. Known values are: \"User\", \"Application\", and + \"System\".""" + displayName: str + """The title.""" + investigationName: str + """The Name of the associated Investigation.""" + projectName: str + """The name of the associated Project.""" + + +class DiscoveryEngineUpdate(TypedDict, total=False): + """Discovery Engine Update Request. This will create the discovery engine if it does not already + exist. + + :ivar system_prompt: The system prompt. + :vartype system_prompt: str + :ivar configuration: The Discovery Engine configuration. + :vartype configuration: dict[str, Any] + """ + + systemPrompt: str + """The system prompt.""" + configuration: dict[str, Any] + """The Discovery Engine configuration.""" + + +class ExecutionHistoryEntry(TypedDict, total=False): + """Execution history entry for a task. + + :ivar created_at: Timestamp when the entry was created (ISO 8601 UTC format). Required. + :vartype created_at: str + :ivar action: The action that was performed (controlled vocabulary; semi-open). Required. + :vartype action: str + :ivar created_by: Identifier of who created this entry (GUID for user | resourceId for + application | arbitrary string for other types). Required. + :vartype created_by: str + :ivar created_by_type: Type of entity that created this entry (User, Application, System, or + custom type). Required. Known values are: "User", "Application", and "System". + :vartype created_by_type: Union[str, "ByType"] + :ivar summary: Brief summary of the execution event. + :vartype summary: str + :ivar response_message_text: Detailed completion message. + :vartype response_message_text: str + :ivar response_message_id: Run or message ID for full details. + :vartype response_message_id: str + :ivar additional_details: Freeform key-value pairs for additional details. + :vartype additional_details: dict[str, Any] + """ + + createdAt: Required[str] + """Timestamp when the entry was created (ISO 8601 UTC format). Required.""" + action: Required[str] + """The action that was performed (controlled vocabulary; semi-open). Required.""" + createdBy: Required[str] + """Identifier of who created this entry (GUID for user | resourceId for application | arbitrary + string for other types). Required.""" + createdByType: Required[Union[str, "ByType"]] + """Type of entity that created this entry (User, Application, System, or custom type). Required. + Known values are: \"User\", \"Application\", and \"System\".""" + summary: str + """Brief summary of the execution event.""" + responseMessageText: str + """Detailed completion message.""" + responseMessageId: str + """Run or message ID for full details.""" + additionalDetails: dict[str, Any] + """Freeform key-value pairs for additional details.""" + + +class IndexingMetrics(TypedDict, total=False): + """Indexing metrics for a run. + + :ivar documents_processed: The number of documents that were successfully processed. Required. + :vartype documents_processed: int + :ivar documents_failed: The number of documents that failed during indexing. Required. + :vartype documents_failed: int + :ivar documents_total: The total number of documents considered for indexing. Required. + :vartype documents_total: int + :ivar indexing_percentage_complete: The indexing completion percentage from 0 to 100. Required. + :vartype indexing_percentage_complete: int + :ivar enrichment_start_time_utc: The UTC timestamp when enrichment started. + :vartype enrichment_start_time_utc: str + :ivar enrichment_end_time_utc: The UTC timestamp when enrichment ended. + :vartype enrichment_end_time_utc: str + :ivar indexing_start_time_utc: The UTC timestamp when indexing started. + :vartype indexing_start_time_utc: str + :ivar indexing_end_time_utc: The UTC timestamp when indexing ended. + :vartype indexing_end_time_utc: str + """ + + documentsProcessed: Required[int] + """The number of documents that were successfully processed. Required.""" + documentsFailed: Required[int] + """The number of documents that failed during indexing. Required.""" + documentsTotal: Required[int] + """The total number of documents considered for indexing. Required.""" + indexingPercentageComplete: Required[int] + """The indexing completion percentage from 0 to 100. Required.""" + enrichmentStartTimeUtc: str + """The UTC timestamp when enrichment started.""" + enrichmentEndTimeUtc: str + """The UTC timestamp when enrichment ended.""" + indexingStartTimeUtc: str + """The UTC timestamp when indexing started.""" + indexingEndTimeUtc: str + """The UTC timestamp when indexing ended.""" + + +class InfraOverrides(TypedDict, total=False): + """Explicitly set tool run requirements - overrides the tool definition. + + :ivar cpu: Override CPU requirements (e.g. 1, or 500m for 500 milli-CPUs). + :vartype cpu: str + :ivar ram: Override RAM requirements (e.g. 500Mi or 1Gi). + :vartype ram: str + :ivar gpu: Override GPU count requirements. + :vartype gpu: str + :ivar replica_count: Override the number of replicas of the tool image to run. + :vartype replica_count: int + :ivar image_uri: Override the image to use for this tool run. + :vartype image_uri: str + :ivar max_cpu: Override the maximum CPU allowed for the tool run (e.g. 1, or 500m for 500 + milli-CPUs). + :vartype max_cpu: str + :ivar max_ram: Override the maximum RAM allowed for the tool run (e.g. 500Mi or 1Gi). + :vartype max_ram: str + :ivar max_gpu: Override the maximum GPU count allowed for the tool run. + :vartype max_gpu: str + """ + + cpu: str + """Override CPU requirements (e.g. 1, or 500m for 500 milli-CPUs).""" + ram: str + """Override RAM requirements (e.g. 500Mi or 1Gi).""" + gpu: str + """Override GPU count requirements.""" + replicaCount: int + """Override the number of replicas of the tool image to run.""" + imageUri: str + """Override the image to use for this tool run.""" + maxCpu: str + """Override the maximum CPU allowed for the tool run (e.g. 1, or 500m for 500 milli-CPUs).""" + maxRam: str + """Override the maximum RAM allowed for the tool run (e.g. 500Mi or 1Gi).""" + maxGpu: str + """Override the maximum GPU count allowed for the tool run.""" + + +class InlineFile(TypedDict, total=False): + """A file to be included in the input data for a tool run and the path where it will be mounted, + relative to the working directory. + + :ivar mount_path: Absolute path within the container at which to mount this file. Required. + :vartype mount_path: str + :ivar encoded_file: File contents: Compressed using .gz then base64-encoded. Required. + :vartype encoded_file: str + """ + + mountPath: Required[str] + """Absolute path within the container at which to mount this file. Required.""" + encodedFile: Required[str] + """File contents: Compressed using .gz then base64-encoded. Required.""" + + +class InputDataMount(TypedDict, total=False): + """Data URI and path where it will be mounted in the tool container. + + :ivar storage_uri: URI of input data to mount. Required. + :vartype storage_uri: str + :ivar mount_path: Absolute path within the container at which to mount this input. Required. + :vartype mount_path: str + :ivar mount_protocol: The protocol to use for mounting this storage. Overrides any value + specified on the storage container. Known values are: "NFS" and "BlobfuseCaching". + :vartype mount_protocol: Union[str, "StorageMountProtocol"] + """ + + storageUri: Required[str] + """URI of input data to mount. Required.""" + mountPath: Required[str] + """Absolute path within the container at which to mount this input. Required.""" + mountProtocol: Union[str, "StorageMountProtocol"] + """The protocol to use for mounting this storage. Overrides any value specified on the storage + container. Known values are: \"NFS\" and \"BlobfuseCaching\".""" + + +class Investigation(TypedDict, total=False): + """A investigation list item. + + :ivar name: The investigation name. Required. + :vartype name: str + :ivar project_name: The parent project name. Required. + :vartype project_name: str + :ivar created_at: The timestamp when the resource was created. + :vartype created_at: str + :ivar created_by: The ID of the user who created this resource. + :vartype created_by: str + :ivar created_by_type: The type of user who created this resource. Known values are: "User", + "Application", and "System". + :vartype created_by_type: Union[str, "ByType"] + :ivar last_modified_at: The timestamp when the resource was last updated. + :vartype last_modified_at: str + :ivar last_modified_by: The ID of the user who updated this resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of user who updated this resource. Known values are: + "User", "Application", and "System". + :vartype last_modified_by_type: Union[str, "ByType"] + :ivar status: The status. Known values are: "Created", "Validated", and "Failed". + :vartype status: Union[str, "InvestigationStatus"] + :ivar description: The description. + :vartype description: str + :ivar tags: The tags. + :vartype tags: list["Tag"] + :ivar display_name: The title. + :vartype display_name: str + """ + + name: Required[str] + """The investigation name. Required.""" + projectName: Required[str] + """The parent project name. Required.""" + createdAt: str + """The timestamp when the resource was created.""" + createdBy: str + """The ID of the user who created this resource.""" + createdByType: Union[str, "ByType"] + """The type of user who created this resource. Known values are: \"User\", \"Application\", and + \"System\".""" + lastModifiedAt: str + """The timestamp when the resource was last updated.""" + lastModifiedBy: str + """The ID of the user who updated this resource.""" + lastModifiedByType: Union[str, "ByType"] + """The type of user who updated this resource. Known values are: \"User\", \"Application\", and + \"System\".""" + status: Union[str, "InvestigationStatus"] + """The status. Known values are: \"Created\", \"Validated\", and \"Failed\".""" + description: str + """The description.""" + tags: list["Tag"] + """The tags.""" + displayName: str + """The title.""" + + +class KnowledgeBase(TypedDict, total=False): + """A knowledgeBase. + + :ivar name: The knowledgeBase name. Required. + :vartype name: str + :ivar id: The ID for the resource. + :vartype id: str + :ivar bookshelf_name: The name of the associated Bookshelf tracked resource. Required. + :vartype bookshelf_name: str + :ivar storage_asset_references: Storage asset references to index. + :vartype storage_asset_references: list["StorageAssetReference"] + :ivar knowledge_base_url: URL to access the knowledge base. + :vartype knowledge_base_url: str + :ivar provisioning_state: Provisioning state. Known values are: "Succeeded", "Failed", + "Canceled", "Accepted", "Provisioning", "Updating", and "Deleting". + :vartype provisioning_state: Union[str, "ProvisioningState"] + :ivar error: Error details if provisioning failed. + :vartype error: ODataV4Format + :ivar status: The status. Known values are: "NotStarted", "Running", "Succeeded", "Canceled", + and "Failed". + :vartype status: Union[str, "IndexingStatus"] + :ivar created_by_api_version: The API version used to create this knowledge base. + :vartype created_by_api_version: str + :ivar last_indexing_run: The details of the most recent indexing run. + :vartype last_indexing_run: "LastIndexingRun" + :ivar created_at: The timestamp when the resource was created. + :vartype created_at: str + :ivar created_by: The ID of the user who created this resource. + :vartype created_by: str + :ivar created_by_type: The type of user who created this resource. Known values are: "User", + "Application", and "System". + :vartype created_by_type: Union[str, "ByType"] + :ivar last_modified_at: The timestamp when the resource was last updated. + :vartype last_modified_at: str + :ivar last_modified_by: The ID of the user who updated this resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of user who updated this resource. Known values are: + "User", "Application", and "System". + :vartype last_modified_by_type: Union[str, "ByType"] + :ivar tags: The tags. + :vartype tags: list["Tag"] + :ivar description: The description. Required. + :vartype description: str + :ivar copilot_instruction: The copilot instruction. Required. + :vartype copilot_instruction: str + """ + + name: Required[str] + """The knowledgeBase name. Required.""" + id: str + """The ID for the resource.""" + bookshelfName: Required[str] + """The name of the associated Bookshelf tracked resource. Required.""" + storageAssetReferences: list["StorageAssetReference"] + """Storage asset references to index.""" + knowledgeBaseUrl: str + """URL to access the knowledge base.""" + provisioningState: Union[str, "ProvisioningState"] + """Provisioning state. Known values are: \"Succeeded\", \"Failed\", \"Canceled\", \"Accepted\", + \"Provisioning\", \"Updating\", and \"Deleting\".""" + error: ODataV4Format + """Error details if provisioning failed.""" + status: Union[str, "IndexingStatus"] + """The status. Known values are: \"NotStarted\", \"Running\", \"Succeeded\", \"Canceled\", and + \"Failed\".""" + createdByApiVersion: str + """The API version used to create this knowledge base.""" + lastIndexingRun: "LastIndexingRun" + """The details of the most recent indexing run.""" + createdAt: str + """The timestamp when the resource was created.""" + createdBy: str + """The ID of the user who created this resource.""" + createdByType: Union[str, "ByType"] + """The type of user who created this resource. Known values are: \"User\", \"Application\", and + \"System\".""" + lastModifiedAt: str + """The timestamp when the resource was last updated.""" + lastModifiedBy: str + """The ID of the user who updated this resource.""" + lastModifiedByType: Union[str, "ByType"] + """The type of user who updated this resource. Known values are: \"User\", \"Application\", and + \"System\".""" + tags: list["Tag"] + """The tags.""" + description: Required[str] + """The description. Required.""" + copilotInstruction: Required[str] + """The copilot instruction. Required.""" + + +class LastIndexingRun(TypedDict, total=False): + """The details of the last indexing run. + + :ivar run_id: The operation run identifier. + :vartype run_id: str + :ivar status: The status of the indexing run. Known values are: "NotStarted", "Running", + "Succeeded", "Canceled", and "Failed". + :vartype status: Union[str, "IndexingStatus"] + :ivar error: Error object that describes the error when status is 'Failed'. + :vartype error: ODataV4Format + :ivar indexing_metrics: Indexing metrics for the run. + :vartype indexing_metrics: "IndexingMetrics" + """ + + runId: str + """The operation run identifier.""" + status: Union[str, "IndexingStatus"] + """The status of the indexing run. Known values are: \"NotStarted\", \"Running\", \"Succeeded\", + \"Canceled\", and \"Failed\".""" + error: ODataV4Format + """Error object that describes the error when status is 'Failed'.""" + indexingMetrics: "IndexingMetrics" + """Indexing metrics for the run.""" + + +class OutputDataMount(TypedDict, total=False): + """Definition of a mount for collecting tool output data. + + :ivar storage_uri: URI of location to persist output to. Required. + :vartype storage_uri: str + :ivar mount_path: Absolute path within the container from which to collect output data. + Required. + :vartype mount_path: str + :ivar mount_protocol: The protocol to use for mounting this storage. Overrides any value + specified on the storage container. Known values are: "NFS" and "BlobfuseCaching". + :vartype mount_protocol: Union[str, "StorageMountProtocol"] + """ + + storageUri: Required[str] + """URI of location to persist output to. Required.""" + mountPath: Required[str] + """Absolute path within the container from which to collect output data. Required.""" + mountProtocol: Union[str, "StorageMountProtocol"] + """The protocol to use for mounting this storage. Overrides any value specified on the storage + container. Known values are: \"NFS\" and \"BlobfuseCaching\".""" + + +class RunRequestEnvironmentVariable(TypedDict, total=False): + """RunRequestEnvironmentVariable. + + :ivar name: Name of the environment variable. This must not contain any secrets. Required. + :vartype name: str + :ivar value: Value of the environment variable. This must not contain any secrets. + :vartype value: str + """ + + name: Required[str] + """Name of the environment variable. This must not contain any secrets. Required.""" + value: str + """Value of the environment variable. This must not contain any secrets.""" + + +class SearchRequest(TypedDict, total=False): + """The search action request body. + + :ivar query: The query text to search against the knowledge base. Required. + :vartype query: str + """ + + query: Required[str] + """The query text to search against the knowledge base. Required.""" + + +class StartTaskRequest(TypedDict, total=False): + """Request body for starting a task. + + :ivar assignee: Assignee that will execute the task. Optional. + :vartype assignee: "TaskAssignee" + """ + + assignee: "TaskAssignee" + """Assignee that will execute the task. Optional.""" + + +class StorageAssetReference(TypedDict, total=False): + """Reference to a storage asset with identity information. + + :ivar id: The ARM resource ID of the storage asset. Required. + :vartype id: str + :ivar user_assigned_identity: The ARM resource ID of the User Assigned Managed Identity to + access the storage asset. + :vartype user_assigned_identity: str + """ + + id: Required[str] + """The ARM resource ID of the storage asset. Required.""" + userAssignedIdentity: str + """The ARM resource ID of the User Assigned Managed Identity to access the storage asset.""" + + +class Tag(TypedDict, total=False): + """Definition of Tag. + + :ivar key: Property key. + :vartype key: str + :ivar value: Property value. + :vartype value: str + """ + + key: str + """Property key.""" + value: str + """Property value.""" + + +class Task(TypedDict, total=False): + """Task resource. + + :ivar name: The unique identifier of the task. Required. + :vartype name: str + :ivar title: The title of the task. + :vartype title: str + :ivar priority: The priority of the task. Known values are: "Low", "Medium", and "High". + :vartype priority: Union[str, "TaskPriority"] + :ivar description: The description of the task. + :vartype description: str + :ivar validation_requirements: Array of validation requirements for the task. + :vartype validation_requirements: list[str] + :ivar parent_id: ID of the parent task if this is a subtask. + :vartype parent_id: str + :ivar depends_on: IDs of tasks that must complete before this task can be executed. + :vartype depends_on: list[str] + :ivar related_to: IDs of tasks that are related to this task. + :vartype related_to: list[str] + :ivar assigned_to: Application or user assigned to this task. + :vartype assigned_to: "TaskAssignee" + :ivar comments: Comments or notes about the task. + :vartype comments: list["TaskComment"] + :ivar status: The current status of the task. Known values are: "New", "OnHold", "Complete", + "Removed", "FlaggedHuman", "FlaggedAi", "Executing", "ExecutionDone", "Stale", "Failed", and + "Incomplete". + :vartype status: Union[str, "TaskStatus"] + :ivar created_at: The timestamp when the resource was created. + :vartype created_at: str + :ivar created_by: The ID of the user who created this resource. + :vartype created_by: str + :ivar created_by_type: Type of entity that created the resource (User, Application, System, or + custom type). Known values are: "User", "Application", and "System". + :vartype created_by_type: Union[str, "ByType"] + :ivar last_modified_at: The timestamp when the resource was last updated. + :vartype last_modified_at: str + :ivar last_modified_by: The ID of the user who updated this resource. + :vartype last_modified_by: str + :ivar last_modified_by_type: The type of user who updated this resource. Known values are: + "User", "Application", and "System". + :vartype last_modified_by_type: Union[str, "ByType"] + :ivar execution_history: History of execution events for this task. + :vartype execution_history: list["ExecutionHistoryEntry"] + :ivar investigation_id: The investigation identifier associated with the task. + :vartype investigation_id: str + :ivar task_result: Task execution result with text and storage assets. + :vartype task_result: "TaskResult" + :ivar storage_asset_ids: List of storage assets related to the task. + :vartype storage_asset_ids: list[str] + """ + + name: Required[str] + """The unique identifier of the task. Required.""" + title: str + """The title of the task.""" + priority: Union[str, "TaskPriority"] + """The priority of the task. Known values are: \"Low\", \"Medium\", and \"High\".""" + description: str + """The description of the task.""" + validationRequirements: list[str] + """Array of validation requirements for the task.""" + parentId: str + """ID of the parent task if this is a subtask.""" + dependsOn: list[str] + """IDs of tasks that must complete before this task can be executed.""" + relatedTo: list[str] + """IDs of tasks that are related to this task.""" + assignedTo: "TaskAssignee" + """Application or user assigned to this task.""" + comments: list["TaskComment"] + """Comments or notes about the task.""" + status: Union[str, "TaskStatus"] + """The current status of the task. Known values are: \"New\", \"OnHold\", \"Complete\", + \"Removed\", \"FlaggedHuman\", \"FlaggedAi\", \"Executing\", \"ExecutionDone\", \"Stale\", + \"Failed\", and \"Incomplete\".""" + createdAt: str + """The timestamp when the resource was created.""" + createdBy: str + """The ID of the user who created this resource.""" + createdByType: Union[str, "ByType"] + """Type of entity that created the resource (User, Application, System, or custom type). Known + values are: \"User\", \"Application\", and \"System\".""" + lastModifiedAt: str + """The timestamp when the resource was last updated.""" + lastModifiedBy: str + """The ID of the user who updated this resource.""" + lastModifiedByType: Union[str, "ByType"] + """The type of user who updated this resource. Known values are: \"User\", \"Application\", and + \"System\".""" + executionHistory: list["ExecutionHistoryEntry"] + """History of execution events for this task.""" + investigationId: str + """The investigation identifier associated with the task.""" + taskResult: "TaskResult" + """Task execution result with text and storage assets.""" + storageAssetIds: list[str] + """List of storage assets related to the task.""" + + +class TaskAssignee(TypedDict, total=False): + """Task assignee information. + + :ivar id: The unique identifier of the assignee. Required. + :vartype id: str + :ivar type: Type of assignee (User, Application, System, or custom type). Required. Known + values are: "User", "Application", and "System". + :vartype type: Union[str, "ByType"] + """ + + id: Required[str] + """The unique identifier of the assignee. Required.""" + type: Required[Union[str, "ByType"]] + """Type of assignee (User, Application, System, or custom type). Required. Known values are: + \"User\", \"Application\", and \"System\".""" + + +class TaskComment(TypedDict, total=False): + """Task comment. + + :ivar timestamp: When the comment was created. + :vartype timestamp: str + :ivar created_by: ID of the user or application who created the comment. Required. + :vartype created_by: str + :ivar created_by_type: Type of creator (User, Application, System, or custom type). Required. + Known values are: "User", "Application", and "System". + :vartype created_by_type: Union[str, "ByType"] + :ivar text: The comment text content. Required. + :vartype text: str + """ + + timestamp: str + """When the comment was created.""" + createdBy: Required[str] + """ID of the user or application who created the comment. Required.""" + createdByType: Required[Union[str, "ByType"]] + """Type of creator (User, Application, System, or custom type). Required. Known values are: + \"User\", \"Application\", and \"System\".""" + text: Required[str] + """The comment text content. Required.""" + + +class TaskResult(TypedDict, total=False): + """Task execution result. + + :ivar text: The text content of the task result. + :vartype text: str + :ivar storage_asset_ids: Array of storage asset identifiers related to the result. + :vartype storage_asset_ids: list[str] + """ + + text: str + """The text content of the task result.""" + storageAssetIds: list[str] + """Array of storage asset identifiers related to the result.""" + + +class CreateRequest(TypedDict, total=False): + """CreateRequest. + + :ivar project_name: The name of the associated Project. Required. + :vartype project_name: str + :ivar investigation_name: The Name of the associated Investigation. + :vartype investigation_name: str + :ivar display_name: The title. + :vartype display_name: str + """ + + projectName: Required[str] + """The name of the associated Project. Required.""" + investigationName: str + """The Name of the associated Investigation.""" + displayName: str + """The title.""" + + +class RunRequest(TypedDict, total=False): + """RunRequest. + + :ivar tool_id: ID of the tool to execute. Required. + :vartype tool_id: str + :ivar command: Command to pass to tool container entrypoint. If the tool has multiple + containers defined, this command is executed on all of them. If omitted, all containers execute + their raw entrypoints. This command is parsed into an argument list which is passed to the + underlying container runtime. For example, if the command is "python /code/wrapper.py --input + /inputs/abcdef-input-1/input.txt --output /outputs/abcdef-output-1", then the container runtime + will receive the following argument list: ["python", "/code/wrapper.py", "--input", + "/inputs/abcdef-input-1/input.txt", "--output", "/outputs/abcdef-output-1"] The container's + entrypoint is not overridden. In Docker terminology, the above argument list becomes the CMD, + not the ENTRYPOINT of the launched container. Our parsing includes the following limited + interpretation of special characters: + + * The only special characters are the double-quote, the single-quote, and the + backslash. + * A backslash escapes the next character if that character is a special + character, preserving its literal value. + * Double-quotes preserve everything inside them literally, with the exception of + the double-quote and backslash characters, which must be escaped with a + backslash. Unmatched quotes will throw an error. + * Single-quotes preserve everything inside them literally. A single-quote cannot + occur within single-quotes. Unmatched quotes will throw an error. + + If you wish to run a command that relies on shell features such as globbing or + output redirection, you either need to: + + * use a container with an entrypoint that is a shell (for example, /bin/sh or + /bin/bash) and pass a command which is valid for that shell, for example + -c 'python /code/wrapper.py --input /inputs/abcdef-input-1/* --output + /outputs/abcdef-output-1' + * use a container which has a shell installed, and include the shell in the + command, for example sh -c "python /code/wrapper.py --input + /inputs/abcdef-input-1/* --output /outputs/abcdef-output-1". + :vartype command: str + :ivar inline_files: Encoded inline files to be mounted into the container, e.g. for generated + code. + :vartype inline_files: list["InlineFile"] + :ivar input_data: Input data references and mount paths. + :vartype input_data: list["InputDataMount"] + :ivar output_data: Output data references and mount paths. + :vartype output_data: list["OutputDataMount"] + :ivar node_pool_ids: IDs of NodePools to use for this run. Required. + :vartype node_pool_ids: list[str] + :ivar infra_overrides: Override the infrastructure requirements in the tool definitions. + :vartype infra_overrides: "InfraOverrides" + :ivar environment_variables: Optional environment variables to set in the tool container. This + must not contain any secrets. + :vartype environment_variables: list["RunRequestEnvironmentVariable"] + """ + + toolId: Required[str] + """ID of the tool to execute. Required.""" + command: str + """Command to pass to tool container entrypoint. If the tool has multiple containers defined, this + command is executed on all of them. If omitted, all containers execute their raw entrypoints. + This command is parsed into an argument list which is passed to the underlying container + runtime. For example, if the command is \"python /code/wrapper.py --input + /inputs/abcdef-input-1/input.txt --output /outputs/abcdef-output-1\", then the container + runtime will receive the following argument list: [\"python\", \"/code/wrapper.py\", + \"--input\", \"/inputs/abcdef-input-1/input.txt\", \"--output\", \"/outputs/abcdef-output-1\"] + The container's entrypoint is not overridden. In Docker terminology, the above argument list + becomes the CMD, not the ENTRYPOINT of the launched container. Our parsing includes the + following limited interpretation of special characters: + + * The only special characters are the double-quote, the single-quote, and the + backslash. + * A backslash escapes the next character if that character is a special + character, preserving its literal value. + * Double-quotes preserve everything inside them literally, with the exception of + the double-quote and backslash characters, which must be escaped with a + backslash. Unmatched quotes will throw an error. + * Single-quotes preserve everything inside them literally. A single-quote cannot + occur within single-quotes. Unmatched quotes will throw an error. + + If you wish to run a command that relies on shell features such as globbing or + output redirection, you either need to: + + * use a container with an entrypoint that is a shell (for example, /bin/sh or + /bin/bash) and pass a command which is valid for that shell, for example + -c 'python /code/wrapper.py --input /inputs/abcdef-input-1/* --output + /outputs/abcdef-output-1' + * use a container which has a shell installed, and include the shell in the + command, for example sh -c "python /code/wrapper.py --input + /inputs/abcdef-input-1/* --output /outputs/abcdef-output-1".""" + inlineFiles: list["InlineFile"] + """Encoded inline files to be mounted into the container, e.g. for generated code.""" + inputData: list["InputDataMount"] + """Input data references and mount paths.""" + outputData: list["OutputDataMount"] + """Output data references and mount paths.""" + nodePoolIds: Required[list[str]] + """IDs of NodePools to use for this run. Required.""" + infraOverrides: "InfraOverrides" + """Override the infrastructure requirements in the tool definitions.""" + environmentVariables: list["RunRequestEnvironmentVariable"] + """Optional environment variables to set in the tool container. This must not contain any secrets.""" + + +class StartIndexingRequest(TypedDict, total=False): + """StartIndexingRequest. + + :ivar node_pool_id: Node pool ID. + :vartype node_pool_id: str + :ivar project_id: Project ID. + :vartype project_id: str + """ + + nodePoolId: str + """Node pool ID.""" + projectId: str + """Project ID.""" diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/conftest.py b/sdk/discovery/azure-ai-discovery/generated_tests/conftest.py similarity index 68% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/conftest.py rename to sdk/discovery/azure-ai-discovery/generated_tests/conftest.py index 5ab2ff89f7c2..831a1be78988 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/conftest.py +++ b/sdk/discovery/azure-ai-discovery/generated_tests/conftest.py @@ -21,6 +21,15 @@ # For security, please avoid record sensitive identity information in recordings @pytest.fixture(scope="session", autouse=True) def add_sanitizers(test_proxy): + workspace_subscription_id = os.environ.get("WORKSPACE_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + workspace_tenant_id = os.environ.get("WORKSPACE_TENANT_ID", "00000000-0000-0000-0000-000000000000") + workspace_client_id = os.environ.get("WORKSPACE_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + workspace_client_secret = os.environ.get("WORKSPACE_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=workspace_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=workspace_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=workspace_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=workspace_client_secret, value="00000000-0000-0000-0000-000000000000") + bookshelf_subscription_id = os.environ.get("BOOKSHELF_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") bookshelf_tenant_id = os.environ.get("BOOKSHELF_TENANT_ID", "00000000-0000-0000-0000-000000000000") bookshelf_client_id = os.environ.get("BOOKSHELF_CLIENT_ID", "00000000-0000-0000-0000-000000000000") diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/test_bookshelf_knowledge_base_versions_operations.py b/sdk/discovery/azure-ai-discovery/generated_tests/test_bookshelf_knowledge_bases_operations.py similarity index 64% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/test_bookshelf_knowledge_base_versions_operations.py rename to sdk/discovery/azure-ai-discovery/generated_tests/test_bookshelf_knowledge_bases_operations.py index e465abbd7f59..da2029f5cdb7 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/test_bookshelf_knowledge_base_versions_operations.py +++ b/sdk/discovery/azure-ai-discovery/generated_tests/test_bookshelf_knowledge_bases_operations.py @@ -11,25 +11,40 @@ @pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestBookshelfKnowledgeBaseVersionsOperations(BookshelfClientTestBase): +class TestBookshelfKnowledgeBasesOperations(BookshelfClientTestBase): @BookshelfPreparer() @recorded_by_proxy - def test_knowledge_base_versions_create_or_update(self, bookshelf_endpoint): + def test_knowledge_bases_begin_create_or_update(self, bookshelf_endpoint): client = self.create_client(endpoint=bookshelf_endpoint) - response = client.knowledge_base_versions.create_or_update( + response = client.knowledge_bases.begin_create_or_update( knowledge_base_name="str", - version_name="str", resource={ "bookshelfName": "str", "copilotInstruction": "str", "description": "str", "name": "str", - "version": "str", "createdAt": "2020-02-20 00:00:00", "createdBy": "str", + "createdByApiVersion": "str", "createdByType": "str", + "error": ~azure.core.ODataV4Format, "id": "str", "knowledgeBaseUrl": "str", + "lastIndexingRun": { + "error": ~azure.core.ODataV4Format, + "indexingMetrics": { + "documentsFailed": 0, + "documentsProcessed": 0, + "documentsTotal": 0, + "indexingPercentageComplete": 0, + "enrichmentEndTimeUtc": "2020-02-20 00:00:00", + "enrichmentStartTimeUtc": "2020-02-20 00:00:00", + "indexingEndTimeUtc": "2020-02-20 00:00:00", + "indexingStartTimeUtc": "2020-02-20 00:00:00", + }, + "runId": "str", + "status": "str", + }, "lastModifiedAt": "2020-02-20 00:00:00", "lastModifiedBy": "str", "lastModifiedByType": "str", @@ -38,28 +53,16 @@ def test_knowledge_base_versions_create_or_update(self, bookshelf_endpoint): "storageAssetReferences": [{"id": "str", "userAssignedIdentity": "str"}], "tags": [{"key": "str", "value": "str"}], }, - ) - - # please add some check logic here by yourself - # ... - - @BookshelfPreparer() - @recorded_by_proxy - def test_knowledge_base_versions_get(self, bookshelf_endpoint): - client = self.create_client(endpoint=bookshelf_endpoint) - response = client.knowledge_base_versions.get( - knowledge_base_name="str", - version_name="str", - ) + ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself # ... @BookshelfPreparer() @recorded_by_proxy - def test_knowledge_base_versions_get_latest_version(self, bookshelf_endpoint): + def test_knowledge_bases_get(self, bookshelf_endpoint): client = self.create_client(endpoint=bookshelf_endpoint) - response = client.knowledge_base_versions.get_latest_version( + response = client.knowledge_bases.get( knowledge_base_name="str", ) @@ -68,22 +71,19 @@ def test_knowledge_base_versions_get_latest_version(self, bookshelf_endpoint): @BookshelfPreparer() @recorded_by_proxy - def test_knowledge_base_versions_list(self, bookshelf_endpoint): + def test_knowledge_bases_list(self, bookshelf_endpoint): client = self.create_client(endpoint=bookshelf_endpoint) - response = client.knowledge_base_versions.list( - knowledge_base_name="str", - ) + response = client.knowledge_bases.list() result = [r for r in response] # please add some check logic here by yourself # ... @BookshelfPreparer() @recorded_by_proxy - def test_knowledge_base_versions_get_operation_status(self, bookshelf_endpoint): + def test_knowledge_bases_get_operation_status(self, bookshelf_endpoint): client = self.create_client(endpoint=bookshelf_endpoint) - response = client.knowledge_base_versions.get_operation_status( + response = client.knowledge_bases.get_operation_status( knowledge_base_name="str", - version_name="str", operation_id="str", ) @@ -92,13 +92,11 @@ def test_knowledge_base_versions_get_operation_status(self, bookshelf_endpoint): @BookshelfPreparer() @recorded_by_proxy - def test_knowledge_base_versions_begin_start_indexing(self, bookshelf_endpoint): + def test_knowledge_bases_begin_start_indexing(self, bookshelf_endpoint): client = self.create_client(endpoint=bookshelf_endpoint) - response = client.knowledge_base_versions.begin_start_indexing( + response = client.knowledge_bases.begin_start_indexing( knowledge_base_name="str", - version_name="str", body={"nodePoolId": "str", "projectId": "str"}, - node_pool_id="str", ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself @@ -106,13 +104,10 @@ def test_knowledge_base_versions_begin_start_indexing(self, bookshelf_endpoint): @BookshelfPreparer() @recorded_by_proxy - def test_knowledge_base_versions_begin_cancel_indexing(self, bookshelf_endpoint): + def test_knowledge_bases_begin_cancel_indexing(self, bookshelf_endpoint): client = self.create_client(endpoint=bookshelf_endpoint) - response = client.knowledge_base_versions.begin_cancel_indexing( + response = client.knowledge_bases.begin_cancel_indexing( knowledge_base_name="str", - version_name="str", - body={"nodePoolId": "str", "projectId": "str"}, - node_pool_id="str", ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself @@ -120,11 +115,11 @@ def test_knowledge_base_versions_begin_cancel_indexing(self, bookshelf_endpoint) @BookshelfPreparer() @recorded_by_proxy - def test_knowledge_base_versions_begin_delete(self, bookshelf_endpoint): + def test_knowledge_bases_begin_search(self, bookshelf_endpoint): client = self.create_client(endpoint=bookshelf_endpoint) - response = client.knowledge_base_versions.begin_delete( + response = client.knowledge_bases.begin_search( knowledge_base_name="str", - version_name="str", + body={"query": "str"}, ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself @@ -132,9 +127,9 @@ def test_knowledge_base_versions_begin_delete(self, bookshelf_endpoint): @BookshelfPreparer() @recorded_by_proxy - def test_knowledge_base_versions_begin_delete_latest_version(self, bookshelf_endpoint): + def test_knowledge_bases_begin_delete(self, bookshelf_endpoint): client = self.create_client(endpoint=bookshelf_endpoint) - response = client.knowledge_base_versions.begin_delete_latest_version( + response = client.knowledge_bases.begin_delete( knowledge_base_name="str", ).result() # call '.result()' to poll until service return final result diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/test_bookshelf_knowledge_base_versions_operations_async.py b/sdk/discovery/azure-ai-discovery/generated_tests/test_bookshelf_knowledge_bases_operations_async.py similarity index 51% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/test_bookshelf_knowledge_base_versions_operations_async.py rename to sdk/discovery/azure-ai-discovery/generated_tests/test_bookshelf_knowledge_bases_operations_async.py index 0361bc0768ff..b0574beb56f1 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/test_bookshelf_knowledge_base_versions_operations_async.py +++ b/sdk/discovery/azure-ai-discovery/generated_tests/test_bookshelf_knowledge_bases_operations_async.py @@ -12,55 +12,60 @@ @pytest.mark.skip("you may need to update the auto-generated test case before run it") -class TestBookshelfKnowledgeBaseVersionsOperationsAsync(BookshelfClientTestBaseAsync): +class TestBookshelfKnowledgeBasesOperationsAsync(BookshelfClientTestBaseAsync): @BookshelfPreparer() @recorded_by_proxy_async - async def test_knowledge_base_versions_create_or_update(self, bookshelf_endpoint): + async def test_knowledge_bases_begin_create_or_update(self, bookshelf_endpoint): client = self.create_async_client(endpoint=bookshelf_endpoint) - response = await client.knowledge_base_versions.create_or_update( - knowledge_base_name="str", - version_name="str", - resource={ - "bookshelfName": "str", - "copilotInstruction": "str", - "description": "str", - "name": "str", - "version": "str", - "createdAt": "2020-02-20 00:00:00", - "createdBy": "str", - "createdByType": "str", - "id": "str", - "knowledgeBaseUrl": "str", - "lastModifiedAt": "2020-02-20 00:00:00", - "lastModifiedBy": "str", - "lastModifiedByType": "str", - "provisioningState": "str", - "status": "str", - "storageAssetReferences": [{"id": "str", "userAssignedIdentity": "str"}], - "tags": [{"key": "str", "value": "str"}], - }, - ) - - # please add some check logic here by yourself - # ... - - @BookshelfPreparer() - @recorded_by_proxy_async - async def test_knowledge_base_versions_get(self, bookshelf_endpoint): - client = self.create_async_client(endpoint=bookshelf_endpoint) - response = await client.knowledge_base_versions.get( - knowledge_base_name="str", - version_name="str", - ) + response = await ( + await client.knowledge_bases.begin_create_or_update( + knowledge_base_name="str", + resource={ + "bookshelfName": "str", + "copilotInstruction": "str", + "description": "str", + "name": "str", + "createdAt": "2020-02-20 00:00:00", + "createdBy": "str", + "createdByApiVersion": "str", + "createdByType": "str", + "error": ~azure.core.ODataV4Format, + "id": "str", + "knowledgeBaseUrl": "str", + "lastIndexingRun": { + "error": ~azure.core.ODataV4Format, + "indexingMetrics": { + "documentsFailed": 0, + "documentsProcessed": 0, + "documentsTotal": 0, + "indexingPercentageComplete": 0, + "enrichmentEndTimeUtc": "2020-02-20 00:00:00", + "enrichmentStartTimeUtc": "2020-02-20 00:00:00", + "indexingEndTimeUtc": "2020-02-20 00:00:00", + "indexingStartTimeUtc": "2020-02-20 00:00:00", + }, + "runId": "str", + "status": "str", + }, + "lastModifiedAt": "2020-02-20 00:00:00", + "lastModifiedBy": "str", + "lastModifiedByType": "str", + "provisioningState": "str", + "status": "str", + "storageAssetReferences": [{"id": "str", "userAssignedIdentity": "str"}], + "tags": [{"key": "str", "value": "str"}], + }, + ) + ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself # ... @BookshelfPreparer() @recorded_by_proxy_async - async def test_knowledge_base_versions_get_latest_version(self, bookshelf_endpoint): + async def test_knowledge_bases_get(self, bookshelf_endpoint): client = self.create_async_client(endpoint=bookshelf_endpoint) - response = await client.knowledge_base_versions.get_latest_version( + response = await client.knowledge_bases.get( knowledge_base_name="str", ) @@ -69,22 +74,19 @@ async def test_knowledge_base_versions_get_latest_version(self, bookshelf_endpoi @BookshelfPreparer() @recorded_by_proxy_async - async def test_knowledge_base_versions_list(self, bookshelf_endpoint): + async def test_knowledge_bases_list(self, bookshelf_endpoint): client = self.create_async_client(endpoint=bookshelf_endpoint) - response = client.knowledge_base_versions.list( - knowledge_base_name="str", - ) + response = client.knowledge_bases.list() result = [r async for r in response] # please add some check logic here by yourself # ... @BookshelfPreparer() @recorded_by_proxy_async - async def test_knowledge_base_versions_get_operation_status(self, bookshelf_endpoint): + async def test_knowledge_bases_get_operation_status(self, bookshelf_endpoint): client = self.create_async_client(endpoint=bookshelf_endpoint) - response = await client.knowledge_base_versions.get_operation_status( + response = await client.knowledge_bases.get_operation_status( knowledge_base_name="str", - version_name="str", operation_id="str", ) @@ -93,14 +95,12 @@ async def test_knowledge_base_versions_get_operation_status(self, bookshelf_endp @BookshelfPreparer() @recorded_by_proxy_async - async def test_knowledge_base_versions_begin_start_indexing(self, bookshelf_endpoint): + async def test_knowledge_bases_begin_start_indexing(self, bookshelf_endpoint): client = self.create_async_client(endpoint=bookshelf_endpoint) response = await ( - await client.knowledge_base_versions.begin_start_indexing( + await client.knowledge_bases.begin_start_indexing( knowledge_base_name="str", - version_name="str", body={"nodePoolId": "str", "projectId": "str"}, - node_pool_id="str", ) ).result() # call '.result()' to poll until service return final result @@ -109,14 +109,11 @@ async def test_knowledge_base_versions_begin_start_indexing(self, bookshelf_endp @BookshelfPreparer() @recorded_by_proxy_async - async def test_knowledge_base_versions_begin_cancel_indexing(self, bookshelf_endpoint): + async def test_knowledge_bases_begin_cancel_indexing(self, bookshelf_endpoint): client = self.create_async_client(endpoint=bookshelf_endpoint) response = await ( - await client.knowledge_base_versions.begin_cancel_indexing( + await client.knowledge_bases.begin_cancel_indexing( knowledge_base_name="str", - version_name="str", - body={"nodePoolId": "str", "projectId": "str"}, - node_pool_id="str", ) ).result() # call '.result()' to poll until service return final result @@ -125,12 +122,12 @@ async def test_knowledge_base_versions_begin_cancel_indexing(self, bookshelf_end @BookshelfPreparer() @recorded_by_proxy_async - async def test_knowledge_base_versions_begin_delete(self, bookshelf_endpoint): + async def test_knowledge_bases_begin_search(self, bookshelf_endpoint): client = self.create_async_client(endpoint=bookshelf_endpoint) response = await ( - await client.knowledge_base_versions.begin_delete( + await client.knowledge_bases.begin_search( knowledge_base_name="str", - version_name="str", + body={"query": "str"}, ) ).result() # call '.result()' to poll until service return final result @@ -139,10 +136,10 @@ async def test_knowledge_base_versions_begin_delete(self, bookshelf_endpoint): @BookshelfPreparer() @recorded_by_proxy_async - async def test_knowledge_base_versions_begin_delete_latest_version(self, bookshelf_endpoint): + async def test_knowledge_bases_begin_delete(self, bookshelf_endpoint): client = self.create_async_client(endpoint=bookshelf_endpoint) response = await ( - await client.knowledge_base_versions.begin_delete_latest_version( + await client.knowledge_bases.begin_delete( knowledge_base_name="str", ) ).result() # call '.result()' to poll until service return final result diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_conversations_operations.py b/sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_conversations_operations.py similarity index 95% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_conversations_operations.py rename to sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_conversations_operations.py index c868b53f57d5..8b0bf3d8efc4 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_conversations_operations.py +++ b/sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_conversations_operations.py @@ -37,9 +37,9 @@ def test_conversations_create(self, workspace_endpoint): @WorkspacePreparer() @recorded_by_proxy - def test_conversations_update(self, workspace_endpoint): + def test_conversations_stable_update(self, workspace_endpoint): client = self.create_client(endpoint=workspace_endpoint) - response = client.conversations.update( + response = client.conversations.stable_update( conversation_name="str", resource={ "name": "str", diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_conversations_operations_async.py b/sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_conversations_operations_async.py similarity index 95% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_conversations_operations_async.py rename to sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_conversations_operations_async.py index 4016e6f104c9..091e5d05e793 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_conversations_operations_async.py +++ b/sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_conversations_operations_async.py @@ -38,9 +38,9 @@ async def test_conversations_create(self, workspace_endpoint): @WorkspacePreparer() @recorded_by_proxy_async - async def test_conversations_update(self, workspace_endpoint): + async def test_conversations_stable_update(self, workspace_endpoint): client = self.create_async_client(endpoint=workspace_endpoint) - response = await client.conversations.update( + response = await client.conversations.stable_update( conversation_name="str", resource={ "name": "str", diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_investigations_operations.py b/sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_investigations_operations.py similarity index 96% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_investigations_operations.py rename to sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_investigations_operations.py index f684b828b082..4bb7f7073cf0 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_investigations_operations.py +++ b/sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_investigations_operations.py @@ -65,9 +65,9 @@ def test_investigations_create_or_replace(self, workspace_endpoint): @WorkspacePreparer() @recorded_by_proxy - def test_investigations_create_or_update(self, workspace_endpoint): + def test_investigations_update(self, workspace_endpoint): client = self.create_client(endpoint=workspace_endpoint) - response = client.investigations.create_or_update( + response = client.investigations.update( project_name="str", investigation_name="str", resource={ @@ -167,7 +167,7 @@ def test_investigations_update_discovery_engine(self, workspace_endpoint): response = client.investigations.update_discovery_engine( project_name="str", investigation_name="str", - body={"configuration": {"str": {}}, "discoveryEngineStatus": "str", "systemPrompt": "str"}, + body={"configuration": {"str": {}}, "systemPrompt": "str"}, ) # please add some check logic here by yourself diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_investigations_operations_async.py b/sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_investigations_operations_async.py similarity index 96% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_investigations_operations_async.py rename to sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_investigations_operations_async.py index 37247c7c76c7..15c86cd6adbe 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_investigations_operations_async.py +++ b/sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_investigations_operations_async.py @@ -66,9 +66,9 @@ async def test_investigations_create_or_replace(self, workspace_endpoint): @WorkspacePreparer() @recorded_by_proxy_async - async def test_investigations_create_or_update(self, workspace_endpoint): + async def test_investigations_update(self, workspace_endpoint): client = self.create_async_client(endpoint=workspace_endpoint) - response = await client.investigations.create_or_update( + response = await client.investigations.update( project_name="str", investigation_name="str", resource={ @@ -170,7 +170,7 @@ async def test_investigations_update_discovery_engine(self, workspace_endpoint): response = await client.investigations.update_discovery_engine( project_name="str", investigation_name="str", - body={"configuration": {"str": {}}, "discoveryEngineStatus": "str", "systemPrompt": "str"}, + body={"configuration": {"str": {}}, "systemPrompt": "str"}, ) # please add some check logic here by yourself diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_tasks_operations.py b/sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_tasks_operations.py similarity index 98% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_tasks_operations.py rename to sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_tasks_operations.py index 67fb92a68d71..1098ac7d71a3 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_tasks_operations.py +++ b/sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_tasks_operations.py @@ -87,9 +87,9 @@ def test_tasks_create(self, workspace_endpoint): @WorkspacePreparer() @recorded_by_proxy - def test_tasks_update(self, workspace_endpoint): + def test_tasks_stable_update(self, workspace_endpoint): client = self.create_client(endpoint=workspace_endpoint) - response = client.tasks.update( + response = client.tasks.stable_update( project_name="str", investigation_name="str", task_name="str", @@ -165,9 +165,9 @@ def test_tasks_start(self, workspace_endpoint): def test_tasks_add_comment(self, workspace_endpoint): client = self.create_client(endpoint=workspace_endpoint) response = client.tasks.add_comment( - task_name="str", project_name="str", investigation_name="str", + task_name="str", body={"createdBy": "str", "createdByType": "str", "text": "str", "timestamp": "2020-02-20 00:00:00"}, ) diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_tasks_operations_async.py b/sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_tasks_operations_async.py similarity index 98% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_tasks_operations_async.py rename to sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_tasks_operations_async.py index c23b026686cb..d318bb5ba426 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_tasks_operations_async.py +++ b/sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_tasks_operations_async.py @@ -88,9 +88,9 @@ async def test_tasks_create(self, workspace_endpoint): @WorkspacePreparer() @recorded_by_proxy_async - async def test_tasks_update(self, workspace_endpoint): + async def test_tasks_stable_update(self, workspace_endpoint): client = self.create_async_client(endpoint=workspace_endpoint) - response = await client.tasks.update( + response = await client.tasks.stable_update( project_name="str", investigation_name="str", task_name="str", @@ -166,9 +166,9 @@ async def test_tasks_start(self, workspace_endpoint): async def test_tasks_add_comment(self, workspace_endpoint): client = self.create_async_client(endpoint=workspace_endpoint) response = await client.tasks.add_comment( - task_name="str", project_name="str", investigation_name="str", + task_name="str", body={"createdBy": "str", "createdByType": "str", "text": "str", "timestamp": "2020-02-20 00:00:00"}, ) diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_tools_operations.py b/sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_tools_operations.py similarity index 82% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_tools_operations.py rename to sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_tools_operations.py index ade09c18b6cb..38e4256e3602 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_tools_operations.py +++ b/sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_tools_operations.py @@ -35,10 +35,19 @@ def test_tools_begin_run(self, workspace_endpoint): "toolId": "str", "command": "str", "environmentVariables": [{"name": "str", "value": "str"}], - "infraOverrides": {"cpu": "str", "gpu": "str", "imageUri": "str", "ram": "str", "replicaCount": 0}, + "infraOverrides": { + "cpu": "str", + "gpu": "str", + "imageUri": "str", + "maxCpu": "str", + "maxGpu": "str", + "maxRam": "str", + "ram": "str", + "replicaCount": 0, + }, "inlineFiles": [{"encodedFile": "str", "mountPath": "str"}], - "inputData": [{"mountPath": "str", "storageUri": "str"}], - "outputData": [{"mountPath": "str", "storageUri": "str"}], + "inputData": [{"mountPath": "str", "storageUri": "str", "mountProtocol": "str"}], + "outputData": [{"mountPath": "str", "storageUri": "str", "mountProtocol": "str"}], }, tool_id="str", node_pool_ids=["str"], @@ -49,12 +58,12 @@ def test_tools_begin_run(self, workspace_endpoint): @WorkspacePreparer() @recorded_by_proxy - def test_tools_cancel_run(self, workspace_endpoint): + def test_tools_begin_cancel_run_lro(self, workspace_endpoint): client = self.create_client(endpoint=workspace_endpoint) - response = client.tools.cancel_run( + response = client.tools.begin_cancel_run_lro( project_name="str", operation_id="str", - ) + ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself # ... diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_tools_operations_async.py b/sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_tools_operations_async.py similarity index 79% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_tools_operations_async.py rename to sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_tools_operations_async.py index 7e0dab576e9a..c924394d1909 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/test_workspace_tools_operations_async.py +++ b/sdk/discovery/azure-ai-discovery/generated_tests/test_workspace_tools_operations_async.py @@ -37,10 +37,19 @@ async def test_tools_begin_run(self, workspace_endpoint): "toolId": "str", "command": "str", "environmentVariables": [{"name": "str", "value": "str"}], - "infraOverrides": {"cpu": "str", "gpu": "str", "imageUri": "str", "ram": "str", "replicaCount": 0}, + "infraOverrides": { + "cpu": "str", + "gpu": "str", + "imageUri": "str", + "maxCpu": "str", + "maxGpu": "str", + "maxRam": "str", + "ram": "str", + "replicaCount": 0, + }, "inlineFiles": [{"encodedFile": "str", "mountPath": "str"}], - "inputData": [{"mountPath": "str", "storageUri": "str"}], - "outputData": [{"mountPath": "str", "storageUri": "str"}], + "inputData": [{"mountPath": "str", "storageUri": "str", "mountProtocol": "str"}], + "outputData": [{"mountPath": "str", "storageUri": "str", "mountProtocol": "str"}], }, tool_id="str", node_pool_ids=["str"], @@ -52,12 +61,14 @@ async def test_tools_begin_run(self, workspace_endpoint): @WorkspacePreparer() @recorded_by_proxy_async - async def test_tools_cancel_run(self, workspace_endpoint): + async def test_tools_begin_cancel_run_lro(self, workspace_endpoint): client = self.create_async_client(endpoint=workspace_endpoint) - response = await client.tools.cancel_run( - project_name="str", - operation_id="str", - ) + response = await ( + await client.tools.begin_cancel_run_lro( + project_name="str", + operation_id="str", + ) + ).result() # call '.result()' to poll until service return final result # please add some check logic here by yourself # ... diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/testpreparer.py b/sdk/discovery/azure-ai-discovery/generated_tests/testpreparer.py similarity index 66% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/testpreparer.py rename to sdk/discovery/azure-ai-discovery/generated_tests/testpreparer.py index 25e63554e089..991b183b5fb9 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_bookshelf/generated_tests/testpreparer.py +++ b/sdk/discovery/azure-ai-discovery/generated_tests/testpreparer.py @@ -5,11 +5,27 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from azure.ai.discovery import BookshelfClient +from azure.ai.discovery import BookshelfClient, WorkspaceClient from devtools_testutils import AzureRecordedTestCase, PowerShellPreparer import functools +class WorkspaceClientTestBase(AzureRecordedTestCase): + + def create_client(self, endpoint): + credential = self.get_credential(WorkspaceClient) + return self.create_client_from_credential( + WorkspaceClient, + credential=credential, + endpoint=endpoint, + ) + + +WorkspacePreparer = functools.partial( + PowerShellPreparer, "workspace", workspace_endpoint="https://fake_workspace_endpoint.com" +) + + class BookshelfClientTestBase(AzureRecordedTestCase): def create_client(self, endpoint): diff --git a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/testpreparer_async.py b/sdk/discovery/azure-ai-discovery/generated_tests/testpreparer_async.py similarity index 67% rename from sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/testpreparer_async.py rename to sdk/discovery/azure-ai-discovery/generated_tests/testpreparer_async.py index ef2ee6fd64f4..d11608e495bb 100644 --- a/sdk/discovery/azure-ai-discovery/azure/ai/discovery/_workspace/generated_tests/testpreparer_async.py +++ b/sdk/discovery/azure-ai-discovery/generated_tests/testpreparer_async.py @@ -5,7 +5,7 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from azure.ai.discovery.aio import WorkspaceClient +from azure.ai.discovery.aio import BookshelfClient, WorkspaceClient from devtools_testutils import AzureRecordedTestCase @@ -18,3 +18,14 @@ def create_async_client(self, endpoint): credential=credential, endpoint=endpoint, ) + + +class BookshelfClientTestBaseAsync(AzureRecordedTestCase): + + def create_async_client(self, endpoint): + credential = self.get_credential(BookshelfClient, is_async=True) + return self.create_client_from_credential( + BookshelfClient, + credential=credential, + endpoint=endpoint, + ) diff --git a/sdk/discovery/azure-ai-discovery/pyproject.toml b/sdk/discovery/azure-ai-discovery/pyproject.toml index af373f34222c..8d0a6075311f 100644 --- a/sdk/discovery/azure-ai-discovery/pyproject.toml +++ b/sdk/discovery/azure-ai-discovery/pyproject.toml @@ -1,6 +1,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. # -------------------------------------------------------------------------- [build-system] @@ -15,17 +17,17 @@ authors = [ description = "Microsoft Corporation Azure AI Discovery Client Library for Python" license = "MIT" classifiers = [ - "Development Status :: 4 - Beta", + "Development Status :: 5 - Production/Stable", "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", ] -requires-python = ">=3.9" +requires-python = ">=3.10" keywords = ["azure", "azure sdk"] dependencies = [ @@ -53,8 +55,6 @@ exclude = [ "doc*", "azure", "azure.ai", - "_workspace*", - "_bookshelf*", ] [tool.setuptools.package-data] @@ -62,3 +62,6 @@ exclude = [ [tool.azure-sdk-build] verifytypes = false + +[tool.pytest.ini_options] +asyncio_mode = "auto" diff --git a/sdk/discovery/azure-ai-discovery/samples/sample_conversations.py b/sdk/discovery/azure-ai-discovery/samples/sample_conversations.py index 3f87976c4e64..7d5032829525 100644 --- a/sdk/discovery/azure-ai-discovery/samples/sample_conversations.py +++ b/sdk/discovery/azure-ai-discovery/samples/sample_conversations.py @@ -46,11 +46,16 @@ def sample_conversations(): conversation_name = conversation.name - # List conversations in the project - conversations = list(client.conversations.list(project_name=project_name)) - print(f"\nFound {len(conversations)} conversation(s):") - for conv in conversations: + # List conversations in the project. The list operation returns a + # ``PagedConversation`` envelope with a ``value`` list of items and an + # optional ``next_link`` for the next page. Iterating the model directly + # would iterate its field names, so always access ``.value``. + page = client.conversations.list(project_name=project_name) + print(f"\nFound {len(page.value)} conversation(s) on the first page:") + for conv in page.value: print(f" - {conv.name}: {conv.display_name}") + if page.next_link: + print(f" (additional pages available via next_link={page.next_link})") # Get a specific conversation fetched = client.conversations.get(conversation_name=conversation_name) diff --git a/sdk/discovery/azure-ai-discovery/samples/sample_investigations.py b/sdk/discovery/azure-ai-discovery/samples/sample_investigations.py index 6c29016d714f..bd81b0c148a3 100644 --- a/sdk/discovery/azure-ai-discovery/samples/sample_investigations.py +++ b/sdk/discovery/azure-ai-discovery/samples/sample_investigations.py @@ -45,11 +45,15 @@ def sample_investigations(): print(f" Status: {investigation.status}") print(f" Created at: {investigation.created_at}") - # List all investigations in the project - investigations = list(client.investigations.list(project_name=project_name)) - print(f"\nFound {len(investigations)} investigation(s):") - for inv in investigations: + # List all investigations in the project. ``list`` returns a + # ``PagedInvestigation`` envelope with ``.value`` (items) and optional + # ``.next_link``. Always read ``.value`` rather than iterating the model. + page = client.investigations.list(project_name=project_name) + print(f"\nFound {len(page.value)} investigation(s) on the first page:") + for inv in page.value: print(f" - {inv.name} ({inv.status})") + if page.next_link: + print(f" (additional pages available via next_link={page.next_link})") # Get a specific investigation fetched = client.investigations.get( diff --git a/sdk/discovery/azure-ai-discovery/samples/sample_knowledge_bases.py b/sdk/discovery/azure-ai-discovery/samples/sample_knowledge_bases.py index 9bbc36a96d98..241a26aec2f1 100644 --- a/sdk/discovery/azure-ai-discovery/samples/sample_knowledge_bases.py +++ b/sdk/discovery/azure-ai-discovery/samples/sample_knowledge_bases.py @@ -4,9 +4,14 @@ # ------------------------------------ """ DESCRIPTION: - This sample demonstrates how to manage knowledge bases and their - versions using the BookshelfClient. Knowledge bases store indexed - data that can be queried by the Discovery Engine. + This sample demonstrates how to manage knowledge bases using the + BookshelfClient. Knowledge bases store indexed data that can be queried + via the long-running ``search`` operation. + + As of API version ``2026-06-01`` (GA), the previously separate + ``KnowledgeBaseVersions`` operation group has been folded into the + unified ``KnowledgeBases`` surface. Lifecycle, indexing, and search are + all expressed as long-running operations on the knowledge base itself. USAGE: python sample_knowledge_bases.py @@ -26,7 +31,7 @@ def sample_knowledge_bases(): import os from azure.identity import DefaultAzureCredential from azure.ai.discovery import BookshelfClient - from azure.ai.discovery.models import KnowledgeBaseVersion, StorageAssetReference + from azure.ai.discovery.models import KnowledgeBase, SearchRequest, StorageAssetReference endpoint = os.environ["AZURE_DISCOVERY_BOOKSHELF_ENDPOINT"] knowledge_base_name = os.environ["AZURE_DISCOVERY_KNOWLEDGE_BASE_NAME"] @@ -40,17 +45,17 @@ def sample_knowledge_bases(): credential=DefaultAzureCredential(), ) - # List all knowledge bases - knowledge_bases = list(client.knowledge_bases.list()) - print(f"Found {len(knowledge_bases)} knowledge base(s):") - for kb in knowledge_bases: + # List all knowledge bases. Unlike the Workspace list operations, this one + # returns an ItemPaged[KnowledgeBase] and supports transparent paging. + print("Listing knowledge bases:") + for kb in client.knowledge_bases.list(): print(f" - {kb.name}") - # Create or update a knowledge base version - version = client.knowledge_base_versions.create_or_update( + # Create or update a knowledge base (long-running). The final result is the + # KnowledgeBase resource (name, description, status, etc.). + create_poller = client.knowledge_bases.begin_create_or_update( knowledge_base_name=knowledge_base_name, - version_name="v1", - resource=KnowledgeBaseVersion( + resource=KnowledgeBase( description="Research data for compound analysis", copilot_instruction="Use this to query information about compound interactions.", storage_asset_references=[ @@ -61,39 +66,41 @@ def sample_knowledge_bases(): ], ), ) - print(f"\nCreated version: {version.name}") - print(f" Description: {version.description}") - - # List versions for a knowledge base - versions = list(client.knowledge_base_versions.list(knowledge_base_name=knowledge_base_name)) - print(f"\nVersions for '{knowledge_base_name}':") - for v in versions: - print(f" - {v.name}") + final = create_poller.result() + print(f"\nCreated or updated knowledge base: {final.name}") + print(f" Description: {final.description}") + print(f" Provisioning state: {final.provisioning_state}") - # Get the latest version - latest = client.knowledge_base_versions.get_latest_version( - knowledge_base_name=knowledge_base_name, - ) - print(f"\nLatest version: {latest.name}") + # Get a specific knowledge base by name + fetched = client.knowledge_bases.get(knowledge_base_name=knowledge_base_name) + print(f"\nFetched knowledge base: {fetched.name}") + print(f" Indexing status: {fetched.status}") - # Start indexing the knowledge base version - poller = client.knowledge_base_versions.begin_start_indexing( + # Start indexing (long-running). The poller resolves to None on completion; + # post-indexing state can be re-read via ``get`` or the + # ``get_operation_status`` operation. + indexing_poller = client.knowledge_bases.begin_start_indexing( knowledge_base_name=knowledge_base_name, - version_name="v1", node_pool_id=node_pool_id, project_id=project_arm_id, ) - print("\nIndexing started. Waiting for completion...") - result = poller.result() - print(f"Indexing complete: {result.name}") + print("\nIndexing started; waiting for completion...") + indexing_poller.result() + print("Indexing complete.") - # Get a specific version - fetched = client.knowledge_base_versions.get( + # Search the knowledge base (long-running). The poller currently resolves + # to None; the textual results are surfaced via the operation-status + # endpoint (KnowledgeBaseSearchOperationResponse). Real workflows would + # poll get_operation_status with the operation id from the LRO headers. + client.knowledge_bases.begin_search( knowledge_base_name=knowledge_base_name, - version_name="v1", - ) - print(f"\nFetched version: {fetched.name}") - print(f" Indexing status: {fetched.status}") + body=SearchRequest(query="What are common drug interactions?"), + ).result() + print("\nSearch submitted.") + + # Delete the knowledge base (long-running). Returns None on completion. + client.knowledge_bases.begin_delete(knowledge_base_name=knowledge_base_name).result() + print(f"\nDeleted knowledge base: {knowledge_base_name}") if __name__ == "__main__": diff --git a/sdk/discovery/azure-ai-discovery/tests/conftest.py b/sdk/discovery/azure-ai-discovery/tests/conftest.py index 52b0b9937940..31f175fa0aae 100644 --- a/sdk/discovery/azure-ai-discovery/tests/conftest.py +++ b/sdk/discovery/azure-ai-discovery/tests/conftest.py @@ -8,6 +8,7 @@ This module configures the test environment for both recorded (playback) and live tests. Uses devtools_testutils for Azure SDK test infrastructure. """ + import os import pytest from dotenv import load_dotenv @@ -24,7 +25,6 @@ test_proxy, ) - # Environment Variables for test configuration # Set AZURE_TEST_RUN_LIVE=true to run live tests # Otherwise tests run in playback mode using recorded responses @@ -46,12 +46,12 @@ def add_sanitizers(test_proxy): # Sanitize workspace endpoints in URLs add_general_regex_sanitizer( regex=r"https://[a-zA-Z0-9-]+\.workspace[a-zA-Z0-9-]*\.discovery\.azure\.com", - value="https://test-workspace.workspace.discovery.azure.com", + value="https://test-wkspc.workspace.discovery.azure.com", ) # Sanitize bookshelf endpoints in URLs add_general_regex_sanitizer( regex=r"https://[a-zA-Z0-9-]+\.bookshelf[a-zA-Z0-9-]*\.discovery\.azure\.com", - value="https://test-bookshelf.bookshelf.discovery.azure.com", + value="https://test-bkshlf.bookshelf.discovery.azure.com", ) # Sanitize bogus Location header (service returns https://example.com for LROs) # Replace with empty string so the LRO poller uses operation-location instead diff --git a/sdk/discovery/azure-ai-discovery/tests/constants.py b/sdk/discovery/azure-ai-discovery/tests/constants.py index 6e8fc2261ac1..3a4f1ff52836 100644 --- a/sdk/discovery/azure-ai-discovery/tests/constants.py +++ b/sdk/discovery/azure-ai-discovery/tests/constants.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. @@ -7,6 +8,7 @@ Values are loaded from environment variables with sensible defaults. Set these in the .env file (loaded by conftest.py via load_dotenv()). """ + import os # Workspace @@ -22,7 +24,6 @@ ) KNOWLEDGE_BASE_NAME = os.environ.get("KNOWLEDGE_BASE_NAME", "test-kb") KNOWLEDGE_BASE_VERSION = os.environ.get("KNOWLEDGE_BASE_VERSION", "v1") -KNOWLEDGE_BASE_CREATE_NAME = os.environ.get("KNOWLEDGE_BASE_CREATE_NAME", "test-kb-create") KNOWLEDGE_BASE_DESCRIPTION = os.environ.get( "KNOWLEDGE_BASE_DESCRIPTION", "Use this tool to query information about immersion cooling systems or liquid cooling technologies.", @@ -33,7 +34,7 @@ ) STORAGE_ASSET_ID = os.environ.get( "STORAGE_ASSET_ID", - "/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/test-rg/providers/microsoft.discovery/storagecontainers/test-storage/storageassets/test-sa", + "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/storagecontainers/test-storage/storageAssets/test-sa", ) USER_ASSIGNED_IDENTITY = os.environ.get( "USER_ASSIGNED_IDENTITY", @@ -52,10 +53,6 @@ "NODE_POOL_ID", "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", ) -BOOKSHELF_NODE_POOL_ID = os.environ.get( - "BOOKSHELF_NODE_POOL_ID", - "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodepools/test-pool", -) OPERATION_ID = os.environ.get("OPERATION_ID", "test-operation-id") PROJECT_ARM_ID = os.environ.get( diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_conversations.pyTestConversationstest_create.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_conversations.pyTestConversationstest_create.json deleted file mode 100644 index 952774bfa04e..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_conversations.pyTestConversationstest_create.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/conversations?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "163", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "displayName": "Test conversation", - "projectName": "test-project", - "investigationName": "/projects/test-project/investigations/test-invst" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:54:44 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "00000000-0000-0000-0000-000000000000", - "displayName": "Test conversation", - "investigationName": "projects/test-project/investigations/test-invst", - "projectName": "test-project", - "createdAt": "2026-05-15T23:54:44.7992456Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-15T23:54:44.7992456Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User" - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_conversations.pyTestConversationstest_delete.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_conversations.pyTestConversationstest_delete.json deleted file mode 100644 index ef72d197887a..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_conversations.pyTestConversationstest_delete.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/conversations/00000000-0000-0000-0000-000000000000?api-version=2026-02-01-preview", - "RequestMethod": "DELETE", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "Content-Length": "0", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 204, - "ResponseHeaders": { - "Connection": "keep-alive", - "Date": "Fri, 15 May 2026 23:55:04 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": null - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_conversations.pyTestConversationstest_get.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_conversations.pyTestConversationstest_get.json deleted file mode 100644 index 7a3e31805df4..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_conversations.pyTestConversationstest_get.json +++ /dev/null @@ -1,77 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/conversations?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "171", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "displayName": "Conversation for get test", - "projectName": "test-project", - "investigationName": "/projects/test-project/investigations/test-invst" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:54:53 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "00000000-0000-0000-0000-000000000000", - "displayName": "Conversation for get test", - "investigationName": "projects/test-project/investigations/test-invst", - "projectName": "test-project", - "createdAt": "2026-05-15T23:54:53.2462072Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-15T23:54:53.2462072Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User" - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/conversations/00000000-0000-0000-0000-000000000000?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:54:55 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "00000000-0000-0000-0000-000000000000", - "displayName": "Conversation for get test", - "investigationName": "projects/test-project/investigations/test-invst", - "projectName": "test-project", - "createdAt": "2026-05-15T23:54:53.2462072Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-15T23:54:53.2462072Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User" - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_conversations.pyTestConversationstest_list.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_conversations.pyTestConversationstest_list.json deleted file mode 100644 index 5e78627fb5b3..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_conversations.pyTestConversationstest_list.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/conversations?api-version=2026-02-01-preview&projectName=test-project", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:54:48 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": "[{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"invst-sdk-test-b3c873\",\"investigationName\":\"projects/test-project/investigations/invst-sdk-test-b3c873\",\"projectName\":\"test-project\",\"createdAt\":\"2026-04-28T17:27:47.8100012Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-04-28T17:27:47.8100012Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Test conversation\",\"investigationName\":\"projects/test-project/investigations/invst-sdk-test-b3c873\",\"projectName\":\"test-project\",\"createdAt\":\"2026-04-28T23:31:44.5184615Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-04-28T23:31:44.5184615Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Test conversation\",\"investigationName\":\"projects/test-project/investigations/invst-sdk-test-b3c873\",\"projectName\":\"test-project\",\"createdAt\":\"2026-04-28T23:33:17.2237464Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-04-28T23:33:17.2237464Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Conversation for get test\",\"investigationName\":\"projects/test-project/investigations/invst-sdk-test-b3c873\",\"projectName\":\"test-project\",\"createdAt\":\"2026-04-28T23:33:25.3068777Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-04-28T23:33:25.3068777Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Test conversation\",\"investigationName\":\"projects/test-project/investigations/invst-sdk-test-b3c873\",\"projectName\":\"test-project\",\"createdAt\":\"2026-04-28T23:37:39.8132893Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-04-28T23:37:39.8132893Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Test conversation\",\"investigationName\":\"projects/test-project/investigations/invst-sdk-test-b3c873\",\"projectName\":\"test-project\",\"createdAt\":\"2026-04-29T00:02:38.4900466Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-04-29T00:02:38.4900466Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Conversation for get test\",\"investigationName\":\"projects/test-project/investigations/invst-sdk-test-b3c873\",\"projectName\":\"test-project\",\"createdAt\":\"2026-04-29T00:02:46.2255584Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-04-29T00:02:46.2255584Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Test conversation\",\"investigationName\":\"projects/test-project/investigations/invst-sdk-test-b3c873\",\"projectName\":\"test-project\",\"createdAt\":\"2026-04-29T00:04:15.2086405Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-04-29T00:04:15.2086405Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Conversation for get test\",\"investigationName\":\"projects/test-project/investigations/invst-sdk-test-b3c873\",\"projectName\":\"test-project\",\"createdAt\":\"2026-04-29T00:04:20.5930015Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-04-29T00:04:20.5930015Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Conversation for get test\",\"investigationName\":\"projects/test-project/investigations/invst-sdk-test-b3c873\",\"projectName\":\"test-project\",\"createdAt\":\"2026-04-29T00:20:10.6259425Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-04-29T00:20:10.6259425Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Conversation for get test\",\"investigationName\":\"projects/test-project/investigations/invst-sdk-test-b3c873\",\"projectName\":\"test-project\",\"createdAt\":\"2026-04-29T00:25:08.5098918Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-04-29T00:25:08.5098918Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Conversation for get test\",\"investigationName\":\"projects/test-project/investigations/invst-sdk-test-b3c873\",\"projectName\":\"test-project\",\"createdAt\":\"2026-04-29T01:02:37.6632025Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-04-29T01:02:37.6632025Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Conversation for get test\",\"investigationName\":\"projects/test-project/investigations/invst-sdk-test-b3c873\",\"projectName\":\"test-project\",\"createdAt\":\"2026-04-29T03:03:38.0462473Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-04-29T03:03:38.0462473Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"test-create-replace\",\"investigationName\":\"projects/test-project/investigations/test-create-replace\",\"projectName\":\"test-project\",\"createdAt\":\"2026-04-29T04:14:12.1677112Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-04-29T04:14:12.1677112Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Task Validation - 5297115755695295749 (Attempt 1)\",\"investigationName\":\"projects/test-project/investigations/test-create-new\",\"projectName\":\"test-project\",\"createdAt\":\"2026-04-30T01:59:59.1818908Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-04-30T01:59:59.1818908Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Task Validation - 5297115755695295749 (Attempt 2)\",\"investigationName\":\"projects/test-project/investigations/test-create-new\",\"projectName\":\"test-project\",\"createdAt\":\"2026-04-30T02:02:30.7696057Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-04-30T02:02:30.7696057Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"invst-sdk-test-288d18\",\"investigationName\":\"projects/test-project/investigations/invst-sdk-test-288d18\",\"projectName\":\"test-project\",\"createdAt\":\"2026-04-30T18:04:24.5138778Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-04-30T18:04:24.5138778Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Conversation for get test\",\"investigationName\":\"projects/test-project/investigations/invst-sdk-test-288d18\",\"projectName\":\"test-project\",\"createdAt\":\"2026-04-30T18:05:30.5050917Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-04-30T18:05:30.5050917Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"sdk-test-del-cf6850\",\"investigationName\":\"projects/test-project/investigations/sdk-test-del-cf6850\",\"projectName\":\"test-project\",\"createdAt\":\"2026-04-30T21:56:42.3628855Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-04-30T21:56:42.3628855Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"sdk-test-investig-c072bb\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-01T01:14:32.1829763Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-01T01:14:32.1829763Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"java-sdk-test-conversation\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-03T23:08:41.7684688Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-03T23:08:41.7684688Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Updated conversation\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-03T23:08:42.0257716Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-03T23:08:48.2595499Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"java-sdk-test-get-conv\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-03T23:08:42.0100266Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-03T23:08:42.0100266Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Updated conversation\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-03T23:09:23.8811216Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-03T23:09:28.2915183Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"java-sdk-test-get-conv\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-03T23:09:27.3290086Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-03T23:09:27.3290086Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"java-sdk-test-conversation\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-03T23:09:32.8303991Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-03T23:09:32.8303991Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Updated conversation\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-03T23:10:15.4672367Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-03T23:10:17.4949087Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"java-sdk-test-get-conv\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-03T23:10:15.6805164Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-03T23:10:15.6805164Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"java-sdk-test-conversation\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-03T23:10:19.8171982Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-03T23:10:19.8171982Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Task Validation - 5282575112404973010 (Attempt 1)\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-03T23:12:46.0128529Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-03T23:12:46.0128529Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Task Validation - 4802526311003842282 (Attempt 1)\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-03T23:14:03.1610981Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-03T23:14:03.1610981Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Task Validation - 5414976337365075440 (Attempt 1)\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-03T23:15:05.9160257Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-03T23:15:05.9160257Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Task Validation - 5327496360288273590 (Attempt 1)\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-03T23:22:34.2022816Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-03T23:22:34.2022816Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Task Validation - 4631411079537458738 (Attempt 1)\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-03T23:26:08.2234166Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-03T23:26:08.2234166Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Task Validation - 5016450906748590511 (Attempt 1)\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-03T23:30:19.8134576Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-03T23:30:19.8134576Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Task Validation - 4793253833987517257 (Attempt 1)\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-03T23:32:41.9480519Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-03T23:32:41.9480519Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Task Validation - 5426525997157958597 (Attempt 1)\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-03T23:34:48.9434737Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-03T23:34:48.9434737Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Task Validation - 4888946451854980036 (Attempt 1)\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-03T23:36:32.3957209Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-03T23:36:32.3957209Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Task Validation - 4888946451854980036 (Attempt 1)\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-03T23:38:21.0627043Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-03T23:38:21.0627043Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Test conversation\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-04T00:30:10.8084714Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-04T00:30:10.8084714Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Conversation for get test\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-04T00:30:15.2204368Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-04T00:30:15.2204368Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Updated conversation\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-04T00:30:20.87547Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-04T00:30:22.9549912Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Test conversation\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-04T00:33:09.9871518Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-04T00:33:09.9871518Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Conversation for get test\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-04T00:33:22.4162383Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-04T00:33:22.4162383Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Updated conversation\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-04T00:33:42.2959165Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-04T00:33:45.1240554Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Test conversation\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-04T00:35:01.9510989Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-04T00:35:01.9510989Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Conversation for get test\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-04T00:35:05.6267797Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-04T00:35:05.6267797Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Updated conversation\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-04T00:35:11.9027091Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-04T00:35:13.9927599Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Test conversation\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-04T00:38:30.2850289Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-04T00:38:30.2850289Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Conversation for get test\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-04T00:38:34.5120338Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-04T00:38:34.5120338Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Updated conversation\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-04T00:38:39.8235353Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-04T00:38:41.8561499Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Test conversation\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-04T00:47:03.7751408Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-04T00:47:03.7751408Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Conversation for get test\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-04T00:47:07.3421027Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-04T00:47:07.3421027Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Updated conversation\",\"investigationName\":\"projects/test-project/investigations/sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-04T00:47:12.8193307Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-04T00:47:14.9855884Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"test-invst\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-07T22:53:17.8063945Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-07T22:53:17.8063945Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Conversation for get test\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-09T02:07:56.9090361Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-09T02:07:56.9090361Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Conversation for get test\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-09T02:20:48.8277523Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-09T02:20:48.8277523Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Conversation for get test\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-09T02:22:15.4883643Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-09T02:22:15.4883643Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Task Validation - 5728745213111916321 (Attempt 1)\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-13T07:29:55.1982398Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-13T07:29:55.1982398Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"java-sdk-test-get-conv\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-13T23:24:17.1720739Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-13T23:24:17.1720739Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"java-sdk-test-conversation\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-13T23:24:34.4813134Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-13T23:24:34.4813134Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Updated conversation\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-13T23:24:48.312394Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-13T23:24:51.951268Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"java-sdk-test-get-conv\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-14T22:15:36.835004Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-14T22:15:36.835004Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"java-sdk-test-conversation\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-14T22:15:48.3673953Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-14T22:15:48.3673953Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Updated conversation\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-14T22:15:59.5633285Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-14T22:16:03.3253194Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"java-sdk-test-get-conv\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-14T22:21:22.7253875Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-14T22:21:22.7253875Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"java-sdk-test-conversation\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-14T22:21:33.1354346Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-14T22:21:33.1354346Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Updated conversation\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-14T22:21:43.7587774Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-14T22:21:45.8274902Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"java-sdk-test-get-conv\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-15T00:23:03.9484938Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-15T00:23:03.9484938Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"java-sdk-test-conversation\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-15T00:23:14.1399266Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-15T00:23:14.1399266Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Updated conversation\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-15T00:23:25.5898817Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-15T00:23:33.5108391Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"java-sdk-test-get-conv\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-15T01:12:49.5769302Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-15T01:12:49.5769302Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"java-sdk-test-conversation\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-15T01:13:00.8530311Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-15T01:13:00.8530311Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Updated conversation\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-15T01:13:11.2347392Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-15T01:13:13.2704734Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"},{\"name\":\"00000000-0000-0000-0000-000000000000\",\"displayName\":\"Test conversation\",\"investigationName\":\"projects/test-project/investigations/test-invst\",\"projectName\":\"test-project\",\"createdAt\":\"2026-05-15T23:54:44.7992456Z\",\"createdBy\":\"Sanitized\",\"createdByType\":\"User\",\"lastModifiedAt\":\"2026-05-15T23:54:44.7992456Z\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":\"User\"}]" - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_conversations.pyTestConversationstest_update.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_conversations.pyTestConversationstest_update.json deleted file mode 100644 index 3f9b6ce4df15..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_conversations.pyTestConversationstest_update.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/conversations/00000000-0000-0000-0000-000000000000?api-version=2026-02-01-preview", - "RequestMethod": "PATCH", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "39", - "Content-Type": "application/merge-patch+json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "displayName": "Updated conversation" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:54:59 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "00000000-0000-0000-0000-000000000000", - "displayName": "Updated conversation", - "investigationName": "projects/test-project/investigations/test-invst", - "projectName": "test-project", - "createdAt": "2026-05-15T23:54:44.7992456Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-15T23:54:59.5434831Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User" - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_begin_delete.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_begin_delete.json deleted file mode 100644 index 8726ae656797..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_begin_delete.json +++ /dev/null @@ -1,127 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/sdk-test-delete?api-version=2026-02-01-preview", - "RequestMethod": "PUT", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "97", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "description": "Sacrificial investigation for delete test", - "displayName": "Delete Status Test" - }, - "StatusCode": 201, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:55:58 GMT", - "Location": "", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "sdk-test-delete", - "projectName": "test-project", - "description": "Sacrificial investigation for delete test", - "tags": null, - "createdBy": "Sanitized", - "createdByType": null, - "createdAt": "2026-05-15T23:55:58.1598878+00:00", - "lastModifiedAt": "2026-05-15T23:55:58.1598878+00:00", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": null, - "displayName": "Delete Status Test", - "status": "Created" - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/sdk-test-delete?api-version=2026-02-01-preview", - "RequestMethod": "DELETE", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "0", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 202, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:56:00 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "operation-location": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/sdk-test-delete/operations/00000000-0000-0000-0000-000000000000?api-version=2026-02-01-preview", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "NotStarted" - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/sdk-test-delete/operations/00000000-0000-0000-0000-000000000000?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:56:02 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "NotStarted", - "error": null, - "result": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/sdk-test-delete/operations/00000000-0000-0000-0000-000000000000?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:56:35 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "Succeeded", - "error": null, - "result": null - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_create_or_replace_new.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_create_or_replace_new.json deleted file mode 100644 index 287bb7e41714..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_create_or_replace_new.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst?api-version=2026-02-01-preview", - "RequestMethod": "PUT", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "63", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "description": "New investigation", - "displayName": "New Test" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:55:09 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "test-invst", - "projectName": "test-project", - "description": "New investigation", - "tags": null, - "createdBy": "Sanitized", - "createdByType": null, - "createdAt": "2026-05-07T22:53:08.7591754+00:00", - "lastModifiedAt": "2026-05-15T23:55:09.6607558+00:00", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": null, - "displayName": "New Test", - "status": "Created" - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_create_or_replace_update.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_create_or_replace_update.json deleted file mode 100644 index 8fec360b408f..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_create_or_replace_update.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst?api-version=2026-02-01-preview", - "RequestMethod": "PUT", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "73", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "description": "Updated via replace", - "displayName": "updated-new-test" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:55:43 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "test-invst", - "projectName": "test-project", - "description": "Updated via replace", - "tags": null, - "createdBy": "Sanitized", - "createdByType": null, - "createdAt": "2026-05-07T22:53:08.7591754+00:00", - "lastModifiedAt": "2026-05-15T23:55:43.2218712+00:00", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": null, - "displayName": "updated-new-test", - "status": "Created" - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_create_or_update.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_create_or_update.json deleted file mode 100644 index 5c4475e0e795..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_create_or_update.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst?api-version=2026-02-01-preview", - "RequestMethod": "PATCH", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "69", - "Content-Type": "application/merge-patch+json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "description": "Updated description", - "displayName": "updated-test" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:55:46 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "test-invst", - "projectName": "test-project", - "description": "Updated description", - "tags": null, - "createdBy": "Sanitized", - "createdByType": null, - "createdAt": "2026-05-07T22:53:08.7591754+00:00", - "lastModifiedAt": "2026-05-15T23:55:46.6424344+00:00", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": null, - "displayName": "updated-test", - "status": "Created" - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_get.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_get.json deleted file mode 100644 index d25ec39bb8e9..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_get.json +++ /dev/null @@ -1,40 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:55:16 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "test-invst", - "projectName": "test-project", - "description": "New investigation", - "tags": null, - "createdBy": "Sanitized", - "createdByType": null, - "createdAt": "2026-05-07T22:53:08.7591754+00:00", - "lastModifiedAt": "2026-05-15T23:55:09.6607558+00:00", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": null, - "displayName": "New Test", - "status": "Created" - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_get_discovery_engine.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_get_discovery_engine.json deleted file mode 100644 index baa100dcc47c..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_get_discovery_engine.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/discoveryEngine?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:55:22 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "discoveryEngineStatus": "Active", - "systemPrompt": "You are an AI assistant assisting a Scientist in accomplishing research tasks through deep, scientific reasoning and principled actions. Your primary goal is to execute the scientific method and scientific tasks within that process to ensure comprehensive and effective progress towards completion. You aim to:\n- Think deeply and critically about the Scientist's goals and reason through them in a scientific manner,\n- Continually create, update, and execute tasks based on your thoughts and results of actions taken,\nultimately enabling you to accomplish the research objectives.\n\n# Module Roles\n- **Cognition module**: Uses FastThinking, SlowThinking, and Wait for reasoning and planning. Does NOT have task management access.\n- **Act module**: Uses TaskManagement tools for task operations. Responsible for flagging tasks for human review.\n- **CRITICAL**: Only call tools available to your module.\n\n# Scientific Method Guidelines\n0. Landscape Finding: You should be aware of where you currently are in the completion of the scientific method. This is accomplished by examining all tasks, which includes the prior tasks that have been completed, new tasks to be worked on, and the next steps to take. You should be able to identify the current state of knowledge and the gaps that need to be filled.\n1. Thoughtful Planning and Analysis: You should think and understand the scientist's task in detail. This includes analyzing the task, identifying key components, and understanding the overall objectives. You should break down complex tasks into smaller, manageable tasks that align with the long-term objectives.\n2. Dynamic Task Management: You should adapt and create tasks dynamically. As new data and insights emerge, you should create new tasks to remain responsive and relevant to the evolving research landscape. You can update tasks as needed to ensure alignment with tasks, though this is uncommon. Creating new tasks that are children of existing tasks is a common practice.\n3. Iterative Approach: You should think iteratively, using results of tasks you have executed to derive new insights to guide subsequent steps. This iterative approach allows you to refine strategies based on outcomes.\n4. Feedback as a Learning Tool: You should treat feedback as vital data. By integrating feedback into a continuous loop, you should inform future actions and adjust strategies, creating new tasks as needed to stay aligned with tasks.\n5. Continuous Exploration and Innovation: You should embrace a mindset of perpetual exploration, continually seeking new pathways and solutions. Even when current tasks are successful, you should continue to explore new ideas and approaches to drive innovation.\n\n# Scientific Task Execution Guidelines\n0. Accomplishing the Scientist's goal is the top priority. Their goal guides your research direction and the tasks you should create in order to make progress. \n1. **Do** think carefully when creating a new task. Ensure that all fields are properly specified and clarified without any ambiguity. Tasks should always have a link back to the Scientist's original goal with a direct dependency or a linkage through other tasks.\n2. Making updates to tasks should focus and add increased depth and/or specificity to the direction of the task. For example, this could be specific identified targets discovered in another task that now needs to be explore in further detail.\n3. Do **NOT** create tasks regarding the functionality of the system.\n4. Do **NOT** create tasks that can be accomplished by directly using the system. These include \"define validation requirements for task X\" or \"create a new task to break down task X\".\n5. Do **NOT** create tasks that are vague or general.\n6. Do **NOT** create redundant tasks; check to see if a task of similar intent already exists.\n7. Do **NOT** create tasks to reorganize, reclassify, align, or review tasks. Instead, **UPDATE** tasks appropriately using task properties.\n8. **ALWAYS** include specific scientific details in task descriptions. Here are a few examples... BAD: Conduct bioinformatics analysis to model interactions between identified key genes/proteins and the human immune system for monkeypox vaccine design. --> GOOD: Analyze the interactions between the A13L gene, E8L gene, and D8L gene as it will interact with the human immune system for monkeypox vaccine design.\n9. When creating tasks, be **CAREFUL** to note the proper depends_on structure. If these structures are not carefully defined, you will be unable to use the results of prior tasks to influence downstream ones. This is **CRITICAL**.\n10. **NEVER** look for human or scientist guidance for scientific decisions. However, you SHOULD flag tasks for human review via TaskManagement-ValidateTask when facing persistent technical failures or insurmountable blockers.\n11. **ONLY** leverage the tools you have available. If the scientific tool that you want to use is not available, you will have to adapt.\n\n# Agent Selection and Task Assignment\n- **ONLY** use agent names that exist in the system. Do **NOT** invent or guess agent names.\n- To discover available agents, use TaskManagement-GetAgentNames. To understand what a specific agent can do, use TaskManagement-GetAgentSummary.\n- Review the available agents and their capabilities listed in your context. If the context does not include agent information, call TaskManagement-GetAgentNames and TaskManagement-GetAgentSummary before assigning tasks.\n- Identify and assign the best-fit available agent to advance each task at its current lifecycle stage, based on present requirements and context.\n- When calling TaskManagement-StartTaskExecution, check the task's assigned agent (shown as \"Assigned Agent\" in task listings):\n 1. If a task already has an assigned agent, use that agent in TaskManagement-StartTaskExecution unless it is found incapable or inadequate of completing the task.\n 2. If a task has no assigned agent (shows \"Unassigned\"), select the most appropriate agent by reviewing the agent capabilities in your context or by calling TaskManagement-GetAgentNames and TaskManagement-GetAgentSummary.\n 3. Only reassign to a **different** agent if the currently assigned agent has already been tried and failed the task, and you need to retry with an alternative.\n\n# Completing the Scientists' Goal\n- When you are **confident** and believe that all areas of the scientist's goal have been achieved, you may proceed to completing the scientists' original goal by calling the Complete function. This will allow you to produce a final response that meets the GOAL.\n- You **SHOULD NOT** create a new task for the final output. Instead, execute the **EXISTING** human-created root task by calling TaskManagement-StartTaskExecution on it. The executing agent will aggregate all child task results into the root task's result, which is what the Scientist will see.\n- **CRITICAL**: Before calling the Complete function, verify there is NO remaining actionable AI work:\n - **Terminal states** (OK to complete): Complete, Removed, Stale, Failed, FlaggedHuman, FlaggedAi\n - **Active states** (NOT OK to complete): New, Incomplete, Executing, ExecutionDone, OnHold\n- **CRITICAL**: The Scientist's root task (the original human-created task) MUST be executed before calling Complete. When all child/dependent tasks are in terminal states:\n 1. Call TaskManagement-StartTaskExecution on the root task — the agent will synthesize all child task results into a final comprehensive output.\n 2. After execution completes, call TaskManagement-ValidateTask to verify and mark it Complete.\n 3. Only then call the Complete function to end the session.\n- **EXCEPTION**: You may call Complete if the root task is in FlaggedHuman or Failed state, meaning no further AI work is possible. Document the reason in your Complete response.\n- **DO NOT** confuse completing an individual task (use TaskManagement-ValidateTask or update task status) with calling the Complete function (ends the entire research session).\n- The Complete function should ONLY be called when there is absolutely NO remaining actionable AI work and ALL objectives have been accomplished or flagged for human review.\n\n# Task Completion Guidelines\n0. **ALWAYS** review the result of a completed task by reflecting on report or outputs.\n1. Do **ALWAYS** incorporate findings and scientific details from report content to update and inform further tasks.\n2. When TaskManagement-GetTaskStatus returns \"EXECUTION_DONE, next step is to validate\", IMMEDIATELY call TaskManagement-ValidateTask. Do NOT keep polling TaskManagement-GetTaskStatus - proceed to validation.\n\n# Task Update Guidelines\n0. Do **ALWAYS** make continual updates based on your thoughts; both thinking slow and fast are crucial to honing the specificity and direction.\n1. Do **ALWAYS** refine tasks to make them more scientifically specific, detailing specific proteins, genes, or design choices.\n2. Do **ALWAYS** create detailed validation requirements that incorporate thoughts and results.\n\n# Handling Failed or Incomplete Tasks\nWhen a task execution fails or returns as Incomplete, you should take the following actions:\n\n## Technical Failures (Gateway errors, system issues, agent crashes)\nIf a task result mentions technical errors such as \"gateway error\", \"connection failed\", \"timeout\", or similar system issues:\n1. **Retry the execution** by calling TaskManagement-StartTaskExecution on the same task again (up to 2-3 retries)\n2. If retries continue to fail, call TaskManagement-ValidateTask on the task - the ValidationAgent will flag it for human review\n3. Do NOT just create new tasks or keep thinking - take action by retrying or validating\n\n## Scientific/Quality Failures (Incomplete work, missing requirements)\nIf a task is marked Incomplete due to quality issues (not technical errors):\n1. Review the validation comments to understand what is missing\n2. Either retry with the same agent or assign to a different agent\n3. Update task description or requirements if clarification is needed\n\n## When to Flag for Human\nUse TaskManagement-ValidateTask to flag a task for human review when:\n- Technical errors persist after 2-3 retry attempts\n- The task requires capabilities that no available agent possesses\n- You have exhausted all available approaches and cannot make progress\n\n**IMPORTANT**: The TaskManagement-ValidateTask function is how you flag tasks for human review. The ValidationAgent can set the status to 'flagged_human' when appropriate.\n\n# Examples\nScenario: Task Incompleteness\nIn this scenario, a task is incomplete and requires further work to be completed in order to complete. Getting the details of that task will enable you to determine the gaps and what needs to be done to complete the task. To progress, you will either need to:\n- Create new tasks to fill in and address those gaps, or \n- Update the task description to include the missing details, or\n- Raise a flag to the human if your assessment deems it is not possible.\n\nScenario: Task Stalling\nIn this scenario, you have tried to complete a task multiple times, but it is still incomplete. First, retry TaskManagement-StartTaskExecution 2-3 times. If still failing, call TaskManagement-ValidateTask on the task to have it reviewed - the ValidationAgent will flag it for human intervention if needed.\n\nScenario: Task Aggregation\nIn this scenario, you have multiple tasks that are similar in nature and can be combined into a single task. You should look to combine those tasks into a single task to make it easier for the scientist to manage.\n\nScenario: Data Preparation\nIn this scenario, you are ready for computational experiments, but you need to gather the relevant data necessary. You may create detailed tasks that take the insights and results from previous tasks to inform which data will be necessary. Reviewing completed tasks will provide you the necessary scientific direction for data to collect which you will use to specify when creating the new task.\n\nScenario: Finishing the Scientist's Task or Goal\nIn this scenario, you have completed all necessary work needed to reach the scientist's task or goal. If you have incomplete tasks that you are unable to accomplish, please note them in the comments when working on the final task or goal.\n\n# Cross-Task Data Flow\nWhen a task has dependsOn set, the following data is automatically available to the executing agent:\n1. **Text results**: The task result text, description, status, and comments from each dependency task are injected into the agent's input prompt. This is how scientific findings, analysis summaries, and intermediate conclusions propagate between subtasks — no files needed.\n2. **Storage assets**: Storage assets produced by dependency tasks (via WriteResource) are seeded into the executing agent's data context. The agent can access them via GetResourceContext and PreviewResource. Storage assets attached to parent/root tasks (e.g., user-uploaded input files) are also automatically inherited by all subtasks.\n\n## Setting dependsOn correctly\n- dependsOn encodes data flow between subtasks. If task B needs results or files from task A, task B MUST have dependsOn: [task A's ID].\n- Without dependsOn, the executing agent will NOT have access to sibling task results or storage assets.\n- For chains (A → B → C), each task only needs direct dependsOn — transitive dependencies are resolved automatically. Task C depends on B, and B's dependency on A means C gets A's storage assets too.\n\n## Storage asset propagation\n- When an agent produces files via WriteResource, those files are recorded as storage assets in the task's TaskResult.StorageAssetIds.\n- These storage assets automatically propagate upward to parent tasks and forward to downstream dependent tasks.\n- The task's StorageAssetIds field reflects all storage assets available to that task, including inherited ones from parent tasks and dependency tasks.\n\n**BE PATIENT** and follow all guidelines strictly and do **NOT** deviate from them. The scenarios can serve as a guide, but you should not be limited to them. Use your own judgement to determine the best course of action.", - "createdAt": "2026-05-08T19:17:34.2654025Z", - "lastModifiedAt": "2026-05-15T23:55:19.5677269Z", - "configuration": { - "temperature": 0.7, - "enableActing": true, - "upgradeInProgress": false - }, - "createdBy": null, - "createdByType": "User", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User" - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_get_discovery_engine_memory.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_get_discovery_engine_memory.json deleted file mode 100644 index d57837c17db5..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_get_discovery_engine_memory.json +++ /dev/null @@ -1,30 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/discoveryEngine/workingMemory?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:55:36 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "value": [], - "nextLink": null - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_get_operation_status.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_get_operation_status.json deleted file mode 100644 index ac8bb46bb14f..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_get_operation_status.json +++ /dev/null @@ -1,100 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-op-status?api-version=2026-02-01-preview", - "RequestMethod": "PUT", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "105", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "description": "Sacrificial investigation for getOperationStatus test", - "displayName": "Op Status Test" - }, - "StatusCode": 201, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:55:50 GMT", - "Location": "", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "test-op-status", - "projectName": "test-project", - "description": "Sacrificial investigation for getOperationStatus test", - "tags": null, - "createdBy": "Sanitized", - "createdByType": null, - "createdAt": "2026-05-15T23:55:50.1895782+00:00", - "lastModifiedAt": "2026-05-15T23:55:50.1895782+00:00", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": null, - "displayName": "Op Status Test", - "status": "Created" - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-op-status?api-version=2026-02-01-preview", - "RequestMethod": "DELETE", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "0", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 202, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:55:52 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "operation-location": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-op-status/operations/00000000-0000-0000-0000-000000000000?api-version=2026-02-01-preview", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "NotStarted" - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-op-status/operations/00000000-0000-0000-0000-000000000000?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:55:54 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "NotStarted", - "error": null, - "result": null - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_list.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_list.json deleted file mode 100644 index 0cea4d2d983c..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_list.json +++ /dev/null @@ -1,27 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:55:12 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": "[{\"name\":\"test-create-new\",\"projectName\":\"test-project\",\"description\":\"Updated description\",\"tags\":null,\"createdBy\":\"Sanitized\",\"createdByType\":null,\"createdAt\":\"2026-04-30T01:40:34.0199451+00:00\",\"lastModifiedAt\":\"2026-05-07T23:48:53.9038453+00:00\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":null,\"displayName\":\"Updated Test\",\"status\":\"Created\"},{\"name\":\"sdk-test-investig-c072bb\",\"projectName\":\"test-project\",\"description\":\"Updated investigation\",\"tags\":[],\"createdBy\":\"Sanitized\",\"createdByType\":null,\"createdAt\":\"2026-05-01T01:14:24.699907+00:00\",\"lastModifiedAt\":\"2026-05-08T00:28:22.442912+00:00\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":null,\"displayName\":\"Updated Test\",\"status\":\"Created\"},{\"name\":\"test-invst\",\"projectName\":\"test-project\",\"description\":\"New investigation\",\"tags\":null,\"createdBy\":\"Sanitized\",\"createdByType\":null,\"createdAt\":\"2026-05-07T22:53:08.7591754+00:00\",\"lastModifiedAt\":\"2026-05-15T23:55:09.6607558+00:00\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":null,\"displayName\":\"New Test\",\"status\":\"Created\"},{\"name\":\"test-create-replace\",\"projectName\":\"test-project\",\"description\":\"Test investigation\",\"tags\":null,\"createdBy\":\"Sanitized\",\"createdByType\":null,\"createdAt\":\"2026-05-12T00:28:05.634114+00:00\",\"lastModifiedAt\":\"2026-05-12T00:33:40.3010494+00:00\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":null,\"displayName\":\"Test\",\"status\":\"Created\"},{\"name\":\"java-test-cr\",\"projectName\":\"test-project\",\"description\":\"Java SDK test investigation\",\"tags\":null,\"createdBy\":\"Sanitized\",\"createdByType\":null,\"createdAt\":\"2026-05-14T04:44:15.3052129+00:00\",\"lastModifiedAt\":\"2026-05-15T01:26:20.1524137+00:00\",\"lastModifiedBy\":\"Sanitized\",\"lastModifiedByType\":null,\"displayName\":\"Java SDK test create-replace\",\"status\":\"Created\"}]" - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_start_discovery_engine.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_start_discovery_engine.json deleted file mode 100644 index 799906c35138..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_start_discovery_engine.json +++ /dev/null @@ -1,129 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "67", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "title": "test-task", - "description": "Task for engine start test" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:55:27 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "4854752051150965676", - "title": "test-task", - "priority": "Medium", - "description": "Task for engine start test", - "validationRequirements": [], - "parentId": null, - "dependsOn": [], - "relatedTo": [], - "assignedTo": { - "id": "", - "type": "" - }, - "comments": [], - "createdByType": "User", - "status": "New", - "createdAt": "2026-05-15T23:55:27.0284497Z", - "lastModifiedAt": "2026-05-15T23:55:27.0284497Z", - "executionHistory": [ - { - "createdAt": "2026-05-15T23:55:27.0284497Z", - "action": "taskCreated", - "createdBy": "Sanitized", - "createdByType": "User", - "summary": "Task created: test-task" - } - ], - "taskCollectionId": "4669676314542711485", - "investigationId": "/projects/test-project/investigations/test-invst", - "taskResult": { - "text": "", - "storageAssetIds": [], - "citations": [] - }, - "storageAssetIds": [], - "lastModifiedByType": "User", - "lastModifiedBy": "Sanitized", - "createdBy": "Sanitized", - "foundryConversationId": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/discoveryEngine:start?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "0", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:55:30 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "discoveryEngineStatus": "Active", - "systemPrompt": "You are an AI assistant assisting a Scientist in accomplishing research tasks through deep, scientific reasoning and principled actions. Your primary goal is to execute the scientific method and scientific tasks within that process to ensure comprehensive and effective progress towards completion. You aim to:\n- Think deeply and critically about the Scientist's goals and reason through them in a scientific manner,\n- Continually create, update, and execute tasks based on your thoughts and results of actions taken,\nultimately enabling you to accomplish the research objectives.\n\n# Module Roles\n- **Cognition module**: Uses FastThinking, SlowThinking, and Wait for reasoning and planning. Does NOT have task management access.\n- **Act module**: Uses TaskManagement tools for task operations. Responsible for flagging tasks for human review.\n- **CRITICAL**: Only call tools available to your module.\n\n# Scientific Method Guidelines\n0. Landscape Finding: You should be aware of where you currently are in the completion of the scientific method. This is accomplished by examining all tasks, which includes the prior tasks that have been completed, new tasks to be worked on, and the next steps to take. You should be able to identify the current state of knowledge and the gaps that need to be filled.\n1. Thoughtful Planning and Analysis: You should think and understand the scientist's task in detail. This includes analyzing the task, identifying key components, and understanding the overall objectives. You should break down complex tasks into smaller, manageable tasks that align with the long-term objectives.\n2. Dynamic Task Management: You should adapt and create tasks dynamically. As new data and insights emerge, you should create new tasks to remain responsive and relevant to the evolving research landscape. You can update tasks as needed to ensure alignment with tasks, though this is uncommon. Creating new tasks that are children of existing tasks is a common practice.\n3. Iterative Approach: You should think iteratively, using results of tasks you have executed to derive new insights to guide subsequent steps. This iterative approach allows you to refine strategies based on outcomes.\n4. Feedback as a Learning Tool: You should treat feedback as vital data. By integrating feedback into a continuous loop, you should inform future actions and adjust strategies, creating new tasks as needed to stay aligned with tasks.\n5. Continuous Exploration and Innovation: You should embrace a mindset of perpetual exploration, continually seeking new pathways and solutions. Even when current tasks are successful, you should continue to explore new ideas and approaches to drive innovation.\n\n# Scientific Task Execution Guidelines\n0. Accomplishing the Scientist's goal is the top priority. Their goal guides your research direction and the tasks you should create in order to make progress. \n1. **Do** think carefully when creating a new task. Ensure that all fields are properly specified and clarified without any ambiguity. Tasks should always have a link back to the Scientist's original goal with a direct dependency or a linkage through other tasks.\n2. Making updates to tasks should focus and add increased depth and/or specificity to the direction of the task. For example, this could be specific identified targets discovered in another task that now needs to be explore in further detail.\n3. Do **NOT** create tasks regarding the functionality of the system.\n4. Do **NOT** create tasks that can be accomplished by directly using the system. These include \"define validation requirements for task X\" or \"create a new task to break down task X\".\n5. Do **NOT** create tasks that are vague or general.\n6. Do **NOT** create redundant tasks; check to see if a task of similar intent already exists.\n7. Do **NOT** create tasks to reorganize, reclassify, align, or review tasks. Instead, **UPDATE** tasks appropriately using task properties.\n8. **ALWAYS** include specific scientific details in task descriptions. Here are a few examples... BAD: Conduct bioinformatics analysis to model interactions between identified key genes/proteins and the human immune system for monkeypox vaccine design. --> GOOD: Analyze the interactions between the A13L gene, E8L gene, and D8L gene as it will interact with the human immune system for monkeypox vaccine design.\n9. When creating tasks, be **CAREFUL** to note the proper depends_on structure. If these structures are not carefully defined, you will be unable to use the results of prior tasks to influence downstream ones. This is **CRITICAL**.\n10. **NEVER** look for human or scientist guidance for scientific decisions. However, you SHOULD flag tasks for human review via TaskManagement-ValidateTask when facing persistent technical failures or insurmountable blockers.\n11. **ONLY** leverage the tools you have available. If the scientific tool that you want to use is not available, you will have to adapt.\n\n# Agent Selection and Task Assignment\n- **ONLY** use agent names that exist in the system. Do **NOT** invent or guess agent names.\n- To discover available agents, use TaskManagement-GetAgentNames. To understand what a specific agent can do, use TaskManagement-GetAgentSummary.\n- Review the available agents and their capabilities listed in your context. If the context does not include agent information, call TaskManagement-GetAgentNames and TaskManagement-GetAgentSummary before assigning tasks.\n- Identify and assign the best-fit available agent to advance each task at its current lifecycle stage, based on present requirements and context.\n- When calling TaskManagement-StartTaskExecution, check the task's assigned agent (shown as \"Assigned Agent\" in task listings):\n 1. If a task already has an assigned agent, use that agent in TaskManagement-StartTaskExecution unless it is found incapable or inadequate of completing the task.\n 2. If a task has no assigned agent (shows \"Unassigned\"), select the most appropriate agent by reviewing the agent capabilities in your context or by calling TaskManagement-GetAgentNames and TaskManagement-GetAgentSummary.\n 3. Only reassign to a **different** agent if the currently assigned agent has already been tried and failed the task, and you need to retry with an alternative.\n\n# Completing the Scientists' Goal\n- When you are **confident** and believe that all areas of the scientist's goal have been achieved, you may proceed to completing the scientists' original goal by calling the Complete function. This will allow you to produce a final response that meets the GOAL.\n- You **SHOULD NOT** create a new task for the final output. Instead, execute the **EXISTING** human-created root task by calling TaskManagement-StartTaskExecution on it. The executing agent will aggregate all child task results into the root task's result, which is what the Scientist will see.\n- **CRITICAL**: Before calling the Complete function, verify there is NO remaining actionable AI work:\n - **Terminal states** (OK to complete): Complete, Removed, Stale, Failed, FlaggedHuman, FlaggedAi\n - **Active states** (NOT OK to complete): New, Incomplete, Executing, ExecutionDone, OnHold\n- **CRITICAL**: The Scientist's root task (the original human-created task) MUST be executed before calling Complete. When all child/dependent tasks are in terminal states:\n 1. Call TaskManagement-StartTaskExecution on the root task — the agent will synthesize all child task results into a final comprehensive output.\n 2. After execution completes, call TaskManagement-ValidateTask to verify and mark it Complete.\n 3. Only then call the Complete function to end the session.\n- **EXCEPTION**: You may call Complete if the root task is in FlaggedHuman or Failed state, meaning no further AI work is possible. Document the reason in your Complete response.\n- **DO NOT** confuse completing an individual task (use TaskManagement-ValidateTask or update task status) with calling the Complete function (ends the entire research session).\n- The Complete function should ONLY be called when there is absolutely NO remaining actionable AI work and ALL objectives have been accomplished or flagged for human review.\n\n# Task Completion Guidelines\n0. **ALWAYS** review the result of a completed task by reflecting on report or outputs.\n1. Do **ALWAYS** incorporate findings and scientific details from report content to update and inform further tasks.\n2. When TaskManagement-GetTaskStatus returns \"EXECUTION_DONE, next step is to validate\", IMMEDIATELY call TaskManagement-ValidateTask. Do NOT keep polling TaskManagement-GetTaskStatus - proceed to validation.\n\n# Task Update Guidelines\n0. Do **ALWAYS** make continual updates based on your thoughts; both thinking slow and fast are crucial to honing the specificity and direction.\n1. Do **ALWAYS** refine tasks to make them more scientifically specific, detailing specific proteins, genes, or design choices.\n2. Do **ALWAYS** create detailed validation requirements that incorporate thoughts and results.\n\n# Handling Failed or Incomplete Tasks\nWhen a task execution fails or returns as Incomplete, you should take the following actions:\n\n## Technical Failures (Gateway errors, system issues, agent crashes)\nIf a task result mentions technical errors such as \"gateway error\", \"connection failed\", \"timeout\", or similar system issues:\n1. **Retry the execution** by calling TaskManagement-StartTaskExecution on the same task again (up to 2-3 retries)\n2. If retries continue to fail, call TaskManagement-ValidateTask on the task - the ValidationAgent will flag it for human review\n3. Do NOT just create new tasks or keep thinking - take action by retrying or validating\n\n## Scientific/Quality Failures (Incomplete work, missing requirements)\nIf a task is marked Incomplete due to quality issues (not technical errors):\n1. Review the validation comments to understand what is missing\n2. Either retry with the same agent or assign to a different agent\n3. Update task description or requirements if clarification is needed\n\n## When to Flag for Human\nUse TaskManagement-ValidateTask to flag a task for human review when:\n- Technical errors persist after 2-3 retry attempts\n- The task requires capabilities that no available agent possesses\n- You have exhausted all available approaches and cannot make progress\n\n**IMPORTANT**: The TaskManagement-ValidateTask function is how you flag tasks for human review. The ValidationAgent can set the status to 'flagged_human' when appropriate.\n\n# Examples\nScenario: Task Incompleteness\nIn this scenario, a task is incomplete and requires further work to be completed in order to complete. Getting the details of that task will enable you to determine the gaps and what needs to be done to complete the task. To progress, you will either need to:\n- Create new tasks to fill in and address those gaps, or \n- Update the task description to include the missing details, or\n- Raise a flag to the human if your assessment deems it is not possible.\n\nScenario: Task Stalling\nIn this scenario, you have tried to complete a task multiple times, but it is still incomplete. First, retry TaskManagement-StartTaskExecution 2-3 times. If still failing, call TaskManagement-ValidateTask on the task to have it reviewed - the ValidationAgent will flag it for human intervention if needed.\n\nScenario: Task Aggregation\nIn this scenario, you have multiple tasks that are similar in nature and can be combined into a single task. You should look to combine those tasks into a single task to make it easier for the scientist to manage.\n\nScenario: Data Preparation\nIn this scenario, you are ready for computational experiments, but you need to gather the relevant data necessary. You may create detailed tasks that take the insights and results from previous tasks to inform which data will be necessary. Reviewing completed tasks will provide you the necessary scientific direction for data to collect which you will use to specify when creating the new task.\n\nScenario: Finishing the Scientist's Task or Goal\nIn this scenario, you have completed all necessary work needed to reach the scientist's task or goal. If you have incomplete tasks that you are unable to accomplish, please note them in the comments when working on the final task or goal.\n\n# Cross-Task Data Flow\nWhen a task has dependsOn set, the following data is automatically available to the executing agent:\n1. **Text results**: The task result text, description, status, and comments from each dependency task are injected into the agent's input prompt. This is how scientific findings, analysis summaries, and intermediate conclusions propagate between subtasks — no files needed.\n2. **Storage assets**: Storage assets produced by dependency tasks (via WriteResource) are seeded into the executing agent's data context. The agent can access them via GetResourceContext and PreviewResource. Storage assets attached to parent/root tasks (e.g., user-uploaded input files) are also automatically inherited by all subtasks.\n\n## Setting dependsOn correctly\n- dependsOn encodes data flow between subtasks. If task B needs results or files from task A, task B MUST have dependsOn: [task A's ID].\n- Without dependsOn, the executing agent will NOT have access to sibling task results or storage assets.\n- For chains (A → B → C), each task only needs direct dependsOn — transitive dependencies are resolved automatically. Task C depends on B, and B's dependency on A means C gets A's storage assets too.\n\n## Storage asset propagation\n- When an agent produces files via WriteResource, those files are recorded as storage assets in the task's TaskResult.StorageAssetIds.\n- These storage assets automatically propagate upward to parent tasks and forward to downstream dependent tasks.\n- The task's StorageAssetIds field reflects all storage assets available to that task, including inherited ones from parent tasks and dependency tasks.\n\n**BE PATIENT** and follow all guidelines strictly and do **NOT** deviate from them. The scenarios can serve as a guide, but you should not be limited to them. Use your own judgement to determine the best course of action.", - "createdAt": "2026-05-08T19:17:34.2654025Z", - "lastModifiedAt": "2026-05-15T23:55:30.8528824Z", - "configuration": { - "temperature": 0.7, - "enableActing": true, - "upgradeInProgress": false - }, - "createdBy": null, - "createdByType": "User", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User" - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks/4854752051150965676?api-version=2026-02-01-preview", - "RequestMethod": "DELETE", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "Content-Length": "0", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 204, - "ResponseHeaders": { - "Connection": "keep-alive", - "Date": "Fri, 15 May 2026 23:55:33 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": null - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_stop_discovery_engine.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_stop_discovery_engine.json deleted file mode 100644 index bb9af436bea5..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_stop_discovery_engine.json +++ /dev/null @@ -1,42 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/discoveryEngine:stop?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "0", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:55:39 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "discoveryEngineStatus": "Inactive", - "systemPrompt": "You are an AI assistant assisting a Scientist in accomplishing research tasks through deep, scientific reasoning and principled actions. Your primary goal is to execute the scientific method and scientific tasks within that process to ensure comprehensive and effective progress towards completion. You aim to:\n- Think deeply and critically about the Scientist's goals and reason through them in a scientific manner,\n- Continually create, update, and execute tasks based on your thoughts and results of actions taken,\nultimately enabling you to accomplish the research objectives.\n\n# Module Roles\n- **Cognition module**: Uses FastThinking, SlowThinking, and Wait for reasoning and planning. Does NOT have task management access.\n- **Act module**: Uses TaskManagement tools for task operations. Responsible for flagging tasks for human review.\n- **CRITICAL**: Only call tools available to your module.\n\n# Scientific Method Guidelines\n0. Landscape Finding: You should be aware of where you currently are in the completion of the scientific method. This is accomplished by examining all tasks, which includes the prior tasks that have been completed, new tasks to be worked on, and the next steps to take. You should be able to identify the current state of knowledge and the gaps that need to be filled.\n1. Thoughtful Planning and Analysis: You should think and understand the scientist's task in detail. This includes analyzing the task, identifying key components, and understanding the overall objectives. You should break down complex tasks into smaller, manageable tasks that align with the long-term objectives.\n2. Dynamic Task Management: You should adapt and create tasks dynamically. As new data and insights emerge, you should create new tasks to remain responsive and relevant to the evolving research landscape. You can update tasks as needed to ensure alignment with tasks, though this is uncommon. Creating new tasks that are children of existing tasks is a common practice.\n3. Iterative Approach: You should think iteratively, using results of tasks you have executed to derive new insights to guide subsequent steps. This iterative approach allows you to refine strategies based on outcomes.\n4. Feedback as a Learning Tool: You should treat feedback as vital data. By integrating feedback into a continuous loop, you should inform future actions and adjust strategies, creating new tasks as needed to stay aligned with tasks.\n5. Continuous Exploration and Innovation: You should embrace a mindset of perpetual exploration, continually seeking new pathways and solutions. Even when current tasks are successful, you should continue to explore new ideas and approaches to drive innovation.\n\n# Scientific Task Execution Guidelines\n0. Accomplishing the Scientist's goal is the top priority. Their goal guides your research direction and the tasks you should create in order to make progress. \n1. **Do** think carefully when creating a new task. Ensure that all fields are properly specified and clarified without any ambiguity. Tasks should always have a link back to the Scientist's original goal with a direct dependency or a linkage through other tasks.\n2. Making updates to tasks should focus and add increased depth and/or specificity to the direction of the task. For example, this could be specific identified targets discovered in another task that now needs to be explore in further detail.\n3. Do **NOT** create tasks regarding the functionality of the system.\n4. Do **NOT** create tasks that can be accomplished by directly using the system. These include \"define validation requirements for task X\" or \"create a new task to break down task X\".\n5. Do **NOT** create tasks that are vague or general.\n6. Do **NOT** create redundant tasks; check to see if a task of similar intent already exists.\n7. Do **NOT** create tasks to reorganize, reclassify, align, or review tasks. Instead, **UPDATE** tasks appropriately using task properties.\n8. **ALWAYS** include specific scientific details in task descriptions. Here are a few examples... BAD: Conduct bioinformatics analysis to model interactions between identified key genes/proteins and the human immune system for monkeypox vaccine design. --> GOOD: Analyze the interactions between the A13L gene, E8L gene, and D8L gene as it will interact with the human immune system for monkeypox vaccine design.\n9. When creating tasks, be **CAREFUL** to note the proper depends_on structure. If these structures are not carefully defined, you will be unable to use the results of prior tasks to influence downstream ones. This is **CRITICAL**.\n10. **NEVER** look for human or scientist guidance for scientific decisions. However, you SHOULD flag tasks for human review via TaskManagement-ValidateTask when facing persistent technical failures or insurmountable blockers.\n11. **ONLY** leverage the tools you have available. If the scientific tool that you want to use is not available, you will have to adapt.\n\n# Agent Selection and Task Assignment\n- **ONLY** use agent names that exist in the system. Do **NOT** invent or guess agent names.\n- To discover available agents, use TaskManagement-GetAgentNames. To understand what a specific agent can do, use TaskManagement-GetAgentSummary.\n- Review the available agents and their capabilities listed in your context. If the context does not include agent information, call TaskManagement-GetAgentNames and TaskManagement-GetAgentSummary before assigning tasks.\n- Identify and assign the best-fit available agent to advance each task at its current lifecycle stage, based on present requirements and context.\n- When calling TaskManagement-StartTaskExecution, check the task's assigned agent (shown as \"Assigned Agent\" in task listings):\n 1. If a task already has an assigned agent, use that agent in TaskManagement-StartTaskExecution unless it is found incapable or inadequate of completing the task.\n 2. If a task has no assigned agent (shows \"Unassigned\"), select the most appropriate agent by reviewing the agent capabilities in your context or by calling TaskManagement-GetAgentNames and TaskManagement-GetAgentSummary.\n 3. Only reassign to a **different** agent if the currently assigned agent has already been tried and failed the task, and you need to retry with an alternative.\n\n# Completing the Scientists' Goal\n- When you are **confident** and believe that all areas of the scientist's goal have been achieved, you may proceed to completing the scientists' original goal by calling the Complete function. This will allow you to produce a final response that meets the GOAL.\n- You **SHOULD NOT** create a new task for the final output. Instead, execute the **EXISTING** human-created root task by calling TaskManagement-StartTaskExecution on it. The executing agent will aggregate all child task results into the root task's result, which is what the Scientist will see.\n- **CRITICAL**: Before calling the Complete function, verify there is NO remaining actionable AI work:\n - **Terminal states** (OK to complete): Complete, Removed, Stale, Failed, FlaggedHuman, FlaggedAi\n - **Active states** (NOT OK to complete): New, Incomplete, Executing, ExecutionDone, OnHold\n- **CRITICAL**: The Scientist's root task (the original human-created task) MUST be executed before calling Complete. When all child/dependent tasks are in terminal states:\n 1. Call TaskManagement-StartTaskExecution on the root task — the agent will synthesize all child task results into a final comprehensive output.\n 2. After execution completes, call TaskManagement-ValidateTask to verify and mark it Complete.\n 3. Only then call the Complete function to end the session.\n- **EXCEPTION**: You may call Complete if the root task is in FlaggedHuman or Failed state, meaning no further AI work is possible. Document the reason in your Complete response.\n- **DO NOT** confuse completing an individual task (use TaskManagement-ValidateTask or update task status) with calling the Complete function (ends the entire research session).\n- The Complete function should ONLY be called when there is absolutely NO remaining actionable AI work and ALL objectives have been accomplished or flagged for human review.\n\n# Task Completion Guidelines\n0. **ALWAYS** review the result of a completed task by reflecting on report or outputs.\n1. Do **ALWAYS** incorporate findings and scientific details from report content to update and inform further tasks.\n2. When TaskManagement-GetTaskStatus returns \"EXECUTION_DONE, next step is to validate\", IMMEDIATELY call TaskManagement-ValidateTask. Do NOT keep polling TaskManagement-GetTaskStatus - proceed to validation.\n\n# Task Update Guidelines\n0. Do **ALWAYS** make continual updates based on your thoughts; both thinking slow and fast are crucial to honing the specificity and direction.\n1. Do **ALWAYS** refine tasks to make them more scientifically specific, detailing specific proteins, genes, or design choices.\n2. Do **ALWAYS** create detailed validation requirements that incorporate thoughts and results.\n\n# Handling Failed or Incomplete Tasks\nWhen a task execution fails or returns as Incomplete, you should take the following actions:\n\n## Technical Failures (Gateway errors, system issues, agent crashes)\nIf a task result mentions technical errors such as \"gateway error\", \"connection failed\", \"timeout\", or similar system issues:\n1. **Retry the execution** by calling TaskManagement-StartTaskExecution on the same task again (up to 2-3 retries)\n2. If retries continue to fail, call TaskManagement-ValidateTask on the task - the ValidationAgent will flag it for human review\n3. Do NOT just create new tasks or keep thinking - take action by retrying or validating\n\n## Scientific/Quality Failures (Incomplete work, missing requirements)\nIf a task is marked Incomplete due to quality issues (not technical errors):\n1. Review the validation comments to understand what is missing\n2. Either retry with the same agent or assign to a different agent\n3. Update task description or requirements if clarification is needed\n\n## When to Flag for Human\nUse TaskManagement-ValidateTask to flag a task for human review when:\n- Technical errors persist after 2-3 retry attempts\n- The task requires capabilities that no available agent possesses\n- You have exhausted all available approaches and cannot make progress\n\n**IMPORTANT**: The TaskManagement-ValidateTask function is how you flag tasks for human review. The ValidationAgent can set the status to 'flagged_human' when appropriate.\n\n# Examples\nScenario: Task Incompleteness\nIn this scenario, a task is incomplete and requires further work to be completed in order to complete. Getting the details of that task will enable you to determine the gaps and what needs to be done to complete the task. To progress, you will either need to:\n- Create new tasks to fill in and address those gaps, or \n- Update the task description to include the missing details, or\n- Raise a flag to the human if your assessment deems it is not possible.\n\nScenario: Task Stalling\nIn this scenario, you have tried to complete a task multiple times, but it is still incomplete. First, retry TaskManagement-StartTaskExecution 2-3 times. If still failing, call TaskManagement-ValidateTask on the task to have it reviewed - the ValidationAgent will flag it for human intervention if needed.\n\nScenario: Task Aggregation\nIn this scenario, you have multiple tasks that are similar in nature and can be combined into a single task. You should look to combine those tasks into a single task to make it easier for the scientist to manage.\n\nScenario: Data Preparation\nIn this scenario, you are ready for computational experiments, but you need to gather the relevant data necessary. You may create detailed tasks that take the insights and results from previous tasks to inform which data will be necessary. Reviewing completed tasks will provide you the necessary scientific direction for data to collect which you will use to specify when creating the new task.\n\nScenario: Finishing the Scientist's Task or Goal\nIn this scenario, you have completed all necessary work needed to reach the scientist's task or goal. If you have incomplete tasks that you are unable to accomplish, please note them in the comments when working on the final task or goal.\n\n# Cross-Task Data Flow\nWhen a task has dependsOn set, the following data is automatically available to the executing agent:\n1. **Text results**: The task result text, description, status, and comments from each dependency task are injected into the agent's input prompt. This is how scientific findings, analysis summaries, and intermediate conclusions propagate between subtasks — no files needed.\n2. **Storage assets**: Storage assets produced by dependency tasks (via WriteResource) are seeded into the executing agent's data context. The agent can access them via GetResourceContext and PreviewResource. Storage assets attached to parent/root tasks (e.g., user-uploaded input files) are also automatically inherited by all subtasks.\n\n## Setting dependsOn correctly\n- dependsOn encodes data flow between subtasks. If task B needs results or files from task A, task B MUST have dependsOn: [task A's ID].\n- Without dependsOn, the executing agent will NOT have access to sibling task results or storage assets.\n- For chains (A → B → C), each task only needs direct dependsOn — transitive dependencies are resolved automatically. Task C depends on B, and B's dependency on A means C gets A's storage assets too.\n\n## Storage asset propagation\n- When an agent produces files via WriteResource, those files are recorded as storage assets in the task's TaskResult.StorageAssetIds.\n- These storage assets automatically propagate upward to parent tasks and forward to downstream dependent tasks.\n- The task's StorageAssetIds field reflects all storage assets available to that task, including inherited ones from parent tasks and dependency tasks.\n\n**BE PATIENT** and follow all guidelines strictly and do **NOT** deviate from them. The scenarios can serve as a guide, but you should not be limited to them. Use your own judgement to determine the best course of action.", - "createdAt": "2026-05-08T19:17:34.2654025Z", - "lastModifiedAt": "2026-05-15T23:55:39.709707Z", - "configuration": { - "temperature": 0.7, - "enableActing": true, - "upgradeInProgress": false - }, - "createdBy": null, - "createdByType": "User", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User" - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_update_discovery_engine.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_update_discovery_engine.json deleted file mode 100644 index a855cfbd6e2c..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_investigations.pyTestInvestigationstest_update_discovery_engine.json +++ /dev/null @@ -1,45 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/discoveryEngine?api-version=2026-02-01-preview", - "RequestMethod": "PATCH", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "35", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "discoveryEngineStatus": "Active" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:55:19 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "discoveryEngineStatus": "Active", - "systemPrompt": "You are an AI assistant assisting a Scientist in accomplishing research tasks through deep, scientific reasoning and principled actions. Your primary goal is to execute the scientific method and scientific tasks within that process to ensure comprehensive and effective progress towards completion. You aim to:\n- Think deeply and critically about the Scientist's goals and reason through them in a scientific manner,\n- Continually create, update, and execute tasks based on your thoughts and results of actions taken,\nultimately enabling you to accomplish the research objectives.\n\n# Module Roles\n- **Cognition module**: Uses FastThinking, SlowThinking, and Wait for reasoning and planning. Does NOT have task management access.\n- **Act module**: Uses TaskManagement tools for task operations. Responsible for flagging tasks for human review.\n- **CRITICAL**: Only call tools available to your module.\n\n# Scientific Method Guidelines\n0. Landscape Finding: You should be aware of where you currently are in the completion of the scientific method. This is accomplished by examining all tasks, which includes the prior tasks that have been completed, new tasks to be worked on, and the next steps to take. You should be able to identify the current state of knowledge and the gaps that need to be filled.\n1. Thoughtful Planning and Analysis: You should think and understand the scientist's task in detail. This includes analyzing the task, identifying key components, and understanding the overall objectives. You should break down complex tasks into smaller, manageable tasks that align with the long-term objectives.\n2. Dynamic Task Management: You should adapt and create tasks dynamically. As new data and insights emerge, you should create new tasks to remain responsive and relevant to the evolving research landscape. You can update tasks as needed to ensure alignment with tasks, though this is uncommon. Creating new tasks that are children of existing tasks is a common practice.\n3. Iterative Approach: You should think iteratively, using results of tasks you have executed to derive new insights to guide subsequent steps. This iterative approach allows you to refine strategies based on outcomes.\n4. Feedback as a Learning Tool: You should treat feedback as vital data. By integrating feedback into a continuous loop, you should inform future actions and adjust strategies, creating new tasks as needed to stay aligned with tasks.\n5. Continuous Exploration and Innovation: You should embrace a mindset of perpetual exploration, continually seeking new pathways and solutions. Even when current tasks are successful, you should continue to explore new ideas and approaches to drive innovation.\n\n# Scientific Task Execution Guidelines\n0. Accomplishing the Scientist's goal is the top priority. Their goal guides your research direction and the tasks you should create in order to make progress. \n1. **Do** think carefully when creating a new task. Ensure that all fields are properly specified and clarified without any ambiguity. Tasks should always have a link back to the Scientist's original goal with a direct dependency or a linkage through other tasks.\n2. Making updates to tasks should focus and add increased depth and/or specificity to the direction of the task. For example, this could be specific identified targets discovered in another task that now needs to be explore in further detail.\n3. Do **NOT** create tasks regarding the functionality of the system.\n4. Do **NOT** create tasks that can be accomplished by directly using the system. These include \"define validation requirements for task X\" or \"create a new task to break down task X\".\n5. Do **NOT** create tasks that are vague or general.\n6. Do **NOT** create redundant tasks; check to see if a task of similar intent already exists.\n7. Do **NOT** create tasks to reorganize, reclassify, align, or review tasks. Instead, **UPDATE** tasks appropriately using task properties.\n8. **ALWAYS** include specific scientific details in task descriptions. Here are a few examples... BAD: Conduct bioinformatics analysis to model interactions between identified key genes/proteins and the human immune system for monkeypox vaccine design. --> GOOD: Analyze the interactions between the A13L gene, E8L gene, and D8L gene as it will interact with the human immune system for monkeypox vaccine design.\n9. When creating tasks, be **CAREFUL** to note the proper depends_on structure. If these structures are not carefully defined, you will be unable to use the results of prior tasks to influence downstream ones. This is **CRITICAL**.\n10. **NEVER** look for human or scientist guidance for scientific decisions. However, you SHOULD flag tasks for human review via TaskManagement-ValidateTask when facing persistent technical failures or insurmountable blockers.\n11. **ONLY** leverage the tools you have available. If the scientific tool that you want to use is not available, you will have to adapt.\n\n# Agent Selection and Task Assignment\n- **ONLY** use agent names that exist in the system. Do **NOT** invent or guess agent names.\n- To discover available agents, use TaskManagement-GetAgentNames. To understand what a specific agent can do, use TaskManagement-GetAgentSummary.\n- Review the available agents and their capabilities listed in your context. If the context does not include agent information, call TaskManagement-GetAgentNames and TaskManagement-GetAgentSummary before assigning tasks.\n- Identify and assign the best-fit available agent to advance each task at its current lifecycle stage, based on present requirements and context.\n- When calling TaskManagement-StartTaskExecution, check the task's assigned agent (shown as \"Assigned Agent\" in task listings):\n 1. If a task already has an assigned agent, use that agent in TaskManagement-StartTaskExecution unless it is found incapable or inadequate of completing the task.\n 2. If a task has no assigned agent (shows \"Unassigned\"), select the most appropriate agent by reviewing the agent capabilities in your context or by calling TaskManagement-GetAgentNames and TaskManagement-GetAgentSummary.\n 3. Only reassign to a **different** agent if the currently assigned agent has already been tried and failed the task, and you need to retry with an alternative.\n\n# Completing the Scientists' Goal\n- When you are **confident** and believe that all areas of the scientist's goal have been achieved, you may proceed to completing the scientists' original goal by calling the Complete function. This will allow you to produce a final response that meets the GOAL.\n- You **SHOULD NOT** create a new task for the final output. Instead, execute the **EXISTING** human-created root task by calling TaskManagement-StartTaskExecution on it. The executing agent will aggregate all child task results into the root task's result, which is what the Scientist will see.\n- **CRITICAL**: Before calling the Complete function, verify there is NO remaining actionable AI work:\n - **Terminal states** (OK to complete): Complete, Removed, Stale, Failed, FlaggedHuman, FlaggedAi\n - **Active states** (NOT OK to complete): New, Incomplete, Executing, ExecutionDone, OnHold\n- **CRITICAL**: The Scientist's root task (the original human-created task) MUST be executed before calling Complete. When all child/dependent tasks are in terminal states:\n 1. Call TaskManagement-StartTaskExecution on the root task — the agent will synthesize all child task results into a final comprehensive output.\n 2. After execution completes, call TaskManagement-ValidateTask to verify and mark it Complete.\n 3. Only then call the Complete function to end the session.\n- **EXCEPTION**: You may call Complete if the root task is in FlaggedHuman or Failed state, meaning no further AI work is possible. Document the reason in your Complete response.\n- **DO NOT** confuse completing an individual task (use TaskManagement-ValidateTask or update task status) with calling the Complete function (ends the entire research session).\n- The Complete function should ONLY be called when there is absolutely NO remaining actionable AI work and ALL objectives have been accomplished or flagged for human review.\n\n# Task Completion Guidelines\n0. **ALWAYS** review the result of a completed task by reflecting on report or outputs.\n1. Do **ALWAYS** incorporate findings and scientific details from report content to update and inform further tasks.\n2. When TaskManagement-GetTaskStatus returns \"EXECUTION_DONE, next step is to validate\", IMMEDIATELY call TaskManagement-ValidateTask. Do NOT keep polling TaskManagement-GetTaskStatus - proceed to validation.\n\n# Task Update Guidelines\n0. Do **ALWAYS** make continual updates based on your thoughts; both thinking slow and fast are crucial to honing the specificity and direction.\n1. Do **ALWAYS** refine tasks to make them more scientifically specific, detailing specific proteins, genes, or design choices.\n2. Do **ALWAYS** create detailed validation requirements that incorporate thoughts and results.\n\n# Handling Failed or Incomplete Tasks\nWhen a task execution fails or returns as Incomplete, you should take the following actions:\n\n## Technical Failures (Gateway errors, system issues, agent crashes)\nIf a task result mentions technical errors such as \"gateway error\", \"connection failed\", \"timeout\", or similar system issues:\n1. **Retry the execution** by calling TaskManagement-StartTaskExecution on the same task again (up to 2-3 retries)\n2. If retries continue to fail, call TaskManagement-ValidateTask on the task - the ValidationAgent will flag it for human review\n3. Do NOT just create new tasks or keep thinking - take action by retrying or validating\n\n## Scientific/Quality Failures (Incomplete work, missing requirements)\nIf a task is marked Incomplete due to quality issues (not technical errors):\n1. Review the validation comments to understand what is missing\n2. Either retry with the same agent or assign to a different agent\n3. Update task description or requirements if clarification is needed\n\n## When to Flag for Human\nUse TaskManagement-ValidateTask to flag a task for human review when:\n- Technical errors persist after 2-3 retry attempts\n- The task requires capabilities that no available agent possesses\n- You have exhausted all available approaches and cannot make progress\n\n**IMPORTANT**: The TaskManagement-ValidateTask function is how you flag tasks for human review. The ValidationAgent can set the status to 'flagged_human' when appropriate.\n\n# Examples\nScenario: Task Incompleteness\nIn this scenario, a task is incomplete and requires further work to be completed in order to complete. Getting the details of that task will enable you to determine the gaps and what needs to be done to complete the task. To progress, you will either need to:\n- Create new tasks to fill in and address those gaps, or \n- Update the task description to include the missing details, or\n- Raise a flag to the human if your assessment deems it is not possible.\n\nScenario: Task Stalling\nIn this scenario, you have tried to complete a task multiple times, but it is still incomplete. First, retry TaskManagement-StartTaskExecution 2-3 times. If still failing, call TaskManagement-ValidateTask on the task to have it reviewed - the ValidationAgent will flag it for human intervention if needed.\n\nScenario: Task Aggregation\nIn this scenario, you have multiple tasks that are similar in nature and can be combined into a single task. You should look to combine those tasks into a single task to make it easier for the scientist to manage.\n\nScenario: Data Preparation\nIn this scenario, you are ready for computational experiments, but you need to gather the relevant data necessary. You may create detailed tasks that take the insights and results from previous tasks to inform which data will be necessary. Reviewing completed tasks will provide you the necessary scientific direction for data to collect which you will use to specify when creating the new task.\n\nScenario: Finishing the Scientist's Task or Goal\nIn this scenario, you have completed all necessary work needed to reach the scientist's task or goal. If you have incomplete tasks that you are unable to accomplish, please note them in the comments when working on the final task or goal.\n\n# Cross-Task Data Flow\nWhen a task has dependsOn set, the following data is automatically available to the executing agent:\n1. **Text results**: The task result text, description, status, and comments from each dependency task are injected into the agent's input prompt. This is how scientific findings, analysis summaries, and intermediate conclusions propagate between subtasks — no files needed.\n2. **Storage assets**: Storage assets produced by dependency tasks (via WriteResource) are seeded into the executing agent's data context. The agent can access them via GetResourceContext and PreviewResource. Storage assets attached to parent/root tasks (e.g., user-uploaded input files) are also automatically inherited by all subtasks.\n\n## Setting dependsOn correctly\n- dependsOn encodes data flow between subtasks. If task B needs results or files from task A, task B MUST have dependsOn: [task A's ID].\n- Without dependsOn, the executing agent will NOT have access to sibling task results or storage assets.\n- For chains (A → B → C), each task only needs direct dependsOn — transitive dependencies are resolved automatically. Task C depends on B, and B's dependency on A means C gets A's storage assets too.\n\n## Storage asset propagation\n- When an agent produces files via WriteResource, those files are recorded as storage assets in the task's TaskResult.StorageAssetIds.\n- These storage assets automatically propagate upward to parent tasks and forward to downstream dependent tasks.\n- The task's StorageAssetIds field reflects all storage assets available to that task, including inherited ones from parent tasks and dependency tasks.\n\n**BE PATIENT** and follow all guidelines strictly and do **NOT** deviate from them. The scenarios can serve as a guide, but you should not be limited to them. Use your own judgement to determine the best course of action.", - "createdAt": "2026-05-08T19:17:34.2654025Z", - "lastModifiedAt": "2026-05-15T23:55:19.5677269Z", - "configuration": { - "temperature": 0.7, - "enableActing": true, - "upgradeInProgress": false - }, - "createdBy": null, - "createdByType": "User", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User" - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_begin_delete.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_begin_delete.json deleted file mode 100644 index 8c6b501f0225..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_begin_delete.json +++ /dev/null @@ -1,144 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases/sdktestdelv1/versions/delv1?api-version=2026-02-01-preview", - "RequestMethod": "PATCH", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "403", - "Content-Type": "application/merge-patch+json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "description": "Sacrificial KB version for delete test", - "copilotInstruction": "Use this tool to query information about immersion cooling systems or liquid cooling technologies.", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ] - }, - "StatusCode": 201, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:57:14 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "name": "sdktestdelv1", - "version": "delv1", - "knowledgeBaseUrl": "", - "bookshelfName": "test-bkshlf", - "createdAt": "2026-05-15T23:57:12.5370453Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-15T23:57:12.5370453Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ], - "provisioningState": "Succeeded", - "status": "NotStarted", - "tags": [ - { - "key": "indexerType", - "value": "LGR" - } - ], - "description": "Sacrificial KB version for delete test", - "copilotInstruction": "Use this tool to query information about immersion cooling systems or liquid cooling technologies.", - "apiVersion": "2026-02-01-preview" - } - }, - { - "RequestUri": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases/sdktestdelv1/versions/delv1?api-version=2026-02-01-preview", - "RequestMethod": "DELETE", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "0", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 202, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:57:16 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "operation-location": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases/sdktestdelv1/versions/delv1/operations/deletekb-test-bkshlf-sdktestdelv1-delv1?api-version=2026-02-01-preview", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "Running" - } - }, - { - "RequestUri": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases/sdktestdelv1/versions/delv1/operations/deletekb-test-bkshlf-sdktestdelv1-delv1?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:57:18 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "Running" - } - }, - { - "RequestUri": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases/sdktestdelv1/versions/delv1/operations/deletekb-test-bkshlf-sdktestdelv1-delv1?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:57:49 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "Succeeded" - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_begin_delete_latest_version.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_begin_delete_latest_version.json deleted file mode 100644 index 3ebe5cd6ccb1..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_begin_delete_latest_version.json +++ /dev/null @@ -1,144 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases/sdktestdelv2/versions/delv2?api-version=2026-02-01-preview", - "RequestMethod": "PATCH", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "410", - "Content-Type": "application/merge-patch+json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "description": "Sacrificial KB version for delete-latest test", - "copilotInstruction": "Use this tool to query information about immersion cooling systems or liquid cooling technologies.", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ] - }, - "StatusCode": 201, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:57:55 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "name": "sdktestdelv2", - "version": "delv2", - "knowledgeBaseUrl": "", - "bookshelfName": "test-bkshlf", - "createdAt": "2026-05-15T23:57:55.0581782Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-15T23:57:55.0581782Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ], - "provisioningState": "Succeeded", - "status": "NotStarted", - "tags": [ - { - "key": "indexerType", - "value": "LGR" - } - ], - "description": "Sacrificial KB version for delete-latest test", - "copilotInstruction": "Use this tool to query information about immersion cooling systems or liquid cooling technologies.", - "apiVersion": "2026-02-01-preview" - } - }, - { - "RequestUri": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases/sdktestdelv2/versions/@latest?api-version=2026-02-01-preview", - "RequestMethod": "DELETE", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "0", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 202, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:57:58 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "operation-location": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases/sdktestdelv2/versions/delv2/operations/deletekb-test-bkshlf-sdktestdelv2-delv2?api-version=2026-02-01-preview", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "Running" - } - }, - { - "RequestUri": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases/sdktestdelv2/versions/delv2/operations/deletekb-test-bkshlf-sdktestdelv2-delv2?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:57:59 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "Running" - } - }, - { - "RequestUri": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases/sdktestdelv2/versions/delv2/operations/deletekb-test-bkshlf-sdktestdelv2-delv2?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:58:31 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "Succeeded" - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_create_or_update.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_create_or_update.json deleted file mode 100644 index e43bece84752..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_create_or_update.json +++ /dev/null @@ -1,67 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases/test-kb/versions/v1?api-version=2026-02-01-preview", - "RequestMethod": "PATCH", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "463", - "Content-Type": "application/merge-patch+json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "description": "Use this tool to query information about immersion cooling systems or liquid cooling technologies.", - "copilotInstruction": "Use this tool to query information about immersion cooling systems or liquid cooling technologies.", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ] - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:56:44 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "name": "test-kb", - "version": "v1", - "knowledgeBaseUrl": "", - "bookshelfName": "test-bkshlf", - "createdAt": "2026-05-10T02:52:11.2547143Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-15T23:56:43.6918552Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ], - "provisioningState": "Succeeded", - "status": "Failed", - "tags": [ - { - "key": "indexerType", - "value": "LGR" - } - ], - "description": "Use this tool to query information about immersion cooling systems or liquid cooling technologies.", - "copilotInstruction": "Use this tool to query information about immersion cooling systems or liquid cooling technologies.", - "apiVersion": "2026-02-01-preview" - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_get.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_get.json deleted file mode 100644 index 425444396fe6..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_get.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases/test-kb/versions/v1?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:56:55 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "name": "test-kb", - "version": "v1", - "knowledgeBaseUrl": "", - "bookshelfName": "test-bkshlf", - "createdAt": "2026-05-10T02:52:11.2547143Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-15T23:56:43.6918552Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ], - "provisioningState": "Succeeded", - "status": "Failed", - "tags": [ - { - "key": "indexerType", - "value": "LGR" - } - ], - "description": "Use this tool to query information about immersion cooling systems or liquid cooling technologies.", - "copilotInstruction": "Use this tool to query information about immersion cooling systems or liquid cooling technologies.", - "apiVersion": "2026-02-01-preview" - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_get_latest_version.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_get_latest_version.json deleted file mode 100644 index edd776b4daa0..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_get_latest_version.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases/test-kb/versions/@latest?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:56:58 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "name": "test-kb", - "version": "v1", - "knowledgeBaseUrl": "", - "bookshelfName": "test-bkshlf", - "createdAt": "2026-05-10T02:52:11.2547143Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-15T23:56:43.6918552Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ], - "provisioningState": "Succeeded", - "status": "Failed", - "tags": [ - { - "key": "indexerType", - "value": "LGR" - } - ], - "description": "Use this tool to query information about immersion cooling systems or liquid cooling technologies.", - "copilotInstruction": "Use this tool to query information about immersion cooling systems or liquid cooling technologies.", - "apiVersion": "2026-02-01-preview" - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_get_operation_status.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_get_operation_status.json deleted file mode 100644 index 67a5ee8795fb..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_get_operation_status.json +++ /dev/null @@ -1,134 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases/test-kb/versions/v1:startIndexing?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "375", - "Content-Type": "application/json", - "Repeatability-First-Sent": "Sanitized", - "Repeatability-Request-ID": "Sanitized", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "nodePoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "projectId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/workspaces/test-wkspc/projects/test-project" - }, - "StatusCode": 202, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:57:02 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "operation-location": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases/test-kb/versions/v1/operations/indexingrune68cc6beff3361d6502a66fb8d1633fe?api-version=2026-02-01-preview", - "repeatability-result": "accepted", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "Processing", - "result": { - "runId": "indexingrune68cc6beff3361d6502a66fb8d1633fe" - } - } - }, - { - "RequestUri": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases/test-kb/versions/v1/operations/indexingrune68cc6beff3361d6502a66fb8d1633fe?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:57:05 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "Processing", - "result": { - "id": "Sanitized", - "name": "test-kb", - "version": "v1", - "knowledgeBaseUrl": "", - "createdAt": "2026-05-10T02:52:11.2547143Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-15T23:57:02.558517Z", - "lastModifiedBy": "Sanitized", - "bookshelfName": "test-bkshlf", - "lastModifiedByType": "User", - "dataAssetIds": [], - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ], - "provisioningState": "Succeeded", - "status": "Running", - "tags": [ - { - "key": "indexerType", - "value": "LGR" - } - ], - "description": "Use this tool to query information about immersion cooling systems or liquid cooling technologies.", - "copilotInstruction": "Use this tool to query information about immersion cooling systems or liquid cooling technologies.", - "apiVersion": "2026-02-01-preview" - } - } - }, - { - "RequestUri": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases/test-kb/versions/v1:cancelIndexing?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "186", - "Content-Type": "application/json", - "Repeatability-First-Sent": "Sanitized", - "Repeatability-Request-ID": "Sanitized", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "nodePoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1" - }, - "StatusCode": 202, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:57:08 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "operation-location": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases/test-kb/versions/v1/operations/indexingrune68cc6beff3361d6502a66fb8d1633fe?api-version=2026-02-01-preview", - "repeatability-result": "accepted", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "Processing", - "result": { - "runId": "indexingrune68cc6beff3361d6502a66fb8d1633fe" - } - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_list.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_list.json deleted file mode 100644 index 81695dc35e22..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_base_versions.pyTestKnowledgeBaseVersionsOperationstest_list.json +++ /dev/null @@ -1,60 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases/test-kb/versions?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:56:52 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "value": [ - { - "id": "Sanitized", - "name": "test-kb", - "version": "v1", - "knowledgeBaseUrl": "", - "bookshelfName": "test-bkshlf", - "createdAt": "2026-05-10T02:52:11.2547143Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-15T23:56:43.6918552Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ], - "provisioningState": "Succeeded", - "status": "Failed", - "tags": [ - { - "key": "indexerType", - "value": "LGR" - } - ], - "description": "Use this tool to query information about immersion cooling systems or liquid cooling technologies.", - "copilotInstruction": "Use this tool to query information about immersion cooling systems or liquid cooling technologies.", - "apiVersion": "2026-02-01-preview" - } - ] - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_bases.pyTestKnowledgeBasesOperationstest_list.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_bases.pyTestKnowledgeBasesOperationstest_list.json deleted file mode 100644 index 19f495befc0e..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_knowledge_bases.pyTestKnowledgeBasesOperationstest_list.json +++ /dev/null @@ -1,394 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-bookshelf.bookshelf.discovery.azure.com/knowledgeBases?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:58:35 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "value": [ - { - "id": "Sanitized", - "name": "pfaskb1", - "version": "v1", - "knowledgeBaseUrl": "test-dbtst-0000000000.database.windows.net", - "bookshelfName": "test-bkshlf", - "createdAt": "2026-03-25T17:22:12.2459663Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-04-21T15:54:17.187051Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ], - "provisioningState": "Succeeded", - "status": "Succeeded", - "tags": [ - { - "key": "type", - "value": "testgs" - }, - { - "key": "indexerType", - "value": "LGR" - } - ], - "description": "PFAS introduction", - "copilotInstruction": "PFAS introduction", - "apiVersion": "2026-02-01-preview" - }, - { - "id": "Sanitized", - "name": "test-kb", - "version": "v1", - "knowledgeBaseUrl": "", - "bookshelfName": "test-bkshlf", - "createdAt": "2026-05-10T02:52:11.2547143Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-15T23:57:02.558517Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ], - "provisioningState": "Succeeded", - "status": "Running", - "tags": [ - { - "key": "indexerType", - "value": "LGR" - } - ], - "description": "Use this tool to query information about immersion cooling systems or liquid cooling technologies.", - "copilotInstruction": "Use this tool to query information about immersion cooling systems or liquid cooling technologies.", - "apiVersion": "2026-02-01-preview" - }, - { - "id": "Sanitized", - "name": "cskbcreate", - "version": "v1", - "knowledgeBaseUrl": "", - "bookshelfName": "test-bkshlf", - "createdAt": "2026-05-12T01:56:58.7277836Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-12T02:20:28.0110259Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ], - "provisioningState": "Succeeded", - "status": "NotStarted", - "tags": [ - { - "key": "indexerType", - "value": "LGR" - } - ], - "description": "Test KB version", - "copilotInstruction": "Test instruction", - "apiVersion": "2026-02-01-preview" - }, - { - "id": "Sanitized", - "name": "kbcrtpt1kr2mg", - "version": "v1", - "knowledgeBaseUrl": "", - "bookshelfName": "test-bkshlf", - "createdAt": "2026-05-12T03:01:18.9910452Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-12T03:01:18.9910452Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ], - "provisioningState": "Succeeded", - "status": "NotStarted", - "tags": [ - { - "key": "indexerType", - "value": "LGR" - } - ], - "description": "Test KB version", - "copilotInstruction": "Test instruction", - "apiVersion": "2026-02-01-preview" - }, - { - "id": "Sanitized", - "name": "kbopsiyosjjai", - "version": "v1", - "knowledgeBaseUrl": "", - "bookshelfName": "test-bkshlf", - "createdAt": "2026-05-12T03:01:43.5456071Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-12T03:11:35.5684625Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ], - "provisioningState": "Succeeded", - "status": "Failed", - "tags": [ - { - "key": "indexerType", - "value": "LGR" - } - ], - "description": "KB version for GetOperationStatus test", - "copilotInstruction": "Test instruction", - "apiVersion": "2026-02-01-preview" - }, - { - "id": "Sanitized", - "name": "kbcrtkbnmr7a9", - "version": "v1", - "knowledgeBaseUrl": "", - "bookshelfName": "test-bkshlf", - "createdAt": "2026-05-12T03:02:09.0842156Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-12T03:02:09.0842156Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ], - "provisioningState": "Succeeded", - "status": "NotStarted", - "tags": [ - { - "key": "indexerType", - "value": "LGR" - } - ], - "description": "Test KB version", - "copilotInstruction": "Test instruction", - "apiVersion": "2026-02-01-preview" - }, - { - "id": "Sanitized", - "name": "kbopsslh0nfdz", - "version": "v1", - "knowledgeBaseUrl": "", - "bookshelfName": "test-bkshlf", - "createdAt": "2026-05-12T03:02:34.4373269Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-12T03:13:36.6348633Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ], - "provisioningState": "Succeeded", - "status": "Failed", - "tags": [ - { - "key": "indexerType", - "value": "LGR" - } - ], - "description": "KB version for GetOperationStatus test", - "copilotInstruction": "Test instruction", - "apiVersion": "2026-02-01-preview" - }, - { - "id": "Sanitized", - "name": "jkbcreate", - "version": "v1", - "knowledgeBaseUrl": "", - "bookshelfName": "test-bkshlf", - "createdAt": "2026-05-13T23:34:31.145588Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-15T01:31:07.8484567Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ], - "provisioningState": "Succeeded", - "status": "NotStarted", - "tags": [ - { - "key": "indexerType", - "value": "LGR" - } - ], - "description": "Java SDK test KB version", - "copilotInstruction": "Test instruction", - "apiVersion": "2026-02-01-preview" - }, - { - "id": "Sanitized", - "name": "jkbops881840e", - "version": "v1", - "knowledgeBaseUrl": "", - "bookshelfName": "test-bkshlf", - "createdAt": "2026-05-15T00:11:52.8607075Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-15T00:51:39.8661754Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ], - "provisioningState": "Succeeded", - "status": "Failed", - "tags": [ - { - "key": "indexerType", - "value": "LGR" - } - ], - "description": "KB version for getOperationStatus test", - "copilotInstruction": "Test instruction", - "apiVersion": "2026-02-01-preview" - }, - { - "id": "Sanitized", - "name": "jkbops5598541", - "version": "v1", - "knowledgeBaseUrl": "", - "bookshelfName": "test-bkshlf", - "createdAt": "2026-05-15T00:14:09.2972247Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-15T01:15:19.5513896Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ], - "provisioningState": "Succeeded", - "status": "Failed", - "tags": [ - { - "key": "indexerType", - "value": "LGR" - } - ], - "description": "KB version for getOperationStatus test", - "copilotInstruction": "Test instruction", - "apiVersion": "2026-02-01-preview" - }, - { - "id": "Sanitized", - "name": "jkbops661028e", - "version": "v1", - "knowledgeBaseUrl": "", - "bookshelfName": "test-bkshlf", - "createdAt": "2026-05-15T00:36:42.4338408Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-15T01:16:25.4421724Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ], - "provisioningState": "Succeeded", - "status": "Failed", - "tags": [ - { - "key": "indexerType", - "value": "LGR" - } - ], - "description": "KB version for getOperationStatus test", - "copilotInstruction": "Test instruction", - "apiVersion": "2026-02-01-preview" - }, - { - "id": "Sanitized", - "name": "jkbops12648f9", - "version": "v1", - "knowledgeBaseUrl": "", - "bookshelfName": "test-bkshlf", - "createdAt": "2026-05-15T01:30:53.2496395Z", - "createdBy": "Sanitized", - "createdByType": "User", - "lastModifiedAt": "2026-05-15T01:40:10.9709743Z", - "lastModifiedBy": "Sanitized", - "lastModifiedByType": "User", - "storageAssetReferences": [ - { - "id": "Sanitized", - "userAssignedIdentity": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.ManagedIdentity/userAssignedIdentities/test-mi" - } - ], - "provisioningState": "Succeeded", - "status": "Failed", - "tags": [ - { - "key": "indexerType", - "value": "LGR" - } - ], - "description": "KB version for getOperationStatus test", - "copilotInstruction": "Test instruction", - "apiVersion": "2026-02-01-preview" - } - ] - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_add_comment.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_add_comment.json deleted file mode 100644 index ef5eadc30085..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_add_comment.json +++ /dev/null @@ -1,173 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "231", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "title": "task-for-comment-test", - "priority": "High", - "description": "Test task for Python SDK", - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "investigationId": "/projects/test-project/investigations/test-invst" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:59:38 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "5090262789708010588", - "title": "task-for-comment-test", - "priority": "High", - "description": "Test task for Python SDK", - "validationRequirements": [], - "parentId": null, - "dependsOn": [], - "relatedTo": [], - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "comments": [], - "createdByType": "User", - "status": "New", - "createdAt": "2026-05-15T23:59:38.6187524Z", - "lastModifiedAt": "2026-05-15T23:59:38.6187524Z", - "executionHistory": [ - { - "createdAt": "2026-05-15T23:59:38.6187524Z", - "action": "taskCreated", - "createdBy": "Sanitized", - "createdByType": "User", - "summary": "Task created: task-for-comment-test" - } - ], - "taskCollectionId": "5215043646661345540", - "investigationId": "/projects/test-project/investigations/test-invst", - "taskResult": { - "text": "", - "storageAssetIds": [], - "citations": [] - }, - "storageAssetIds": [], - "lastModifiedByType": "User", - "lastModifiedBy": "Sanitized", - "createdBy": "Sanitized", - "foundryConversationId": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks/5090262789708010588:addComment?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "105", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "timestamp": "2026-04-08T21:00:00Z", - "createdBy": "Sanitized", - "createdByType": "User", - "text": "Test comment" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:59:40 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "5090262789708010588", - "title": "task-for-comment-test", - "priority": "High", - "description": "Test task for Python SDK", - "validationRequirements": [], - "parentId": null, - "dependsOn": [], - "relatedTo": [], - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "comments": [ - { - "timestamp": "2026-04-08T21:00:00Z", - "createdBy": "Sanitized", - "createdByType": "User", - "text": "Test comment" - } - ], - "createdByType": "User", - "status": "New", - "createdAt": "2026-05-15T23:59:38.6187524Z", - "lastModifiedAt": "2026-05-15T23:59:40.4486884Z", - "executionHistory": [ - { - "createdAt": "2026-05-15T23:59:38.6187524Z", - "action": "taskCreated", - "createdBy": "Sanitized", - "createdByType": "User", - "summary": "Task created: task-for-comment-test" - } - ], - "taskCollectionId": "5215043646661345540", - "investigationId": "/projects/test-project/investigations/test-invst", - "taskResult": { - "text": "", - "storageAssetIds": [], - "citations": [] - }, - "storageAssetIds": [], - "lastModifiedByType": "User", - "lastModifiedBy": "Sanitized", - "createdBy": "Sanitized", - "foundryConversationId": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks/5090262789708010588?api-version=2026-02-01-preview", - "RequestMethod": "DELETE", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "Content-Length": "0", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 204, - "ResponseHeaders": { - "Connection": "keep-alive", - "Date": "Fri, 15 May 2026 23:59:42 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": null - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_add_execution_history.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_add_execution_history.json deleted file mode 100644 index b3cf9347918a..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_add_execution_history.json +++ /dev/null @@ -1,174 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "236", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "title": "task-for-exec-history-test", - "priority": "High", - "description": "Test task for Python SDK", - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "investigationId": "/projects/test-project/investigations/test-invst" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:59:46 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "5085059468704295156", - "title": "task-for-exec-history-test", - "priority": "High", - "description": "Test task for Python SDK", - "validationRequirements": [], - "parentId": null, - "dependsOn": [], - "relatedTo": [], - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "comments": [], - "createdByType": "User", - "status": "New", - "createdAt": "2026-05-15T23:59:46.4626568Z", - "lastModifiedAt": "2026-05-15T23:59:46.4626568Z", - "executionHistory": [ - { - "createdAt": "2026-05-15T23:59:46.4626568Z", - "action": "taskCreated", - "createdBy": "Sanitized", - "createdByType": "User", - "summary": "Task created: task-for-exec-history-test" - } - ], - "taskCollectionId": "5215043646661345540", - "investigationId": "/projects/test-project/investigations/test-invst", - "taskResult": { - "text": "", - "storageAssetIds": [], - "citations": [] - }, - "storageAssetIds": [], - "lastModifiedByType": "User", - "lastModifiedBy": "Sanitized", - "createdBy": "Sanitized", - "foundryConversationId": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks/5085059468704295156:addExecutionHistory?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "148", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "createdAt": "2026-04-08T21:00:00Z", - "action": "completed", - "createdBy": "Sanitized", - "createdByType": "Application", - "summary": "Task execution completed" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:59:48 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "5085059468704295156", - "title": "task-for-exec-history-test", - "priority": "High", - "description": "Test task for Python SDK", - "validationRequirements": [], - "parentId": null, - "dependsOn": [], - "relatedTo": [], - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "comments": [], - "createdByType": "User", - "status": "New", - "createdAt": "2026-05-15T23:59:46.4626568Z", - "lastModifiedAt": "2026-05-15T23:59:48.5461643Z", - "executionHistory": [ - { - "createdAt": "2026-05-15T23:59:46.4626568Z", - "action": "taskCreated", - "createdBy": "Sanitized", - "createdByType": "User", - "summary": "Task created: task-for-exec-history-test" - }, - { - "createdAt": "2026-04-08T21:00:00Z", - "action": "completed", - "createdBy": "Sanitized", - "createdByType": "Application", - "summary": "Task execution completed" - } - ], - "taskCollectionId": "5215043646661345540", - "investigationId": "/projects/test-project/investigations/test-invst", - "taskResult": { - "text": "", - "storageAssetIds": [], - "citations": [] - }, - "storageAssetIds": [], - "lastModifiedByType": "User", - "lastModifiedBy": "Sanitized", - "createdBy": "Sanitized", - "foundryConversationId": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks/5085059468704295156?api-version=2026-02-01-preview", - "RequestMethod": "DELETE", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "Content-Length": "0", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 204, - "ResponseHeaders": { - "Connection": "keep-alive", - "Date": "Fri, 15 May 2026 23:59:50 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": null - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_create.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_create.json deleted file mode 100644 index 7d6be01c26ff..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_create.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "224", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "title": "A new sdk task", - "priority": "High", - "description": "Test task for Python SDK", - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "investigationId": "/projects/test-project/investigations/test-invst" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:58:49 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "5584174122409283759", - "title": "A new sdk task", - "priority": "High", - "description": "Test task for Python SDK", - "validationRequirements": [], - "parentId": null, - "dependsOn": [], - "relatedTo": [], - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "comments": [], - "createdByType": "User", - "status": "New", - "createdAt": "2026-05-15T23:58:49.2365121Z", - "lastModifiedAt": "2026-05-15T23:58:49.2365121Z", - "executionHistory": [ - { - "createdAt": "2026-05-15T23:58:49.2365121Z", - "action": "taskCreated", - "createdBy": "Sanitized", - "createdByType": "User", - "summary": "Task created: A new sdk task" - } - ], - "taskCollectionId": "5215043646661345540", - "investigationId": "/projects/test-project/investigations/test-invst", - "taskResult": { - "text": "", - "storageAssetIds": [], - "citations": [] - }, - "storageAssetIds": [], - "lastModifiedByType": "User", - "lastModifiedBy": "Sanitized", - "createdBy": "Sanitized", - "foundryConversationId": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks/5584174122409283759?api-version=2026-02-01-preview", - "RequestMethod": "DELETE", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "Content-Length": "0", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 204, - "ResponseHeaders": { - "Connection": "keep-alive", - "Date": "Fri, 15 May 2026 23:58:51 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": null - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_delete.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_delete.json deleted file mode 100644 index 7a7ac73b994a..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_delete.json +++ /dev/null @@ -1,98 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "230", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "title": "task-for-delete-test", - "priority": "High", - "description": "Test task for Python SDK", - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "investigationId": "/projects/test-project/investigations/test-invst" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:59:14 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "5003115330298088532", - "title": "task-for-delete-test", - "priority": "High", - "description": "Test task for Python SDK", - "validationRequirements": [], - "parentId": null, - "dependsOn": [], - "relatedTo": [], - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "comments": [], - "createdByType": "User", - "status": "New", - "createdAt": "2026-05-15T23:59:14.6672229Z", - "lastModifiedAt": "2026-05-15T23:59:14.6672229Z", - "executionHistory": [ - { - "createdAt": "2026-05-15T23:59:14.6672229Z", - "action": "taskCreated", - "createdBy": "Sanitized", - "createdByType": "User", - "summary": "Task created: task-for-delete-test" - } - ], - "taskCollectionId": "5215043646661345540", - "investigationId": "/projects/test-project/investigations/test-invst", - "taskResult": { - "text": "", - "storageAssetIds": [], - "citations": [] - }, - "storageAssetIds": [], - "lastModifiedByType": "User", - "lastModifiedBy": "Sanitized", - "createdBy": "Sanitized", - "foundryConversationId": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks/5003115330298088532?api-version=2026-02-01-preview", - "RequestMethod": "DELETE", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "Content-Length": "0", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 204, - "ResponseHeaders": { - "Connection": "keep-alive", - "Date": "Fri, 15 May 2026 23:59:16 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": null - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_get.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_get.json deleted file mode 100644 index ce8a4f60b922..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_get.json +++ /dev/null @@ -1,159 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "227", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "title": "task-for-get-test", - "priority": "High", - "description": "Test task for Python SDK", - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "investigationId": "/projects/test-project/investigations/test-invst" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:58:58 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "5016624948271181322", - "title": "task-for-get-test", - "priority": "High", - "description": "Test task for Python SDK", - "validationRequirements": [], - "parentId": null, - "dependsOn": [], - "relatedTo": [], - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "comments": [], - "createdByType": "User", - "status": "New", - "createdAt": "2026-05-15T23:58:57.9619116Z", - "lastModifiedAt": "2026-05-15T23:58:57.9619116Z", - "executionHistory": [ - { - "createdAt": "2026-05-15T23:58:57.9619116Z", - "action": "taskCreated", - "createdBy": "Sanitized", - "createdByType": "User", - "summary": "Task created: task-for-get-test" - } - ], - "taskCollectionId": "5215043646661345540", - "investigationId": "/projects/test-project/investigations/test-invst", - "taskResult": { - "text": "", - "storageAssetIds": [], - "citations": [] - }, - "storageAssetIds": [], - "lastModifiedByType": "User", - "lastModifiedBy": "Sanitized", - "createdBy": "Sanitized", - "foundryConversationId": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks/5016624948271181322?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:59:00 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "5016624948271181322", - "title": "task-for-get-test", - "priority": "High", - "description": "Test task for Python SDK", - "validationRequirements": [], - "parentId": null, - "dependsOn": [], - "relatedTo": [], - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "comments": [], - "createdByType": "User", - "status": "New", - "createdAt": "2026-05-15T23:58:57.9619116Z", - "lastModifiedAt": "2026-05-15T23:58:57.9619116Z", - "executionHistory": [ - { - "createdAt": "2026-05-15T23:58:57.9619116Z", - "action": "taskCreated", - "createdBy": "Sanitized", - "createdByType": "User", - "summary": "Task created: task-for-get-test" - } - ], - "taskCollectionId": "5215043646661345540", - "investigationId": "/projects/test-project/investigations/test-invst", - "taskResult": { - "text": "", - "storageAssetIds": [], - "citations": [] - }, - "storageAssetIds": [], - "lastModifiedByType": "User", - "lastModifiedBy": "Sanitized", - "createdBy": "Sanitized", - "foundryConversationId": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks/5016624948271181322?api-version=2026-02-01-preview", - "RequestMethod": "DELETE", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "Content-Length": "0", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 204, - "ResponseHeaders": { - "Connection": "keep-alive", - "Date": "Fri, 15 May 2026 23:59:02 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": null - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_list.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_list.json deleted file mode 100644 index f909ec51d474..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_list.json +++ /dev/null @@ -1,164 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "228", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "title": "task-for-list-test", - "priority": "High", - "description": "Test task for Python SDK", - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "investigationId": "/projects/test-project/investigations/test-invst" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:58:40 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "5179765376681240914", - "title": "task-for-list-test", - "priority": "High", - "description": "Test task for Python SDK", - "validationRequirements": [], - "parentId": null, - "dependsOn": [], - "relatedTo": [], - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "comments": [], - "createdByType": "User", - "status": "New", - "createdAt": "2026-05-15T23:58:39.9916319Z", - "lastModifiedAt": "2026-05-15T23:58:39.9916319Z", - "executionHistory": [ - { - "createdAt": "2026-05-15T23:58:39.9916319Z", - "action": "taskCreated", - "createdBy": "Sanitized", - "createdByType": "User", - "summary": "Task created: task-for-list-test" - } - ], - "taskCollectionId": "5215043646661345540", - "investigationId": "/projects/test-project/investigations/test-invst", - "taskResult": { - "text": "", - "storageAssetIds": [], - "citations": [] - }, - "storageAssetIds": [], - "lastModifiedByType": "User", - "lastModifiedBy": "Sanitized", - "createdBy": "Sanitized", - "foundryConversationId": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:58:42 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "value": [ - { - "name": "5179765376681240914", - "title": "task-for-list-test", - "priority": "High", - "description": "Test task for Python SDK", - "validationRequirements": [], - "parentId": null, - "dependsOn": [], - "relatedTo": [], - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "comments": [], - "createdByType": "User", - "status": "New", - "createdAt": "2026-05-15T23:58:39.9916319Z", - "lastModifiedAt": "2026-05-15T23:58:39.9916319Z", - "executionHistory": [ - { - "createdAt": "2026-05-15T23:58:39.9916319Z", - "action": "taskCreated", - "createdBy": "Sanitized", - "createdByType": "User", - "summary": "Task created: task-for-list-test" - } - ], - "taskCollectionId": "5215043646661345540", - "investigationId": "/projects/test-project/investigations/test-invst", - "taskResult": { - "text": "", - "storageAssetIds": [], - "citations": [] - }, - "storageAssetIds": [], - "lastModifiedByType": "User", - "lastModifiedBy": "Sanitized", - "createdBy": "Sanitized", - "foundryConversationId": null - } - ], - "nextLink": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks/5179765376681240914?api-version=2026-02-01-preview", - "RequestMethod": "DELETE", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "Content-Length": "0", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 204, - "ResponseHeaders": { - "Connection": "keep-alive", - "Date": "Fri, 15 May 2026 23:58:45 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": null - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_list_with_filter.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_list_with_filter.json deleted file mode 100644 index 036bba5a3e58..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_list_with_filter.json +++ /dev/null @@ -1,164 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "230", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "title": "task-for-filter-test", - "priority": "High", - "description": "Test task for Python SDK", - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "investigationId": "/projects/test-project/investigations/test-invst" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:59:20 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "4691394372835118639", - "title": "task-for-filter-test", - "priority": "High", - "description": "Test task for Python SDK", - "validationRequirements": [], - "parentId": null, - "dependsOn": [], - "relatedTo": [], - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "comments": [], - "createdByType": "User", - "status": "New", - "createdAt": "2026-05-15T23:59:20.1964221Z", - "lastModifiedAt": "2026-05-15T23:59:20.1964221Z", - "executionHistory": [ - { - "createdAt": "2026-05-15T23:59:20.1964221Z", - "action": "taskCreated", - "createdBy": "Sanitized", - "createdByType": "User", - "summary": "Task created: task-for-filter-test" - } - ], - "taskCollectionId": "5215043646661345540", - "investigationId": "/projects/test-project/investigations/test-invst", - "taskResult": { - "text": "", - "storageAssetIds": [], - "citations": [] - }, - "storageAssetIds": [], - "lastModifiedByType": "User", - "lastModifiedBy": "Sanitized", - "createdBy": "Sanitized", - "foundryConversationId": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks?api-version=2026-02-01-preview&filter=status%20eq%20%27New%27", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:59:22 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "value": [ - { - "name": "4691394372835118639", - "title": "task-for-filter-test", - "priority": "High", - "description": "Test task for Python SDK", - "validationRequirements": [], - "parentId": null, - "dependsOn": [], - "relatedTo": [], - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "comments": [], - "createdByType": "User", - "status": "New", - "createdAt": "2026-05-15T23:59:20.1964221Z", - "lastModifiedAt": "2026-05-15T23:59:20.1964221Z", - "executionHistory": [ - { - "createdAt": "2026-05-15T23:59:20.1964221Z", - "action": "taskCreated", - "createdBy": "Sanitized", - "createdByType": "User", - "summary": "Task created: task-for-filter-test" - } - ], - "taskCollectionId": "5215043646661345540", - "investigationId": "/projects/test-project/investigations/test-invst", - "taskResult": { - "text": "", - "storageAssetIds": [], - "citations": [] - }, - "storageAssetIds": [], - "lastModifiedByType": "User", - "lastModifiedBy": "Sanitized", - "createdBy": "Sanitized", - "foundryConversationId": null - } - ], - "nextLink": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks/4691394372835118639?api-version=2026-02-01-preview", - "RequestMethod": "DELETE", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "Content-Length": "0", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 204, - "ResponseHeaders": { - "Connection": "keep-alive", - "Date": "Fri, 15 May 2026 23:59:24 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": null - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_start.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_start.json deleted file mode 100644 index 6737c3df8bf3..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_start.json +++ /dev/null @@ -1,186 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "229", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "title": "task-for-start-test", - "priority": "High", - "description": "Test task for Python SDK", - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "investigationId": "/projects/test-project/investigations/test-invst" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:59:27 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "4975886658412173146", - "title": "task-for-start-test", - "priority": "High", - "description": "Test task for Python SDK", - "validationRequirements": [], - "parentId": null, - "dependsOn": [], - "relatedTo": [], - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "comments": [], - "createdByType": "User", - "status": "New", - "createdAt": "2026-05-15T23:59:27.4912978Z", - "lastModifiedAt": "2026-05-15T23:59:27.4912978Z", - "executionHistory": [ - { - "createdAt": "2026-05-15T23:59:27.4912978Z", - "action": "taskCreated", - "createdBy": "Sanitized", - "createdByType": "User", - "summary": "Task created: task-for-start-test" - } - ], - "taskCollectionId": "5215043646661345540", - "investigationId": "/projects/test-project/investigations/test-invst", - "taskResult": { - "text": "", - "storageAssetIds": [], - "citations": [] - }, - "storageAssetIds": [], - "lastModifiedByType": "User", - "lastModifiedBy": "Sanitized", - "createdBy": "Sanitized", - "foundryConversationId": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks/4975886658412173146:start?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "0", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:59:33 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "4975886658412173146", - "title": "task-for-start-test", - "priority": "High", - "description": "Test task for Python SDK", - "validationRequirements": [], - "parentId": null, - "dependsOn": [], - "relatedTo": [], - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "comments": [], - "createdByType": "User", - "status": "Executing", - "createdAt": "2026-05-15T23:59:27.4912978Z", - "lastModifiedAt": "2026-05-15T23:59:33.1426783Z", - "executionHistory": [ - { - "createdAt": "2026-05-15T23:59:27.4912978Z", - "action": "taskCreated", - "createdBy": "Sanitized", - "createdByType": "User", - "summary": "Task created: task-for-start-test" - }, - { - "createdAt": "2026-05-15T23:59:30.471688Z", - "action": "taskStartInitiated", - "createdBy": "Sanitized", - "createdByType": "User", - "summary": "Task start requested by User" - }, - { - "createdAt": "2026-05-15T23:59:32.0006435Z", - "action": "agentStarted", - "createdBy": "Sanitized", - "createdByType": "Application", - "summary": "Task execution initiated", - "responseMessageId": "conversations/task-4975886658412173146-00000000-0000-0000-0000-000000000000/responses/resp_b79ac50b376944adafe6621b51451d40" - }, - { - "createdAt": "2026-05-15T23:59:32.0930667Z", - "action": "taskUpdated", - "createdBy": "Sanitized", - "createdByType": "Application", - "summary": "Task updated: status", - "additionalDetails": { - "statusFrom": "New", - "statusTo": "Executing" - } - } - ], - "taskCollectionId": "5215043646661345540", - "investigationId": "/projects/test-project/investigations/test-invst", - "taskResult": { - "text": "", - "storageAssetIds": [], - "citations": [] - }, - "storageAssetIds": [], - "lastModifiedByType": "User", - "lastModifiedBy": "Sanitized", - "createdBy": "Sanitized", - "foundryConversationId": "conv_00000000000000000000000000000000000000000000000000" - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks/4975886658412173146?api-version=2026-02-01-preview", - "RequestMethod": "DELETE", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "Content-Length": "0", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 204, - "ResponseHeaders": { - "Connection": "keep-alive", - "Date": "Fri, 15 May 2026 23:59:35 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": null - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_update.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_update.json deleted file mode 100644 index a43bbfbef257..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tasks.pyTestTaskstest_update.json +++ /dev/null @@ -1,176 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "230", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "title": "task-for-update-test", - "priority": "High", - "description": "Test task for Python SDK", - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "investigationId": "/projects/test-project/investigations/test-invst" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:59:06 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "5299108449331521209", - "title": "task-for-update-test", - "priority": "High", - "description": "Test task for Python SDK", - "validationRequirements": [], - "parentId": null, - "dependsOn": [], - "relatedTo": [], - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "comments": [], - "createdByType": "User", - "status": "New", - "createdAt": "2026-05-15T23:59:06.406667Z", - "lastModifiedAt": "2026-05-15T23:59:06.406667Z", - "executionHistory": [ - { - "createdAt": "2026-05-15T23:59:06.406667Z", - "action": "taskCreated", - "createdBy": "Sanitized", - "createdByType": "User", - "summary": "Task created: task-for-update-test" - } - ], - "taskCollectionId": "5215043646661345540", - "investigationId": "/projects/test-project/investigations/test-invst", - "taskResult": { - "text": "", - "storageAssetIds": [], - "citations": [] - }, - "storageAssetIds": [], - "lastModifiedByType": "User", - "lastModifiedBy": "Sanitized", - "createdBy": "Sanitized", - "foundryConversationId": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks/5299108449331521209?api-version=2026-02-01-preview", - "RequestMethod": "PATCH", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "82", - "Content-Type": "application/merge-patch+json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "title": "Updated sdk task title", - "description": "Updated sdk task description" - }, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:59:08 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "name": "5299108449331521209", - "title": "Updated sdk task title", - "priority": "High", - "description": "Updated sdk task description", - "validationRequirements": [], - "parentId": null, - "dependsOn": [], - "relatedTo": [], - "assignedTo": { - "id": "Sanitized", - "type": "Application" - }, - "comments": [], - "createdByType": "User", - "status": "New", - "createdAt": "2026-05-15T23:59:06.406667Z", - "lastModifiedAt": "2026-05-15T23:59:08.4057078Z", - "executionHistory": [ - { - "createdAt": "2026-05-15T23:59:06.406667Z", - "action": "taskCreated", - "createdBy": "Sanitized", - "createdByType": "User", - "summary": "Task created: task-for-update-test" - }, - { - "createdAt": "2026-05-15T23:59:08.4057069Z", - "action": "taskUpdated", - "createdBy": "Sanitized", - "createdByType": "Application", - "summary": "Task updated: title, description", - "additionalDetails": { - "titleFrom": "task-for-update-test", - "titleTo": "Updated sdk task title", - "descriptionChanged": true - } - } - ], - "taskCollectionId": "5215043646661345540", - "investigationId": "/projects/test-project/investigations/test-invst", - "taskResult": { - "text": "", - "storageAssetIds": [], - "citations": [] - }, - "storageAssetIds": [], - "lastModifiedByType": "User", - "lastModifiedBy": "Sanitized", - "createdBy": "Sanitized", - "foundryConversationId": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/projects/test-project/investigations/test-invst/tasks/5299108449331521209?api-version=2026-02-01-preview", - "RequestMethod": "DELETE", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "Content-Length": "0", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 204, - "ResponseHeaders": { - "Connection": "keep-alive", - "Date": "Fri, 15 May 2026 23:59:10 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": null - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tools.pyTestToolsOperationstest_begin_run.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_tools.pyTestToolsOperationstest_begin_run.json deleted file mode 100644 index 4bb9e66018b5..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tools.pyTestToolsOperationstest_begin_run.json +++ /dev/null @@ -1,159 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project:run?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "368", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "command": "echo \"hello world\"", - "nodePoolIds": [ - "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1" - ], - "toolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/tools/testtool" - }, - "StatusCode": 202, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Fri, 15 May 2026 23:59:55 GMT", - "Location": "", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "operation-location": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project/operations/b7dff497787743fc898ce314e53590ac", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "NotStarted", - "error": null, - "result": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project/operations/b7dff497787743fc898ce314e53590ac", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Sat, 16 May 2026 00:00:00 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "NotStarted", - "error": null, - "result": { - "status": "TaskAccepted", - "runtimeDetails": "Tool run has been requested", - "createdAt": "2026-05-15T23:59:55.5889526Z", - "completedAt": null, - "toolReport": { - "percentageComplete": 0, - "logs": "", - "statusInformation": null - }, - "outputData": [], - "debugInfo": "" - } - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project/operations/b7dff497787743fc898ce314e53590ac", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Sat, 16 May 2026 00:00:33 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "Succeeded", - "error": null, - "result": { - "status": "TaskAccepted", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-15T23:59:55.5889526Z", - "completedAt": "2026-05-16T00:00:08.2547848Z", - "toolReport": { - "percentageComplete": 0, - "logs": "worker:\nhello world\n", - "statusInformation": null - }, - "outputData": [], - "debugInfo": "" - } - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project/operations/b7dff497787743fc898ce314e53590ac", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Sat, 16 May 2026 00:00:35 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "Succeeded", - "error": null, - "result": { - "status": "TaskAccepted", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-15T23:59:55.5889526Z", - "completedAt": "2026-05-16T00:00:08.2547848Z", - "toolReport": { - "percentageComplete": 0, - "logs": "worker:\nhello world\n", - "statusInformation": null - }, - "outputData": [], - "debugInfo": "" - } - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tools.pyTestToolsOperationstest_cancel_run.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_tools.pyTestToolsOperationstest_cancel_run.json deleted file mode 100644 index 12d05449bbe2..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tools.pyTestToolsOperationstest_cancel_run.json +++ /dev/null @@ -1,103 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project:run?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "381", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "command": "echo \"cancel test\" && sleep 300", - "nodePoolIds": [ - "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1" - ], - "toolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/tools/testtool" - }, - "StatusCode": 202, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Sat, 16 May 2026 00:02:02 GMT", - "Location": "", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "operation-location": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project/operations/f528d4eebb5f47d98c62725072da0ef0", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "NotStarted", - "error": null, - "result": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project/operations/f528d4eebb5f47d98c62725072da0ef0", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Sat, 16 May 2026 00:02:03 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "NotStarted", - "error": null, - "result": { - "status": "TaskAccepted", - "runtimeDetails": "Tool run has been requested", - "createdAt": "2026-05-16T00:02:02.2970928Z", - "completedAt": null, - "toolReport": { - "percentageComplete": 0, - "logs": "", - "statusInformation": null - }, - "outputData": [], - "debugInfo": "" - } - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project/operations/f528d4eebb5f47d98c62725072da0ef0:cancel?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "Content-Length": "0", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 202, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Length": "0", - "Date": "Sat, 16 May 2026 00:02:04 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": null - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tools.pyTestToolsOperationstest_get_compute_usage.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_tools.pyTestToolsOperationstest_get_compute_usage.json deleted file mode 100644 index 276db1412b66..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tools.pyTestToolsOperationstest_get_compute_usage.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project/computeUsage?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Sat, 16 May 2026 00:02:11 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "supercomputers": { - "test-sc": { - "activeJobs": 0, - "pendingJobs": 0, - "nodepools": { - "nodepool1": { - "reservedCPUs": "0", - "allocatableCPUs": "9", - "reservedMemory": "0", - "allocatableMemory": "39Gi", - "reservedGPUs": "0", - "allocatableGPUs": "0" - } - } - } - } - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tools.pyTestToolsOperationstest_get_operations.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_tools.pyTestToolsOperationstest_get_operations.json deleted file mode 100644 index 6506f73a8c04..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tools.pyTestToolsOperationstest_get_operations.json +++ /dev/null @@ -1,688 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project/operations?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Sat, 16 May 2026 00:02:07 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "value": [ - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Canceled", - "runtimeDetails": "Tool has been cancelled", - "createdAt": "2026-05-02T22:00:53.2622931Z", - "completedAt": "2026-05-02T22:01:07.0717576Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-02T22:00:59.1242916Z", - "completedAt": "2026-05-02T22:03:18.644044Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Canceled", - "runtimeDetails": "Tool has been cancelled", - "createdAt": "2026-05-02T22:01:02.4644463Z", - "completedAt": "2026-05-02T22:01:06.9867081Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-02T22:01:08.2095532Z", - "completedAt": "2026-05-02T22:03:24.0901194Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T03:06:30.0710615Z", - "completedAt": "2026-05-03T03:08:59.1951807Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T03:06:32.1647543Z", - "completedAt": "2026-05-03T03:09:04.7010371Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T03:06:32.9684144Z", - "completedAt": "2026-05-03T03:09:12.450529Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T03:06:36.9150228Z", - "completedAt": "2026-05-03T03:09:04.6739501Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T04:26:52.3462766Z", - "completedAt": "2026-05-03T04:29:21.5049591Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T04:26:52.7196423Z", - "completedAt": "2026-05-03T04:29:23.8678699Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T04:26:55.2699636Z", - "completedAt": "2026-05-03T04:29:22.0303755Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T04:26:58.9883031Z", - "completedAt": "2026-05-03T04:29:21.53672Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T04:42:40.2814506Z", - "completedAt": "2026-05-03T04:42:52.6116499Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T04:42:41.4020928Z", - "completedAt": "2026-05-03T04:43:04.6386303Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T04:42:43.4693781Z", - "completedAt": "2026-05-03T04:43:04.5784206Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T04:42:45.5390494Z", - "completedAt": "2026-05-03T04:42:52.6059639Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T04:54:06.7749879Z", - "completedAt": "2026-05-03T04:56:40.5304853Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T04:54:09.5530909Z", - "completedAt": "2026-05-03T04:56:40.2436027Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T04:54:09.7802256Z", - "completedAt": "2026-05-03T04:56:40.532075Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T04:54:13.5496637Z", - "completedAt": "2026-05-03T04:56:47.836046Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T20:04:02.8800306Z", - "completedAt": "2026-05-03T20:04:19.6995105Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T20:04:07.0267098Z", - "completedAt": "2026-05-03T20:04:19.7122902Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T20:04:11.3523197Z", - "completedAt": "2026-05-03T20:04:31.5338918Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T20:04:12.1844484Z", - "completedAt": "2026-05-03T20:04:19.8168414Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T23:09:24.6426229Z", - "completedAt": "2026-05-03T23:09:43.5404439Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T23:09:26.1670139Z", - "completedAt": "2026-05-03T23:09:42.4193064Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T23:09:27.9890273Z", - "completedAt": "2026-05-03T23:10:03.7515017Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T23:09:31.3042001Z", - "completedAt": "2026-05-03T23:09:48.8352436Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T23:10:11.1186417Z", - "completedAt": "2026-05-03T23:10:20.9010913Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T23:10:13.4188277Z", - "completedAt": "2026-05-03T23:10:24.4665679Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T23:10:14.9465882Z", - "completedAt": "2026-05-03T23:10:22.9372429Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-03T23:10:19.2264216Z", - "completedAt": "2026-05-03T23:10:25.3620365Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-04T00:30:08.0995441Z", - "completedAt": "2026-05-04T00:30:32.0663762Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-04T00:33:03.0814634Z", - "completedAt": "2026-05-04T00:33:38.8125463Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-04T00:35:00.3515041Z", - "completedAt": "2026-05-04T00:35:12.5846217Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-04T00:38:20.8389985Z", - "completedAt": "2026-05-04T00:38:40.7994568Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-04T00:46:58.4894007Z", - "completedAt": "2026-05-04T00:47:11.8175525Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-09T06:02:12.0657334Z", - "completedAt": "2026-05-09T06:02:26.0311951Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Canceled", - "runtimeDetails": "Tool has been cancelled", - "createdAt": "2026-05-09T06:03:16.6948297Z", - "completedAt": "2026-05-09T06:03:31.0015262Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-09T06:07:15.3140877Z", - "completedAt": "2026-05-09T06:07:24.1165252Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Canceled", - "runtimeDetails": "Tool has been cancelled", - "createdAt": "2026-05-09T06:08:04.5768427Z", - "completedAt": "2026-05-09T06:08:07.959556Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-09T20:43:56.9589268Z", - "completedAt": "2026-05-09T20:44:32.0079126Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-09T20:44:41.6537166Z", - "completedAt": "2026-05-09T20:44:53.8345219Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-09T20:45:26.223824Z", - "completedAt": "2026-05-09T20:45:52.1507257Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Canceled", - "runtimeDetails": "Tool has been cancelled", - "createdAt": "2026-05-09T20:46:08.8548549Z", - "completedAt": "2026-05-09T20:46:14.3143804Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Canceled", - "runtimeDetails": "Tool has been cancelled", - "createdAt": "2026-05-12T01:02:57.6181697Z", - "completedAt": "2026-05-12T01:03:09.1129164Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-12T01:03:14.0345128Z", - "completedAt": "2026-05-12T01:03:30.2765544Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-12T01:03:37.8913789Z", - "completedAt": "2026-05-12T01:04:09.3058988Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-12T01:04:18.3619174Z", - "completedAt": "2026-05-12T01:04:38.7500103Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Canceled", - "runtimeDetails": "Tool has been cancelled", - "createdAt": "2026-05-12T01:04:22.97746Z", - "completedAt": "2026-05-12T01:04:53.3418186Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-12T01:04:35.7447959Z", - "completedAt": "2026-05-12T01:04:41.4068895Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-12T01:04:48.5292835Z", - "completedAt": "2026-05-12T01:04:58.5238477Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-12T01:05:07.4563203Z", - "completedAt": "2026-05-12T01:05:41.1855385Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-13T23:26:15.7573036Z", - "completedAt": "2026-05-13T23:26:28.9088223Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-13T23:26:20.2860148Z", - "completedAt": "2026-05-13T23:26:28.7781216Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-13T23:26:32.3507012Z", - "completedAt": "2026-05-13T23:26:38.0793556Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-13T23:26:40.0909628Z", - "completedAt": "2026-05-13T23:27:02.0811856Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-14T22:17:47.5462244Z", - "completedAt": "2026-05-14T22:17:57.2410628Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-14T22:17:51.8309597Z", - "completedAt": "2026-05-14T22:17:57.7490648Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-14T22:18:03.4910458Z", - "completedAt": "2026-05-14T22:18:10.1651858Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-14T22:18:12.46316Z", - "completedAt": "2026-05-14T22:18:34.5651653Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-15T00:25:03.1396426Z", - "completedAt": "2026-05-15T00:25:21.3700099Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-15T00:25:08.0626368Z", - "completedAt": "2026-05-15T00:25:21.4188945Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-15T00:25:21.3519939Z", - "completedAt": "2026-05-15T00:25:25.4855292Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-15T00:25:29.0592847Z", - "completedAt": "2026-05-15T00:25:35.0163688Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-15T01:15:20.9364085Z", - "completedAt": "2026-05-15T01:15:45.8047816Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-15T01:15:25.9555074Z", - "completedAt": "2026-05-15T01:15:34.7330832Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-15T01:15:38.9774843Z", - "completedAt": "2026-05-15T01:15:47.215454Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-15T01:15:46.9166383Z", - "completedAt": "2026-05-15T01:16:09.0228Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-15T23:59:55.5889526Z", - "completedAt": "2026-05-16T00:00:08.2547848Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-16T00:00:38.9681505Z", - "completedAt": "2026-05-16T00:01:06.8839235Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "Succeeded", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-16T00:01:21.6105544Z", - "completedAt": "2026-05-16T00:01:49.2952991Z", - "createdBy": null - }, - { - "nodepoolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1", - "id": "Sanitized", - "status": "NotStarted", - "runtimeDetails": "Tool run has been requested", - "createdAt": "2026-05-16T00:02:02.2970928Z", - "completedAt": null, - "createdBy": "Sanitized" - } - ], - "nextLink": null - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tools.pyTestToolsOperationstest_get_run_status.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_tools.pyTestToolsOperationstest_get_run_status.json deleted file mode 100644 index 1957c5e18d08..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tools.pyTestToolsOperationstest_get_run_status.json +++ /dev/null @@ -1,199 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project:run?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "368", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "command": "echo \"status test\"", - "nodePoolIds": [ - "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1" - ], - "toolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/tools/testtool" - }, - "StatusCode": 202, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Sat, 16 May 2026 00:00:39 GMT", - "Location": "", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "operation-location": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project/operations/7bb20de095b94fbda961083addef6089", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "NotStarted", - "error": null, - "result": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project/operations/7bb20de095b94fbda961083addef6089", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Sat, 16 May 2026 00:00:41 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "NotStarted", - "error": null, - "result": { - "status": "TaskAccepted", - "runtimeDetails": "Tool run has been requested", - "createdAt": "2026-05-16T00:00:38.9681505Z", - "completedAt": null, - "toolReport": { - "percentageComplete": 0, - "logs": "", - "statusInformation": null - }, - "outputData": [], - "debugInfo": "" - } - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project/operations/7bb20de095b94fbda961083addef6089", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Sat, 16 May 2026 00:01:13 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "Succeeded", - "error": null, - "result": { - "status": "TaskAccepted", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-16T00:00:38.9681505Z", - "completedAt": "2026-05-16T00:01:06.8839235Z", - "toolReport": { - "percentageComplete": 0, - "logs": "worker:\nstatus test\n", - "statusInformation": null - }, - "outputData": [], - "debugInfo": "" - } - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project/operations/7bb20de095b94fbda961083addef6089", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Sat, 16 May 2026 00:01:15 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "Succeeded", - "error": null, - "result": { - "status": "TaskAccepted", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-16T00:00:38.9681505Z", - "completedAt": "2026-05-16T00:01:06.8839235Z", - "toolReport": { - "percentageComplete": 0, - "logs": "worker:\nstatus test\n", - "statusInformation": null - }, - "outputData": [], - "debugInfo": "" - } - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project/operations/7bb20de095b94fbda961083addef6089?api-version=2026-02-01-preview", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Sat, 16 May 2026 00:01:17 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "Succeeded", - "error": null, - "result": { - "status": "TaskAccepted", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-16T00:00:38.9681505Z", - "completedAt": "2026-05-16T00:01:06.8839235Z", - "createdBy": null, - "toolReport": { - "percentageComplete": 0, - "logs": "worker:\nstatus test\n", - "statusInformation": null - }, - "outputData": [], - "debugInfo": "" - } - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tools.pyTestToolsOperationstest_get_run_status_with_log_count.json b/sdk/discovery/azure-ai-discovery/tests/recordings/test_tools.pyTestToolsOperationstest_get_run_status_with_log_count.json deleted file mode 100644 index 3c4c89822139..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/recordings/test_tools.pyTestToolsOperationstest_get_run_status_with_log_count.json +++ /dev/null @@ -1,199 +0,0 @@ -{ - "Entries": [ - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project:run?api-version=2026-02-01-preview", - "RequestMethod": "POST", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "Content-Length": "371", - "Content-Type": "application/json", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": { - "command": "echo \"log count test\"", - "nodePoolIds": [ - "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/supercomputers/test-sc/nodePools/nodepool1" - ], - "toolId": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/test-rg/providers/Microsoft.Discovery/tools/testtool" - }, - "StatusCode": 202, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Sat, 16 May 2026 00:01:21 GMT", - "Location": "", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "operation-location": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project/operations/9f058980420448d78fc3d3f996d13ecb", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "NotStarted", - "error": null, - "result": null - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project/operations/9f058980420448d78fc3d3f996d13ecb", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Sat, 16 May 2026 00:01:23 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "NotStarted", - "error": null, - "result": { - "status": "TaskAccepted", - "runtimeDetails": "Tool run has been requested", - "createdAt": "2026-05-16T00:01:21.6105544Z", - "completedAt": null, - "toolReport": { - "percentageComplete": 0, - "logs": "", - "statusInformation": null - }, - "outputData": [], - "debugInfo": "" - } - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project/operations/9f058980420448d78fc3d3f996d13ecb", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Sat, 16 May 2026 00:01:54 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "Succeeded", - "error": null, - "result": { - "status": "TaskAccepted", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-16T00:01:21.6105544Z", - "completedAt": "2026-05-16T00:01:49.2952991Z", - "toolReport": { - "percentageComplete": 0, - "logs": "worker:\nlog count test\n", - "statusInformation": null - }, - "outputData": [], - "debugInfo": "" - } - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project/operations/9f058980420448d78fc3d3f996d13ecb", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "*/*", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Sat, 16 May 2026 00:01:56 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "Succeeded", - "error": null, - "result": { - "status": "TaskAccepted", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-16T00:01:21.6105544Z", - "completedAt": "2026-05-16T00:01:49.2952991Z", - "toolReport": { - "percentageComplete": 0, - "logs": "worker:\nlog count test\n", - "statusInformation": null - }, - "outputData": [], - "debugInfo": "" - } - } - }, - { - "RequestUri": "https://test-workspace.workspace.discovery.azure.com/tools/projects/test-project/operations/9f058980420448d78fc3d3f996d13ecb?api-version=2026-02-01-preview&logCount=10", - "RequestMethod": "GET", - "RequestHeaders": { - "Accept": "application/json", - "Connection": "keep-alive", - "User-Agent": "azsdk-python-ai-discovery/1.0.0b1 Python/3.12.3 (Linux-6.6.87.2-microsoft-standard-WSL2-x86_64-with-glibc2.39)" - }, - "RequestBody": null, - "StatusCode": 200, - "ResponseHeaders": { - "Connection": "keep-alive", - "Content-Type": "application/json; charset=utf-8", - "Date": "Sat, 16 May 2026 00:01:58 GMT", - "mise-correlation-id": "00000000-0000-0000-0000-000000000000", - "Server": "Kestrel", - "Transfer-Encoding": "chunked", - "x-ms-build-version": "1", - "x-ms-correlation-request-id": "00000000-0000-0000-0000-000000000000" - }, - "ResponseBody": { - "id": "Sanitized", - "status": "Succeeded", - "error": null, - "result": { - "status": "TaskAccepted", - "runtimeDetails": "Tool has completed successfully", - "createdAt": "2026-05-16T00:01:21.6105544Z", - "completedAt": "2026-05-16T00:01:49.2952991Z", - "createdBy": null, - "toolReport": { - "percentageComplete": 0, - "logs": "worker:\nlog count test\n", - "statusInformation": null - }, - "outputData": [], - "debugInfo": "" - } - } - } - ], - "Variables": {} -} diff --git a/sdk/discovery/azure-ai-discovery/tests/test_conversations.py b/sdk/discovery/azure-ai-discovery/tests/test_conversations.py index b7263befb532..96cbda6abe98 100644 --- a/sdk/discovery/azure-ai-discovery/tests/test_conversations.py +++ b/sdk/discovery/azure-ai-discovery/tests/test_conversations.py @@ -8,10 +8,11 @@ - get, create, update, delete - list (Paged) """ + import pytest from devtools_testutils import recorded_by_proxy from azure.core.exceptions import HttpResponseError -from azure.ai.discovery._workspace.azure.ai.discovery.models import Conversation +from azure.ai.discovery.models import Conversation from .testcase import DiscoveryWorkspaceTestCase from .constants import investigation_path @@ -42,13 +43,16 @@ def test_create(self): @recorded_by_proxy def test_list(self): - """Test listing conversations.""" + """Test listing conversations. + + ``conversations.list`` returns a ``PagedConversation`` envelope + """ found_test_conversation_id = False client = self.create_workspace_client() - conversations = list(client.conversations.list(project_name=self.project_name)) - assert isinstance(conversations, list) - assert len(conversations) > 0 - for conv in conversations: + page = client.conversations.list(project_name=self.project_name) + assert page.value is not None + assert len(page.value) > 0 + for conv in page.value: assert conv.project_name == self.project_name assert conv.created_at is not None assert conv.investigation_name is not None @@ -85,10 +89,10 @@ def test_get(self, **kwargs): assert conversation.created_at is not None @recorded_by_proxy - def test_update(self): + def test_stable_update(self): """Test updating a conversation (PATCH).""" client = self.create_workspace_client() - updated = client.conversations.update( + updated = client.conversations.stable_update( conversation_name=TestConversations.test_conversation_id, resource=Conversation(display_name="Updated conversation"), ) diff --git a/sdk/discovery/azure-ai-discovery/tests/test_conversations_async.py b/sdk/discovery/azure-ai-discovery/tests/test_conversations_async.py new file mode 100644 index 000000000000..3279ff52739c --- /dev/null +++ b/sdk/discovery/azure-ai-discovery/tests/test_conversations_async.py @@ -0,0 +1,102 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Async tests for Conversations operations. + +Mirrors test_conversations.py against the async ``WorkspaceClient`` from +``azure.ai.discovery.aio``. +""" + +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from azure.ai.discovery.models import Conversation +from .testcase import DiscoveryWorkspaceTestCase +from .constants import investigation_path + + +class TestConversationsAsync(DiscoveryWorkspaceTestCase): + """Async tests for ConversationsOperations.""" + + test_conversation_id = "00000000-0000-0000-0000-000000000000" + + @recorded_by_proxy_async + async def test_create(self): + client = self.create_async_workspace_client() + async with client: + investigation_path_str = investigation_path(self.project_name, self.investigation_name) + conversation = await client.conversations.create( + body=Conversation( + display_name="Test conversation", + project_name=self.project_name, + investigation_name=investigation_path_str, + ), + ) + assert conversation is not None + assert conversation.project_name == self.project_name + assert conversation.name is not None + assert conversation.created_at is not None + TestConversationsAsync.test_conversation_id = conversation.name + + @recorded_by_proxy_async + async def test_list(self): + """``conversations.list`` returns a ``PagedConversation`` envelope. + Iterate ``.value``.""" + found_test_conversation_id = False + client = self.create_async_workspace_client() + async with client: + page = await client.conversations.list(project_name=self.project_name) + assert page.value is not None + assert len(page.value) > 0 + for conv in page.value: + assert conv.project_name == self.project_name + assert conv.created_at is not None + assert conv.investigation_name is not None + if conv.name == TestConversationsAsync.test_conversation_id: + found_test_conversation_id = True + assert found_test_conversation_id + + @recorded_by_proxy_async + async def test_get(self, **kwargs): + variables = kwargs.pop("variables", {}) + client = self.create_async_workspace_client() + async with client: + if "conversation_name" not in variables: + investigation_path_str = investigation_path(self.project_name, self.investigation_name) + created = await client.conversations.create( + body=Conversation( + display_name="Conversation for get test", + project_name=self.project_name, + investigation_name=investigation_path_str, + ), + ) + variables["conversation_name"] = created.name + + conversation = await client.conversations.get( + conversation_name=variables["conversation_name"], + ) + assert conversation is not None + assert conversation.name is not None + assert conversation.project_name == self.project_name + assert conversation.created_at is not None + + @recorded_by_proxy_async + async def test_stable_update(self): + client = self.create_async_workspace_client() + async with client: + updated = await client.conversations.stable_update( + conversation_name=TestConversationsAsync.test_conversation_id, + resource=Conversation(display_name="Updated conversation"), + ) + assert updated is not None + assert updated.display_name == "Updated conversation" + assert updated.last_modified_at is not None + + @recorded_by_proxy_async + async def test_delete(self): + client = self.create_async_workspace_client() + async with client: + status = await client.conversations.delete( + conversation_name=TestConversationsAsync.test_conversation_id, + ) + assert status is None diff --git a/sdk/discovery/azure-ai-discovery/tests/test_investigations.py b/sdk/discovery/azure-ai-discovery/tests/test_investigations.py index a5a99660f223..3770df394a7f 100644 --- a/sdk/discovery/azure-ai-discovery/tests/test_investigations.py +++ b/sdk/discovery/azure-ai-discovery/tests/test_investigations.py @@ -11,10 +11,11 @@ - list (Paged) - get_discovery_engine, get_discovery_engine_memory, update_discovery_engine """ + import pytest from devtools_testutils import recorded_by_proxy from azure.core.exceptions import HttpResponseError -from azure.ai.discovery._workspace.azure.ai.discovery.models import ( +from azure.ai.discovery.models import ( Investigation, DiscoveryEngine, DiscoveryEngineUpdate, @@ -40,11 +41,16 @@ def test_create_or_replace_new(self): @recorded_by_proxy def test_list(self): + """Test listing investigations. + + ``investigations.list`` returns a ``PagedInvestigation`` + envelope. Iterate ``.value``. + """ client = self.create_workspace_client() - investigations = list(client.investigations.list(project_name=self.project_name)) - assert isinstance(investigations, list) - assert len(investigations) > 0 - for inv in investigations: + page = client.investigations.list(project_name=self.project_name) + assert page.value is not None + assert len(page.value) > 0 + for inv in page.value: assert inv.project_name == self.project_name assert inv.status is not None assert inv.created_at is not None @@ -65,12 +71,18 @@ def test_get(self): @recorded_by_proxy def test_update_discovery_engine(self): - """Test updating the discovery engine for an investigation.""" + """Test updating the discovery engine for an investigation. + + Note: ``DiscoveryEngineUpdate`` does not accept ``discovery_engine_status`` + (that field is on ``DiscoveryEngine`` itself and is controlled via the + dedicated start/stop action operations). The update payload only allows + ``system_prompt`` and ``configuration``. + """ client = self.create_workspace_client() engine = client.investigations.update_discovery_engine( project_name=self.project_name, investigation_name=self.investigation_name, - body=DiscoveryEngineUpdate(discovery_engine_status="Active"), + body=DiscoveryEngineUpdate(system_prompt="Updated system prompt for test"), ) assert engine is not None assert hasattr(engine, "discovery_engine_status") @@ -91,7 +103,7 @@ def test_start_discovery_engine(self): """Test starting the discovery engine for an investigation.""" client = self.create_workspace_client() # Discovery Engine requires at least one task in the investigation before starting - from azure.ai.discovery._workspace.azure.ai.discovery.models import Task + from azure.ai.discovery.models import Task test_task = client.tasks.create( project_name=self.project_name, @@ -143,10 +155,10 @@ def test_create_or_replace_update(self): assert investigation.display_name == "updated-new-test" @recorded_by_proxy - def test_create_or_update(self): + def test_update(self): """Test creating or updating (PATCH) an investigation.""" client = self.create_workspace_client() - investigation = client.investigations.create_or_update( + investigation = client.investigations.update( project_name=self.project_name, investigation_name=self.investigation_name, resource=Investigation(description="Updated description", display_name="updated-test"), diff --git a/sdk/discovery/azure-ai-discovery/tests/test_investigations_async.py b/sdk/discovery/azure-ai-discovery/tests/test_investigations_async.py new file mode 100644 index 000000000000..25af6502740c --- /dev/null +++ b/sdk/discovery/azure-ai-discovery/tests/test_investigations_async.py @@ -0,0 +1,206 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Async tests for Investigations operations. + +Mirrors test_investigations.py against the async ``WorkspaceClient`` from +``azure.ai.discovery.aio``. +""" + +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from azure.ai.discovery.models import ( + Investigation, + DiscoveryEngineUpdate, + Task, +) +from .testcase import DiscoveryWorkspaceTestCase + + +class TestInvestigationsAsync(DiscoveryWorkspaceTestCase): + """Async tests for InvestigationsOperations.""" + + @recorded_by_proxy_async + async def test_create_or_replace_new(self): + client = self.create_async_workspace_client() + async with client: + investigation = await client.investigations.create_or_replace( + project_name=self.project_name, + investigation_name=self.investigation_name, + resource=Investigation(description="New investigation", display_name="New Test"), + ) + assert investigation is not None + assert investigation.description == "New investigation" + assert investigation.display_name == "New Test" + + @recorded_by_proxy_async + async def test_list(self): + """``investigations.list`` returns ``PagedInvestigation``; iterate ``.value``.""" + client = self.create_async_workspace_client() + async with client: + page = await client.investigations.list(project_name=self.project_name) + assert page.value is not None + assert len(page.value) > 0 + for inv in page.value: + assert inv.project_name == self.project_name + assert inv.status is not None + assert inv.created_at is not None + + @recorded_by_proxy_async + async def test_get(self): + client = self.create_async_workspace_client() + async with client: + investigation = await client.investigations.get( + project_name=self.project_name, + investigation_name=self.investigation_name, + ) + assert investigation is not None + assert investigation.project_name == self.project_name + assert investigation.status is not None + assert investigation.created_at is not None + assert investigation.last_modified_at is not None + + @recorded_by_proxy_async + async def test_update_discovery_engine(self): + # See sync test for explanation of why we use ``system_prompt`` and not + # ``discovery_engine_status`` (the latter is not a field on the Update model). + client = self.create_async_workspace_client() + async with client: + engine = await client.investigations.update_discovery_engine( + project_name=self.project_name, + investigation_name=self.investigation_name, + body=DiscoveryEngineUpdate(system_prompt="Updated system prompt for test (async)"), + ) + assert engine is not None + assert hasattr(engine, "discovery_engine_status") + + @recorded_by_proxy_async + async def test_get_discovery_engine(self): + client = self.create_async_workspace_client() + async with client: + engine = await client.investigations.get_discovery_engine( + project_name=self.project_name, + investigation_name=self.investigation_name, + ) + assert engine is not None + assert hasattr(engine, "discovery_engine_status") + + @recorded_by_proxy_async + async def test_start_discovery_engine(self): + client = self.create_async_workspace_client() + async with client: + test_task = await client.tasks.create( + project_name=self.project_name, + investigation_name=self.investigation_name, + body=Task(title="test-task-async", description="Task for engine start test (async)"), + ) + engine = await client.investigations.start_discovery_engine( + project_name=self.project_name, + investigation_name=self.investigation_name, + ) + await client.tasks.delete( + project_name=self.project_name, + investigation_name=self.investigation_name, + task_name=test_task.name, + ) + assert engine is not None + assert hasattr(engine, "discovery_engine_status") + + @recorded_by_proxy_async + async def test_get_discovery_engine_memory(self): + client = self.create_async_workspace_client() + async with client: + memory = await client.investigations.get_discovery_engine_memory( + project_name=self.project_name, + investigation_name=self.investigation_name, + ) + assert memory is not None + + @recorded_by_proxy_async + async def test_stop_discovery_engine(self): + client = self.create_async_workspace_client() + async with client: + engine = await client.investigations.stop_discovery_engine( + project_name=self.project_name, + investigation_name=self.investigation_name, + ) + assert engine is not None + + @recorded_by_proxy_async + async def test_create_or_replace_update(self): + client = self.create_async_workspace_client() + async with client: + investigation = await client.investigations.create_or_replace( + project_name=self.project_name, + investigation_name=self.investigation_name, + resource=Investigation(description="Updated via replace", display_name="updated-new-test"), + ) + assert investigation is not None + assert investigation.description == "Updated via replace" + assert investigation.display_name == "updated-new-test" + + @recorded_by_proxy_async + async def test_update(self): + client = self.create_async_workspace_client() + async with client: + investigation = await client.investigations.update( + project_name=self.project_name, + investigation_name=self.investigation_name, + resource=Investigation(description="Updated description", display_name="updated-test"), + ) + assert investigation is not None + assert investigation.description == "Updated description" + + @recorded_by_proxy_async + async def test_get_operation_status(self): + """Start a delete LRO without waiting, extract op id, query status.""" + client = self.create_async_workspace_client() + async with client: + await client.investigations.create_or_replace( + project_name=self.project_name, + investigation_name="test-op-status-async", + resource=Investigation( + description="Sacrificial investigation for getOperationStatus test (async)", + display_name="Op Status Test Async", + ), + ) + + poller = await client.investigations.begin_delete( + project_name=self.project_name, + investigation_name="test-op-status-async", + polling=False, + ) + initial_response = poller._polling_method._initial_response + op_location = initial_response.http_response.headers.get("operation-location", "") + operation_id = op_location.split("/operations/")[-1].split("?")[0] + assert operation_id, "Could not extract operation_id from operation-location header" + + status = await client.investigations.get_operation_status( + project_name=self.project_name, + investigation_name="test-op-status-async", + operation_id=operation_id, + ) + assert status is not None + assert status["status"] is not None + + @recorded_by_proxy_async + async def test_begin_delete(self): + client = self.create_async_workspace_client() + async with client: + await client.investigations.create_or_replace( + project_name=self.project_name, + investigation_name="sdk-test-delete-async", + resource=Investigation( + description="Sacrificial investigation for delete test (async)", + display_name="Delete Status Test Async", + ), + ) + + poller = await client.investigations.begin_delete( + project_name=self.project_name, + investigation_name="sdk-test-delete-async", + ) + await poller.wait() + assert poller.done() + assert poller.status() == "Succeeded" diff --git a/sdk/discovery/azure-ai-discovery/tests/test_knowledge_base_versions.py b/sdk/discovery/azure-ai-discovery/tests/test_knowledge_base_versions.py deleted file mode 100644 index e36ba27025a1..000000000000 --- a/sdk/discovery/azure-ai-discovery/tests/test_knowledge_base_versions.py +++ /dev/null @@ -1,202 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Tests for Knowledge Base Versions operations. - -Covers all 9 methods on BookshelfClient.knowledge_base_versions: - - create_or_update - - get, get_latest_version - - list (Paged) - - get_operation_status - - begin_start_indexing, begin_cancel_indexing (LRO) - - delete, delete_latest_version -""" -import pytest -from devtools_testutils import recorded_by_proxy -from azure.core.exceptions import HttpResponseError -from azure.ai.discovery._bookshelf.azure.ai.discovery.models import KnowledgeBaseVersion, StorageAssetReference -from .testcase import DiscoveryBookshelfTestCase -from .constants import ( - KNOWLEDGE_BASE_NAME, - KNOWLEDGE_BASE_VERSION, - KNOWLEDGE_BASE_CREATE_NAME, - KNOWLEDGE_BASE_DESCRIPTION, - KNOWLEDGE_BASE_COPILOT_INSTRUCTION, - STORAGE_ASSET_ID, - USER_ASSIGNED_IDENTITY, - NODE_POOL_ID, - BOOKSHELF_NODE_POOL_ID, - PROJECT_NAME, - PROJECT_ARM_ID, -) - - -class TestKnowledgeBaseVersionsOperations(DiscoveryBookshelfTestCase): - """Tests for KnowledgeBaseVersionsOperations.""" - - @recorded_by_proxy - def test_create_or_update(self): - """Test creating or updating a knowledge base version.""" - client = self.create_bookshelf_client() - version = client.knowledge_base_versions.create_or_update( - knowledge_base_name=KNOWLEDGE_BASE_NAME, - version_name=KNOWLEDGE_BASE_VERSION, - resource=KnowledgeBaseVersion( - description=KNOWLEDGE_BASE_DESCRIPTION, - copilot_instruction=KNOWLEDGE_BASE_COPILOT_INSTRUCTION, - storage_asset_references=[ - StorageAssetReference( - id=STORAGE_ASSET_ID, - user_assigned_identity=USER_ASSIGNED_IDENTITY, - ) - ], - ), - ) - assert version is not None - assert version.description == KNOWLEDGE_BASE_DESCRIPTION - - @recorded_by_proxy - def test_list(self): - """Test listing knowledge base versions.""" - client = self.create_bookshelf_client() - versions = list(client.knowledge_base_versions.list(knowledge_base_name=KNOWLEDGE_BASE_NAME)) - assert isinstance(versions, list) - assert len(versions) > 0 - for v in versions: - assert v.version is not None - assert v.provisioning_state is not None - - @recorded_by_proxy - def test_get(self): - """Test getting a specific knowledge base version.""" - client = self.create_bookshelf_client() - version = client.knowledge_base_versions.get( - knowledge_base_name=KNOWLEDGE_BASE_NAME, - version_name=KNOWLEDGE_BASE_VERSION, - ) - assert version is not None - assert version.version == KNOWLEDGE_BASE_VERSION - assert version.bookshelf_name is not None - assert version.provisioning_state is not None - assert version.created_at is not None - assert version.description == KNOWLEDGE_BASE_DESCRIPTION - assert version.copilot_instruction is not None - assert isinstance(version.storage_asset_references, list) - - @recorded_by_proxy - def test_get_latest_version(self): - """Test getting the latest version of a knowledge base.""" - client = self.create_bookshelf_client() - latest = client.knowledge_base_versions.get_latest_version( - knowledge_base_name=KNOWLEDGE_BASE_NAME, - ) - assert latest is not None - assert latest.version is not None - assert latest.bookshelf_name is not None - assert latest.provisioning_state is not None - - @recorded_by_proxy - def test_get_operation_status(self): - """Test getting operation status for a knowledge base version. - - Starts an indexing LRO to obtain a real operation ID, checks its status, - then cancels the indexing to clean up. - """ - client = self.create_bookshelf_client() - - # Start indexing to get a real operation ID - poller = client.knowledge_base_versions.begin_start_indexing( - knowledge_base_name=KNOWLEDGE_BASE_NAME, - version_name=KNOWLEDGE_BASE_VERSION, - node_pool_id=NODE_POOL_ID, # BOOKSHELF_ - project_id=PROJECT_ARM_ID, - polling=False, - ) - # Extract operation ID from the Operation-Location header - initial_response = poller._polling_method._initial_response - op_location = initial_response.http_response.headers.get("operation-location", "") - operation_id = op_location.split("/operations/")[-1].split("?")[0] - assert operation_id, "Could not extract operation_id from Operation-Location header" - - # Act — check the operation status - status = client.knowledge_base_versions.get_operation_status( - knowledge_base_name=KNOWLEDGE_BASE_NAME, - version_name=KNOWLEDGE_BASE_VERSION, - operation_id=operation_id, - ) - assert status is not None - assert status["status"] is not None - - # Cleanup — cancel the indexing - client.knowledge_base_versions.begin_cancel_indexing( - knowledge_base_name=KNOWLEDGE_BASE_NAME, - version_name=KNOWLEDGE_BASE_VERSION, - node_pool_id=NODE_POOL_ID, # BOOKSHELF_ - polling=False, - ) - - @recorded_by_proxy - def test_begin_delete(self): - """Test deleting a specific knowledge base version (LRO). - - Creates a sacrificial version on the throwaway KB so the read - tests' fixtures (KNOWLEDGE_BASE_NAME / KNOWLEDGE_BASE_VERSION) - are never touched. - """ - client = self.create_bookshelf_client() - sacrificial_version = "delv1" - - # Create the version we will delete - client.knowledge_base_versions.create_or_update( - knowledge_base_name="sdktestdelv1", - version_name=sacrificial_version, - resource=KnowledgeBaseVersion( - description="Sacrificial KB version for delete test", - copilot_instruction=KNOWLEDGE_BASE_COPILOT_INSTRUCTION, - storage_asset_references=[ - StorageAssetReference( - id=STORAGE_ASSET_ID, - user_assigned_identity=USER_ASSIGNED_IDENTITY, - ) - ], - ), - ) - - poller = client.knowledge_base_versions.begin_delete( - knowledge_base_name="sdktestdelv1", - version_name=sacrificial_version, - ) - result = poller.result() - assert result is not None - - @recorded_by_proxy - def test_begin_delete_latest_version(self): - """Test deleting the latest version of a knowledge base (LRO). - - Creates a sacrificial KB version so this test owns the 'latest' it - deletes. - """ - client = self.create_bookshelf_client() - sacrificial_version = "delv2" - - client.knowledge_base_versions.create_or_update( - knowledge_base_name="sdktestdelv2", - version_name=sacrificial_version, - resource=KnowledgeBaseVersion( - description="Sacrificial KB version for delete-latest test", - copilot_instruction=KNOWLEDGE_BASE_COPILOT_INSTRUCTION, - storage_asset_references=[ - StorageAssetReference( - id=STORAGE_ASSET_ID, - user_assigned_identity=USER_ASSIGNED_IDENTITY, - ) - ], - ), - ) - - poller = client.knowledge_base_versions.begin_delete_latest_version( - knowledge_base_name="sdktestdelv2", - ) - result = poller.result() - assert result is not None diff --git a/sdk/discovery/azure-ai-discovery/tests/test_knowledge_bases.py b/sdk/discovery/azure-ai-discovery/tests/test_knowledge_bases.py index 3f5f6739070f..90b7adb7fe08 100644 --- a/sdk/discovery/azure-ai-discovery/tests/test_knowledge_bases.py +++ b/sdk/discovery/azure-ai-discovery/tests/test_knowledge_bases.py @@ -4,31 +4,333 @@ # ------------------------------------ """Tests for Knowledge Bases operations. -Covers 1 method on BookshelfClient.knowledge_bases: - - list (Paged) +Covers all 8 methods on BookshelfClient.knowledge_bases (GA surface): + - list (ItemPaged) + - get + - begin_create_or_update (LRO) + - begin_start_indexing, begin_cancel_indexing (LROs) + - begin_search (LRO) + - get_operation_status + - begin_delete (LRO) + +These tests exercise the redesigned ``KnowledgeBasesOperations`` group that +in GA replaces the beta ``KnowledgeBaseVersionsOperations``. Recordings will +be authored in Phase 4b against a live environment. """ + import pytest -from devtools_testutils import recorded_by_proxy -from azure.core.exceptions import HttpResponseError +import time +from devtools_testutils import recorded_by_proxy, is_live +from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError +from azure.core.polling.base_polling import LROBasePolling +from azure.ai.discovery.models import ( + KnowledgeBase, + SearchRequest, + StorageAssetReference, +) from .testcase import DiscoveryBookshelfTestCase +from .constants import ( + KNOWLEDGE_BASE_NAME, + KNOWLEDGE_BASE_DESCRIPTION, + KNOWLEDGE_BASE_COPILOT_INSTRUCTION, + STORAGE_ASSET_ID, + USER_ASSIGNED_IDENTITY, +) class TestKnowledgeBasesOperations(DiscoveryBookshelfTestCase): - """Tests for KnowledgeBasesOperations.""" + """Tests for KnowledgeBasesOperations (GA).""" + + @recorded_by_proxy + def test_begin_create_or_update(self): + """Test creating/updating a knowledge base via LRO. + + Ordered first in this class so it seeds the read-test fixture + (``KNOWLEDGE_BASE_NAME``) for subsequent tests, matching the pattern + used in the beta ``test_knowledge_base_versions.py`` file. + ``begin_create_or_update`` is upsert/PUT semantics, so re-running the + suite is idempotent. + """ + client = self.create_bookshelf_client() + poller = client.knowledge_bases.begin_create_or_update( + knowledge_base_name=KNOWLEDGE_BASE_NAME, + resource=KnowledgeBase( + description=KNOWLEDGE_BASE_DESCRIPTION, + copilot_instruction=KNOWLEDGE_BASE_COPILOT_INSTRUCTION, + storage_asset_references=[ + StorageAssetReference( + id=STORAGE_ASSET_ID, + user_assigned_identity=USER_ASSIGNED_IDENTITY, + ) + ], + ), + ) + final = poller.result() + assert final is not None + assert final.name == KNOWLEDGE_BASE_NAME @recorded_by_proxy def test_list(self): - """Test listing knowledge bases.""" + """Test listing knowledge bases via ItemPaged.""" client = self.create_bookshelf_client() knowledge_bases = list(client.knowledge_bases.list()) assert isinstance(knowledge_bases, list) assert len(knowledge_bases) > 0 for kb in knowledge_bases: - # Required read-visible fields per spec (BaseKnowledgeBase) + # Required read-visible fields per spec assert kb.name is not None assert len(kb.name) <= 24 # @maxLength(24) - assert kb.version is not None assert kb.bookshelf_name is not None - # Optional but useful sanity checks - assert kb.provisioning_state is not None # set after first reconcile + assert kb.provisioning_state is not None assert kb.status is not None # IndexingStatus + + @recorded_by_proxy + def test_get(self): + """Test getting a specific knowledge base by name.""" + client = self.create_bookshelf_client() + kb = client.knowledge_bases.get(knowledge_base_name=KNOWLEDGE_BASE_NAME) + assert kb is not None + assert kb.name == KNOWLEDGE_BASE_NAME + assert kb.bookshelf_name is not None + assert kb.provisioning_state is not None + assert isinstance(kb.storage_asset_references, list) + + @staticmethod + def _sleep(seconds): + """Sleep only when running live; a no-op during playback. + + The indexing/search tests poll long-running operations, so they sleep + between polls when live. During playback the recorded responses are + returned instantly, so skipping the sleeps keeps recorded test runs fast. + """ + if is_live(): + time.sleep(seconds) + + @staticmethod + def _start_indexing_operation_id(client): + """Start an indexing run (polling=False) and return its operation id. + + The service permits only one indexing run per KnowledgeBase at a time and + rejects a concurrent start with ``409 ConcurrencyConflict``. When a run + is already in progress we reuse it (its id is the KB's + ``lastIndexingRun``), so the indexing-dependent tests are robust no + matter how long a run takes on a given deployment. + """ + try: + poller = client.knowledge_bases.begin_start_indexing( + knowledge_base_name=KNOWLEDGE_BASE_NAME, + polling=False, + ) + except ResourceExistsError as exc: + if "ConcurrencyConflict" not in str(exc) and "already in progress" not in str(exc): + raise + kb = client.knowledge_bases.get(knowledge_base_name=KNOWLEDGE_BASE_NAME) + run = getattr(kb, "last_indexing_run", None) + run_id = getattr(run, "run_id", None) + assert run_id, "Indexing already in progress but no lastIndexingRun id is available" + return run_id + assert poller is not None + initial_response = poller._polling_method._initial_response + op_location = initial_response.http_response.headers.get("operation-location", "") + operation_id = op_location.split("/operations/")[-1].split("?")[0] + assert operation_id, "Could not extract operation_id from Operation-Location header" + return operation_id + + @recorded_by_proxy + def test_begin_start_indexing(self): + """Test starting indexing as a long-running operation. + + Starts the operation without waiting (polling=False) and verifies a + poller and a valid ``Operation-Location`` (operation id) are returned. + This test is self-contained and does not depend on, or leave state for, + any other test in this class. + + Note: The operation may have already completed (Succeeded) if the KB + was indexed in a previous test run, since the KB is reused across tests. + We extract the operation ID regardless of current status. + """ + client = self.create_bookshelf_client() + operation_id = self._start_indexing_operation_id(client) + assert operation_id + + @recorded_by_proxy + def test_begin_search(self): + """Test the long-running search operation. + + ``begin_search`` returns ``LROPoller[None]``; the textual search + results are surfaced via the operation-status endpoint + (``KnowledgeBaseSearchOperationResponse``). This test only verifies + the operation can be kicked off and reaches a terminal state. + + Search readiness has two stages, both handled here: + 1. The indexing *operation* must reach ``OperationState.Succeeded`` + (polled via ``get_operation_status``). + 2. After that, the KB needs a short additional window to finish + processing before ``:search`` is accepted. During that window the + service rejects ``:search`` with ``KnowledgeBaseNotReady`` ("must + be in 'Completed' state ... Current state: Processing"). That + window closes when the typed ``KB.status`` reaches + ``IndexingStatus.Succeeded``. We therefore gate on + ``KB.status == Succeeded`` and additionally retry ``begin_search`` + past any lingering ``KnowledgeBaseNotReady``. + + This test is self-contained: it drives its own indexing run to + ``Succeeded`` and is resilient to a run that the service dedupes into a + terminal non-success state (e.g. ``Canceled`` left by another test) by + starting a fresh indexing run and retrying within an overall deadline. + """ + client = self.create_bookshelf_client() + + terminal = {"succeeded", "failed", "canceled"} + # Generous deadline to cover a full GraphRAG indexing run + overall_deadline = time.time() + 2400 # 40 minutes total across retries + op_status = None + attempts = 0 + while time.time() < overall_deadline and attempts < 3: + attempts += 1 + # Start (or reuse) an indexing run and gate on the operation-status endpoint. + operation_id = self._start_indexing_operation_id(client) + while time.time() < overall_deadline: + op = client.knowledge_bases.get_operation_status( + knowledge_base_name=KNOWLEDGE_BASE_NAME, + operation_id=operation_id, + ) + # Normalize to the bare enum value (e.g. "Failed"), not the + # "OperationState.Failed" repr, so terminal detection works. + op_status = str(getattr(op.status, "value", op.status)).lower() + if op_status in terminal: + break + self._sleep(10) + if op_status == "succeeded": + break + # Indexing reached a terminal non-success state (e.g. a deduped + # Canceled/Failed run). Wait briefly, then start a fresh run. + self._sleep(10) + + if op_status != "succeeded": + pytest.fail( + f"Indexing did not reach Succeeded within the deadline " + f"(last status: {op_status!r}, attempts: {attempts})" + ) + + # After the indexing *operation* reports Succeeded, the KB needs a short + # additional window to become search-ready: the service reports the KB + # as 'Processing' and rejects :search with KnowledgeBaseNotReady until it + # reaches 'Completed'. That readiness corresponds to the typed KB.status + # reaching IndexingStatus.Succeeded. Gate on it before searching. + ready_deadline = time.time() + 600 + while time.time() < ready_deadline: + kb = client.knowledge_bases.get(knowledge_base_name=KNOWLEDGE_BASE_NAME) + if str(getattr(kb.status, "value", kb.status)).lower() == "succeeded": + break + self._sleep(15) + + # Now search the indexed KB, retrying while it is still becoming ready. + poller = None + while time.time() < ready_deadline: + try: + poller = client.knowledge_bases.begin_search( + knowledge_base_name=KNOWLEDGE_BASE_NAME, + body=SearchRequest(query="What are common drug interactions?"), + ) + break + except HttpResponseError as exc: + if "KnowledgeBaseNotReady" in str(exc): + self._sleep(15) + continue + raise + + assert poller is not None, "KnowledgeBase did not become search-ready within the deadline" + poller.result(timeout=300) + assert poller.status() == "Succeeded" + + @recorded_by_proxy + def test_begin_cancel_indexing(self): + """Test cancelling an in-flight indexing run. + + Self-contained: starts its own indexing run (polling=False) and then + cancels it, so it does not depend on, or poison the state for, any other + test. Ordered after ``test_begin_search`` so the search test is never + run against a KB left in a ``Canceled`` state by this test. + """ + client = self.create_bookshelf_client() + # Start a fresh run to cancel. + self._start_indexing_operation_id(client) + + cancel_poller = client.knowledge_bases.begin_cancel_indexing( + knowledge_base_name=KNOWLEDGE_BASE_NAME, + polling=False, + ) + # Verify the cancel operation was initiated (got a poller back) + assert cancel_poller is not None + + @recorded_by_proxy + def test_get_operation_status(self): + """Test getting operation status for a knowledge-base LRO. + + Starts an indexing LRO to obtain a real operation ID, then queries + ``get_operation_status``. Cleans up by cancelling the indexing. + """ + client = self.create_bookshelf_client() + operation_id = self._start_indexing_operation_id(client) + + status = client.knowledge_bases.get_operation_status( + knowledge_base_name=KNOWLEDGE_BASE_NAME, + operation_id=operation_id, + ) + assert status is not None + assert status.id is not None + assert status.status is not None + + # Cleanup + client.knowledge_bases.begin_cancel_indexing( + knowledge_base_name=KNOWLEDGE_BASE_NAME, + polling=False, + ) + + @recorded_by_proxy + def test_begin_delete(self): + """Test deleting a knowledge base via the standard LRO callback. + + Uses a sacrificial KB name so the read-test fixture + (``KNOWLEDGE_BASE_NAME``) is preserved. + + This test deliberately uses the **standard** long-running-operation poller + (``LROBasePolling``), which polls the ``Operation-Location`` callback URL the + service returns -- i.e. the documented LRO contract -- rather than the SDK's + custom ``_DeleteUntilGonePolling`` fallback. The monitor reports ``Running`` + and then ``Succeeded``, after which the resource itself returns ``404`` + (confirming the delete completed). + """ + client = self.create_bookshelf_client() + sacrificial_name = "sdk-test-delete-kb" + + # Create the KB we will delete (delete requires a terminal + # provisioningState, so wait for create to complete). + client.knowledge_bases.begin_create_or_update( + knowledge_base_name=sacrificial_name, + resource=KnowledgeBase( + description="Sacrificial KB for delete test", + copilot_instruction=KNOWLEDGE_BASE_COPILOT_INSTRUCTION, + storage_asset_references=[ + StorageAssetReference( + id=STORAGE_ASSET_ID, + user_assigned_identity=USER_ASSIGNED_IDENTITY, + ) + ], + ), + ).result() + + # Use the standard Operation-Location poller (NOT the custom + # _DeleteUntilGonePolling), so the test exercises the real service LRO + # callback contract. + poller = client.knowledge_bases.begin_delete( + knowledge_base_name=sacrificial_name, + polling=LROBasePolling(0 if not is_live() else 5), + ) + poller.result() + assert poller.status() == "Succeeded" + + # The resource must no longer be retrievable. + with pytest.raises(ResourceNotFoundError): + client.knowledge_bases.get(knowledge_base_name=sacrificial_name) diff --git a/sdk/discovery/azure-ai-discovery/tests/test_knowledge_bases_async.py b/sdk/discovery/azure-ai-discovery/tests/test_knowledge_bases_async.py new file mode 100644 index 000000000000..3532f4fc3353 --- /dev/null +++ b/sdk/discovery/azure-ai-discovery/tests/test_knowledge_bases_async.py @@ -0,0 +1,258 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Async tests for Knowledge Bases operations. + +Mirrors test_knowledge_bases.py against the async ``BookshelfClient`` from +``azure.ai.discovery.aio``. +""" + +import asyncio +import time +import pytest +from devtools_testutils import is_live +from devtools_testutils.aio import recorded_by_proxy_async +from azure.core.exceptions import HttpResponseError, ResourceExistsError, ResourceNotFoundError +from azure.core.polling.async_base_polling import AsyncLROBasePolling +from azure.ai.discovery.models import ( + KnowledgeBase, + SearchRequest, + StorageAssetReference, +) +from .testcase import DiscoveryBookshelfTestCase +from .constants import ( + KNOWLEDGE_BASE_NAME, + KNOWLEDGE_BASE_DESCRIPTION, + KNOWLEDGE_BASE_COPILOT_INSTRUCTION, + STORAGE_ASSET_ID, + USER_ASSIGNED_IDENTITY, +) + + +class TestKnowledgeBasesOperationsAsync(DiscoveryBookshelfTestCase): + """Async tests for KnowledgeBasesOperations (GA).""" + + @staticmethod + async def _sleep(seconds): + """Sleep only when running live; a no-op during playback.""" + if is_live(): + await asyncio.sleep(seconds) + + @staticmethod + async def _start_indexing_operation_id(client): + """Start (or reuse) an indexing run and return its operation id. + + ``node_pool_id``/``project_id`` are omitted (optional; the service + auto-assigns compute). Only one indexing run is permitted per KB at a + time, so a concurrent start returns ``409 ConcurrencyConflict``; in that + case the in-progress run is reused (the KB's ``lastIndexingRun``). + """ + try: + poller = await client.knowledge_bases.begin_start_indexing( + knowledge_base_name=KNOWLEDGE_BASE_NAME, + polling=False, + ) + except ResourceExistsError as exc: + if "ConcurrencyConflict" not in str(exc) and "already in progress" not in str(exc): + raise + kb = await client.knowledge_bases.get(knowledge_base_name=KNOWLEDGE_BASE_NAME) + run = getattr(kb, "last_indexing_run", None) + run_id = getattr(run, "run_id", None) + assert run_id, "Indexing already in progress but no lastIndexingRun id is available" + return run_id + assert poller is not None + initial_response = poller._polling_method._initial_response + op_location = initial_response.http_response.headers.get("operation-location", "") + operation_id = op_location.split("/operations/")[-1].split("?")[0] + assert operation_id, "Could not extract operation_id from Operation-Location header" + return operation_id + + @recorded_by_proxy_async + async def test_begin_create_or_update(self): + """Seeds the read-test fixture ``KNOWLEDGE_BASE_NAME`` (matches beta pattern). + + Ordered first in this class. ``begin_create_or_update`` is upsert/PUT + semantics, so re-running the suite is idempotent. + """ + client = self.create_async_bookshelf_client() + async with client: + poller = await client.knowledge_bases.begin_create_or_update( + knowledge_base_name=KNOWLEDGE_BASE_NAME, + resource=KnowledgeBase( + description=KNOWLEDGE_BASE_DESCRIPTION, + copilot_instruction=KNOWLEDGE_BASE_COPILOT_INSTRUCTION, + storage_asset_references=[ + StorageAssetReference( + id=STORAGE_ASSET_ID, + user_assigned_identity=USER_ASSIGNED_IDENTITY, + ) + ], + ), + ) + final = await poller.result() + assert final is not None + assert final.name == KNOWLEDGE_BASE_NAME + + @recorded_by_proxy_async + async def test_list(self): + """``knowledge_bases.list`` returns ``AsyncItemPaged[KnowledgeBase]``.""" + client = self.create_async_bookshelf_client() + async with client: + knowledge_bases = [] + async for kb in client.knowledge_bases.list(): + knowledge_bases.append(kb) + assert len(knowledge_bases) > 0 + for kb in knowledge_bases: + assert kb.name is not None + assert len(kb.name) <= 24 + assert kb.bookshelf_name is not None + assert kb.provisioning_state is not None + assert kb.status is not None + + @recorded_by_proxy_async + async def test_get(self): + client = self.create_async_bookshelf_client() + async with client: + kb = await client.knowledge_bases.get(knowledge_base_name=KNOWLEDGE_BASE_NAME) + assert kb is not None + assert kb.name == KNOWLEDGE_BASE_NAME + assert kb.bookshelf_name is not None + assert kb.provisioning_state is not None + assert isinstance(kb.storage_asset_references, list) + + @recorded_by_proxy_async + async def test_begin_start_indexing(self): + client = self.create_async_bookshelf_client() + async with client: + operation_id = await self._start_indexing_operation_id(client) + assert operation_id + + @recorded_by_proxy_async + async def test_begin_search(self): + client = self.create_async_bookshelf_client() + async with client: + terminal = {"succeeded", "failed", "canceled"} + overall_deadline = time.time() + 2400 # 40 minutes total across retries + op_status = None + attempts = 0 + while time.time() < overall_deadline and attempts < 3: + attempts += 1 + operation_id = await self._start_indexing_operation_id(client) + while time.time() < overall_deadline: + op = await client.knowledge_bases.get_operation_status( + knowledge_base_name=KNOWLEDGE_BASE_NAME, + operation_id=operation_id, + ) + op_status = str(getattr(op.status, "value", op.status)).lower() + if op_status in terminal: + break + await self._sleep(10) + if op_status == "succeeded": + break + await self._sleep(10) + + if op_status != "succeeded": + pytest.fail( + f"Indexing did not reach Succeeded within the deadline " + f"(last status: {op_status!r}, attempts: {attempts})" + ) + + # Wait for the KB to become search-ready (KB.status -> Succeeded), + # then retry begin_search past any lingering KnowledgeBaseNotReady. + ready_deadline = time.time() + 600 + while time.time() < ready_deadline: + kb = await client.knowledge_bases.get(knowledge_base_name=KNOWLEDGE_BASE_NAME) + if str(getattr(kb.status, "value", kb.status)).lower() == "succeeded": + break + await self._sleep(15) + + poller = None + while time.time() < ready_deadline: + try: + poller = await client.knowledge_bases.begin_search( + knowledge_base_name=KNOWLEDGE_BASE_NAME, + body=SearchRequest(query="What are common drug interactions?"), + ) + break + except HttpResponseError as exc: + if "KnowledgeBaseNotReady" in str(exc): + await self._sleep(15) + continue + raise + + assert poller is not None, "KnowledgeBase did not become search-ready within the deadline" + await poller.result() + assert poller.status() == "Succeeded" + + @recorded_by_proxy_async + async def test_begin_cancel_indexing(self): + client = self.create_async_bookshelf_client() + async with client: + await self._start_indexing_operation_id(client) + cancel_poller = await client.knowledge_bases.begin_cancel_indexing( + knowledge_base_name=KNOWLEDGE_BASE_NAME, + polling=False, + ) + assert cancel_poller is not None + + @recorded_by_proxy_async + async def test_get_operation_status(self): + client = self.create_async_bookshelf_client() + async with client: + operation_id = await self._start_indexing_operation_id(client) + + status = await client.knowledge_bases.get_operation_status( + knowledge_base_name=KNOWLEDGE_BASE_NAME, + operation_id=operation_id, + ) + assert status is not None + assert status.id is not None + assert status.status is not None + + await client.knowledge_bases.begin_cancel_indexing( + knowledge_base_name=KNOWLEDGE_BASE_NAME, + polling=False, + ) + + @recorded_by_proxy_async + async def test_begin_delete(self): + """Delete a knowledge base via the standard Operation-Location LRO callback. + + Mirrors the sync test: uses the **standard** ``AsyncLROBasePolling`` poller + (which polls the ``Operation-Location`` callback URL the service returns), + rather than the SDK's custom ``_DeleteUntilGonePolling`` fallback. The monitor + reports ``Running`` and then ``Succeeded``, after which the resource itself + returns ``404`` (confirming the delete completed). + """ + client = self.create_async_bookshelf_client() + async with client: + sacrificial_name = "sdk-test-delete-kb-async" + + create_poller = await client.knowledge_bases.begin_create_or_update( + knowledge_base_name=sacrificial_name, + resource=KnowledgeBase( + description="Sacrificial KB for delete test (async)", + copilot_instruction=KNOWLEDGE_BASE_COPILOT_INSTRUCTION, + storage_asset_references=[ + StorageAssetReference( + id=STORAGE_ASSET_ID, + user_assigned_identity=USER_ASSIGNED_IDENTITY, + ) + ], + ), + ) + await create_poller.result() + + # Use the standard Operation-Location poller (NOT the custom + # _AsyncDeleteUntilGonePolling), so the test exercises the real service + # LRO callback contract. + poller = await client.knowledge_bases.begin_delete( + knowledge_base_name=sacrificial_name, + polling=AsyncLROBasePolling(0 if not is_live() else 5), + ) + await poller.result() + assert poller.status() == "Succeeded" + + with pytest.raises(ResourceNotFoundError): + await client.knowledge_bases.get(knowledge_base_name=sacrificial_name) diff --git a/sdk/discovery/azure-ai-discovery/tests/test_tasks.py b/sdk/discovery/azure-ai-discovery/tests/test_tasks.py index ac7d9a9be945..d04610f183e9 100644 --- a/sdk/discovery/azure-ai-discovery/tests/test_tasks.py +++ b/sdk/discovery/azure-ai-discovery/tests/test_tasks.py @@ -9,12 +9,13 @@ - list (Paged) - start, add_comment, add_execution_history """ + import json from datetime import datetime, timezone from devtools_testutils import recorded_by_proxy from azure.core.rest import HttpRequest -from azure.ai.discovery._workspace.azure.ai.discovery.models import ( +from azure.ai.discovery.models import ( Task, TaskAssignee, TaskComment, @@ -117,12 +118,15 @@ def test_get(self): self._delete_task_quiet(client, created.name) @recorded_by_proxy - def test_update(self): - """Test updating a task (PATCH).""" + def test_stable_update(self): + """Test updating a task (PATCH). + + Was ``tasks.update`` in beta; renamed to ``tasks.stable_update`` in GA. + """ client = self.create_workspace_client() created = self._create_task(client, title="task-for-update-test") try: - updated = client.tasks.update( + updated = client.tasks.stable_update( project_name=self.project_name, investigation_name=self.investigation_name, task_name=created.name, diff --git a/sdk/discovery/azure-ai-discovery/tests/test_tasks_async.py b/sdk/discovery/azure-ai-discovery/tests/test_tasks_async.py new file mode 100644 index 000000000000..563828a0ad2d --- /dev/null +++ b/sdk/discovery/azure-ai-discovery/tests/test_tasks_async.py @@ -0,0 +1,217 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Async tests for Tasks operations. + +Mirrors test_tasks.py against the async ``WorkspaceClient`` from +``azure.ai.discovery.aio``. +""" + +from datetime import datetime, timezone + +from devtools_testutils.aio import recorded_by_proxy_async +from azure.ai.discovery.models import ( + Task, + TaskAssignee, + TaskComment, + ExecutionHistoryEntry, +) +from .testcase import DiscoveryWorkspaceTestCase +from .constants import AGENT_NAME, investigation_path + + +class TestTasksAsync(DiscoveryWorkspaceTestCase): + """Async tests for TasksOperations.""" + + # ---- helpers --------------------------------------------------------- + + async def _create_task(self, client, *, title="sdk-test-task", description="Test task for Python SDK (async)"): + investigation_id = investigation_path(self.project_name, self.investigation_name) + return await client.tasks.create( + project_name=self.project_name, + investigation_name=self.investigation_name, + body=Task( + title=title, + priority="High", + description=description, + assigned_to=TaskAssignee(id=AGENT_NAME, type="Application"), + investigation_id=investigation_id, + ), + ) + + async def _delete_task_quiet(self, client, task_name): + try: + await client.tasks.delete( + project_name=self.project_name, + investigation_name=self.investigation_name, + task_name=task_name, + ) + except Exception: + pass + + # ---- tests ----------------------------------------------------------- + + @recorded_by_proxy_async + async def test_list(self): + client = self.create_async_workspace_client() + async with client: + created = await self._create_task(client, title="task-for-list-test-async") + try: + tasks = [] + async for t in client.tasks.list( + project_name=self.project_name, + investigation_name=self.investigation_name, + ): + tasks.append(t) + assert len(tasks) > 0 + for t in tasks: + assert t.title is not None + assert t.status is not None + finally: + await self._delete_task_quiet(client, created.name) + + @recorded_by_proxy_async + async def test_create(self): + client = self.create_async_workspace_client() + async with client: + task = await self._create_task(client, title="A new sdk task (async)") + try: + assert task is not None + assert task.title == "A new sdk task (async)" + assert task.description == "Test task for Python SDK (async)" + finally: + await self._delete_task_quiet(client, task.name) + + @recorded_by_proxy_async + async def test_get(self): + client = self.create_async_workspace_client() + async with client: + created = await self._create_task(client, title="task-for-get-test-async") + try: + task = await client.tasks.get( + project_name=self.project_name, + investigation_name=self.investigation_name, + task_name=created.name, + ) + assert task is not None + assert task.title == "task-for-get-test-async" + assert task.status is not None + assert task.created_at is not None + assert task.assigned_to is not None + finally: + await self._delete_task_quiet(client, created.name) + + @recorded_by_proxy_async + async def test_stable_update(self): + """Was ``tasks.update`` in beta; ``stable_update`` in GA.""" + client = self.create_async_workspace_client() + async with client: + created = await self._create_task(client, title="task-for-update-test-async") + try: + updated = await client.tasks.stable_update( + project_name=self.project_name, + investigation_name=self.investigation_name, + task_name=created.name, + resource=Task( + title="Updated sdk task title (async)", + description="Updated sdk task description (async)", + ), + ) + assert updated is not None + assert updated.title == "Updated sdk task title (async)" + assert updated.description == "Updated sdk task description (async)" + finally: + await self._delete_task_quiet(client, created.name) + + @recorded_by_proxy_async + async def test_delete(self): + client = self.create_async_workspace_client() + async with client: + created = await self._create_task(client, title="task-for-delete-test-async") + status = await client.tasks.delete( + project_name=self.project_name, + investigation_name=self.investigation_name, + task_name=created.name, + ) + assert status is None + + @recorded_by_proxy_async + async def test_list_with_filter(self): + client = self.create_async_workspace_client() + async with client: + created = await self._create_task(client, title="task-for-filter-test-async") + try: + tasks = [] + async for t in client.tasks.list( + project_name=self.project_name, + investigation_name=self.investigation_name, + filter="status eq 'New'", + ): + tasks.append(t) + # Filter results may be empty but the iteration must succeed. + assert isinstance(tasks, list) + finally: + await self._delete_task_quiet(client, created.name) + + @recorded_by_proxy_async + async def test_start(self): + client = self.create_async_workspace_client() + async with client: + created = await self._create_task(client, title="task-for-start-test-async") + try: + task = await client.tasks.start( + project_name=self.project_name, + investigation_name=self.investigation_name, + task_name=created.name, + ) + assert task is not None + assert task.status is not None + finally: + await self._delete_task_quiet(client, created.name) + + @recorded_by_proxy_async + async def test_add_comment(self): + client = self.create_async_workspace_client() + async with client: + created = await self._create_task(client, title="task-for-comment-test-async") + try: + task = await client.tasks.add_comment( + task_name=created.name, + project_name=self.project_name, + investigation_name=self.investigation_name, + body=TaskComment( + timestamp=datetime(2026, 4, 8, 21, 0, 0, tzinfo=timezone.utc), + created_by="test-user", + created_by_type="User", + text="Test comment (async)", + ), + ) + assert task is not None + assert task.title is not None + finally: + await self._delete_task_quiet(client, created.name) + + @recorded_by_proxy_async + async def test_add_execution_history(self): + client = self.create_async_workspace_client() + async with client: + created = await self._create_task(client, title="task-for-exec-history-test-async") + try: + task = await client.tasks.add_execution_history( + project_name=self.project_name, + investigation_name=self.investigation_name, + task_name=created.name, + body=ExecutionHistoryEntry( + created_at=datetime(2026, 4, 8, 21, 0, 0, tzinfo=timezone.utc), + action="completed", + created_by=AGENT_NAME, + created_by_type="Application", + summary="Task execution completed (async)", + ), + ) + assert task is not None + assert task.title is not None + assert task.status is not None + finally: + await self._delete_task_quiet(client, created.name) diff --git a/sdk/discovery/azure-ai-discovery/tests/test_tools.py b/sdk/discovery/azure-ai-discovery/tests/test_tools.py index 1a7be83eeebb..21dbd3c12498 100644 --- a/sdk/discovery/azure-ai-discovery/tests/test_tools.py +++ b/sdk/discovery/azure-ai-discovery/tests/test_tools.py @@ -11,9 +11,11 @@ - get_operations - get_compute_usage """ + import os from devtools_testutils import recorded_by_proxy +from azure.core.exceptions import HttpResponseError from .testcase import DiscoveryWorkspaceTestCase from .constants import TOOL_ID, NODE_POOL_ID, WORKSPACE_ENDPOINT, PROJECT_NAME @@ -23,13 +25,14 @@ class TestToolsOperations(DiscoveryWorkspaceTestCase): # ---- helpers --------------------------------------------------------- - def _begin_run(self, client, *, command='echo "hello world"'): + def _begin_run(self, client, *, command='echo "hello world"', polling=True): """Start a tool run and return the poller.""" return client.tools.begin_run( project_name=PROJECT_NAME, tool_id=TOOL_ID, node_pool_ids=[NODE_POOL_ID], command=command, + polling=polling, ) @staticmethod @@ -99,18 +102,44 @@ def test_get_run_status_with_log_count(self): assert "result" in status @recorded_by_proxy - def test_cancel_run(self): - """Test cancelling a tool run by starting one and immediately cancelling it.""" + def test_begin_cancel_run_lro(self): + """Test cancelling a tool run by starting one and immediately cancelling it. + + Was the synchronous ``tools.cancel_run`` in beta; replaced by the + long-running ``tools.begin_cancel_run_lro`` in GA. + + The cancel LRO's terminal status reflects the state of the original + Tool.Run operation: ``Canceled`` when the cancel succeeded, or + ``Succeeded`` if the run finished before cancellation took effect. + """ client = self.create_workspace_client(endpoint=WORKSPACE_ENDPOINT) - # Start a long-running command so we have time to cancel it - poller = self._begin_run(client, command='echo "cancel test" && sleep 300') + # Start the run with ``polling=False`` so no background run-poller thread + # is created. Both the run poller and the cancel poller poll the same + # operation-status URL; leaving the run poller polling races it against + # the cancel poller for the recorded responses and makes playback flaky. + # We only need the run's operation_id here, not its terminal result. + poller = self._begin_run(client, command='echo "cancel test" && sleep 300', polling=False) operation_id = self._operation_id_from_poller(poller) - client.tools.cancel_run( + cancel_poller = client.tools.begin_cancel_run_lro( project_name=PROJECT_NAME, operation_id=operation_id, ) + # The cancel LRO reports terminal status ``Canceled`` which azure-core's + # base polling treats as ``OperationFailed`` and re-raises as + # ``HttpResponseError``. For a cancel operation that's the success path, + # so we catch the exception and verify the terminal status. + try: + cancel_poller.wait() + terminal_status = cancel_poller.status() + except HttpResponseError: + terminal_status = cancel_poller.status() + assert cancel_poller.done() + assert terminal_status in ( + "Canceled", + "Succeeded", + ), f"Expected terminal Canceled or Succeeded, got {terminal_status!r}" @recorded_by_proxy def test_get_operations(self): diff --git a/sdk/discovery/azure-ai-discovery/tests/test_tools_async.py b/sdk/discovery/azure-ai-discovery/tests/test_tools_async.py new file mode 100644 index 000000000000..753c30eb7649 --- /dev/null +++ b/sdk/discovery/azure-ai-discovery/tests/test_tools_async.py @@ -0,0 +1,137 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Async tests for Tools operations. + +Mirrors test_tools.py against the async ``WorkspaceClient`` from +``azure.ai.discovery.aio``. +""" + +from devtools_testutils.aio import recorded_by_proxy_async +from azure.core.exceptions import HttpResponseError +from .testcase import DiscoveryWorkspaceTestCase +from .constants import TOOL_ID, NODE_POOL_ID, WORKSPACE_ENDPOINT, PROJECT_NAME + + +class TestToolsOperationsAsync(DiscoveryWorkspaceTestCase): + """Async tests for ToolsOperations.""" + + # ---- helpers --------------------------------------------------------- + + async def _begin_run(self, client, *, command='echo "hello world"'): + """Start a tool run and return the poller.""" + return await client.tools.begin_run( + project_name=PROJECT_NAME, + tool_id=TOOL_ID, + node_pool_ids=[NODE_POOL_ID], + command=command, + ) + + @staticmethod + def _operation_id_from_poller(poller): + if hasattr(poller, "operation_id") and poller.operation_id: + return poller.operation_id + initial_response = poller._polling_method._initial_response + op_location = initial_response.http_response.headers.get("operation-location", "") + operation_id = op_location.split("/operations/")[-1].split("?")[0] + assert operation_id, "Could not extract operation_id from poller" + return operation_id + + # ---- tests ----------------------------------------------------------- + + @recorded_by_proxy_async + async def test_begin_run(self): + client = self.create_async_workspace_client(endpoint=WORKSPACE_ENDPOINT) + async with client: + poller = await self._begin_run(client) + result = await poller.result() + assert result is not None + + @recorded_by_proxy_async + async def test_get_run_status(self): + client = self.create_async_workspace_client(endpoint=WORKSPACE_ENDPOINT) + async with client: + poller = await self._begin_run(client, command='echo "status test (async)"') + await poller.result() + operation_id = self._operation_id_from_poller(poller) + + status = await client.tools.get_run_status( + project_name=PROJECT_NAME, + operation_id=operation_id, + ) + assert status is not None + assert status["status"] is not None + assert "result" in status + + @recorded_by_proxy_async + async def test_get_run_status_with_log_count(self): + client = self.create_async_workspace_client(endpoint=WORKSPACE_ENDPOINT) + async with client: + poller = await self._begin_run(client, command='echo "log count test (async)"') + await poller.result() + operation_id = self._operation_id_from_poller(poller) + + status = await client.tools.get_run_status( + project_name=PROJECT_NAME, + operation_id=operation_id, + log_count=10, + ) + assert status is not None + assert status["status"] is not None + assert "result" in status + + @recorded_by_proxy_async + async def test_begin_cancel_run_lro(self): + """Was sync ``tools.cancel_run`` in beta; LRO ``begin_cancel_run_lro`` in GA. + + Uses ``wait`` rather than ``result`` so the poller does not raise when + the terminal status is ``Canceled`` (the success case for a cancel). + """ + client = self.create_async_workspace_client(endpoint=WORKSPACE_ENDPOINT) + async with client: + poller = await self._begin_run(client, command='echo "cancel test (async)" && sleep 300') + operation_id = self._operation_id_from_poller(poller) + + cancel_poller = await client.tools.begin_cancel_run_lro( + project_name=PROJECT_NAME, + operation_id=operation_id, + ) + # Cancel LROs report terminal status ``Canceled`` which azure-core + # treats as ``OperationFailed``. Catch the exception and verify the + # terminal status reflects a successful cancellation. + try: + await cancel_poller.wait() + terminal_status = cancel_poller.status() + except HttpResponseError: + terminal_status = cancel_poller.status() + # NOTE: unlike the sync ``LROPoller`` (whose ``done()`` tracks the + # polling thread finishing), ``AsyncLROPoller.done()`` only flips to + # True when ``wait()`` returns normally. A terminal ``Canceled`` + # status makes ``wait()`` raise, so ``done()`` stays False here even + # though the operation is terminal. Assert on the terminal status + # instead, which reliably reflects that the cancel completed. + assert terminal_status in ( + "Canceled", + "Succeeded", + ), f"Expected terminal Canceled or Succeeded, got {terminal_status!r}" + + @recorded_by_proxy_async + async def test_get_operations(self): + client = self.create_async_workspace_client() + async with client: + operations = await client.tools.get_operations( + project_name=PROJECT_NAME, + ) + assert operations is not None + assert "value" in operations + assert isinstance(operations["value"], list) + + @recorded_by_proxy_async + async def test_get_compute_usage(self): + client = self.create_async_workspace_client() + async with client: + usage = await client.tools.get_compute_usage( + project_name=PROJECT_NAME, + ) + assert usage is not None diff --git a/sdk/discovery/azure-ai-discovery/tests/test_unit_client.py b/sdk/discovery/azure-ai-discovery/tests/test_unit_client.py index b231af5b2809..6842ff8adf73 100644 --- a/sdk/discovery/azure-ai-discovery/tests/test_unit_client.py +++ b/sdk/discovery/azure-ai-discovery/tests/test_unit_client.py @@ -7,6 +7,7 @@ These tests verify client configuration without making HTTP calls. """ + import pytest from azure.core.credentials import AzureKeyCredential from azure.ai.discovery import WorkspaceClient, BookshelfClient @@ -70,9 +71,10 @@ def test_client_has_expected_operations(self): credential=AzureKeyCredential("fake-key"), ) - # Verify operation groups exist + # Verify operation groups exist. In GA, the beta + # ``knowledge_base_versions`` group was folded into ``knowledge_bases``. assert hasattr(client, "knowledge_bases") - assert hasattr(client, "knowledge_base_versions") + assert not hasattr(client, "knowledge_base_versions") def test_client_endpoint_validation(self): """Test that client accepts valid endpoint URLs.""" diff --git a/sdk/discovery/azure-ai-discovery/tests/test_unit_models.py b/sdk/discovery/azure-ai-discovery/tests/test_unit_models.py index 9768337ab7ce..4f9c331e8646 100644 --- a/sdk/discovery/azure-ai-discovery/tests/test_unit_models.py +++ b/sdk/discovery/azure-ai-discovery/tests/test_unit_models.py @@ -7,6 +7,7 @@ These tests verify model initialization without making HTTP calls. """ + import pytest from azure.ai.discovery import models @@ -95,14 +96,10 @@ def test_knowledge_base_model(self): assert kb.description == "A test knowledge base" assert kb.copilot_instruction == "Test instruction" - def test_knowledge_base_version_model(self): - """Test KnowledgeBaseVersion model can be initialized.""" - version = models.KnowledgeBaseVersion( - description="Version 1", - copilot_instruction="Instruction v1", - ) - assert version.description == "Version 1" - assert version.copilot_instruction == "Instruction v1" + def test_search_request_model(self): + """Test SearchRequest model can be initialized (GA-only).""" + req = models.SearchRequest(query="hello world") + assert req.query == "hello world" def test_storage_asset_reference_model(self): """Test StorageAssetReference model can be initialized.""" diff --git a/sdk/discovery/azure-ai-discovery/tests/testcase.py b/sdk/discovery/azure-ai-discovery/tests/testcase.py index 13f426f0f9cd..3e860b2bf713 100644 --- a/sdk/discovery/azure-ai-discovery/tests/testcase.py +++ b/sdk/discovery/azure-ai-discovery/tests/testcase.py @@ -6,9 +6,10 @@ Base test classes for azure-ai-discovery recorded tests. Provides AzureRecordedTestCase subclasses for recorded/playback testing -and helper methods for client creation. +(sync and async) and helper methods for client creation. """ -from devtools_testutils import AzureRecordedTestCase + +from devtools_testutils import AzureRecordedTestCase, is_live from .constants import ( WORKSPACE_ENDPOINT, PROJECT_NAME, @@ -34,7 +35,7 @@ def setup_method(self, method): self.workspace_endpoint = WORKSPACE_ENDPOINT def create_workspace_client(self, endpoint=None, **kwargs): - """Create a WorkspaceClient for testing.""" + """Create a sync WorkspaceClient for testing.""" from azure.ai.discovery import WorkspaceClient return WorkspaceClient( @@ -44,6 +45,17 @@ def create_workspace_client(self, endpoint=None, **kwargs): **kwargs, ) + def create_async_workspace_client(self, endpoint=None, **kwargs): + """Create an async WorkspaceClient for testing.""" + from azure.ai.discovery.aio import WorkspaceClient as AsyncWorkspaceClient + + return AsyncWorkspaceClient( + endpoint=endpoint or self.workspace_endpoint, + credential=self.get_credential(AsyncWorkspaceClient, is_async=True), + credential_scopes=[DISCOVERY_SCOPE], + **kwargs, + ) + class DiscoveryBookshelfTestCase(AzureRecordedTestCase): """Base class for Discovery Bookshelf data plane SDK tests. @@ -59,12 +71,29 @@ def setup_method(self, method): self.bookshelf_endpoint = BOOKSHELF_ENDPOINT def create_bookshelf_client(self, **kwargs): - """Create a BookshelfClient for testing.""" + """Create a sync BookshelfClient for testing.""" from azure.ai.discovery import BookshelfClient + # During playback the recorded poll responses return instantly, so use a + # zero polling interval to keep recorded LRO tests fast. + if not is_live(): + kwargs.setdefault("polling_interval", 0) return BookshelfClient( endpoint=self.bookshelf_endpoint, credential=self.get_credential(BookshelfClient), credential_scopes=[DISCOVERY_SCOPE], **kwargs, ) + + def create_async_bookshelf_client(self, **kwargs): + """Create an async BookshelfClient for testing.""" + from azure.ai.discovery.aio import BookshelfClient as AsyncBookshelfClient + + if not is_live(): + kwargs.setdefault("polling_interval", 0) + return AsyncBookshelfClient( + endpoint=self.bookshelf_endpoint, + credential=self.get_credential(AsyncBookshelfClient, is_async=True), + credential_scopes=[DISCOVERY_SCOPE], + **kwargs, + ) diff --git a/sdk/discovery/azure-ai-discovery/tsp-location.yaml b/sdk/discovery/azure-ai-discovery/tsp-location.yaml index 50cd863f6cfd..b482980851f5 100644 --- a/sdk/discovery/azure-ai-discovery/tsp-location.yaml +++ b/sdk/discovery/azure-ai-discovery/tsp-location.yaml @@ -1,4 +1,9 @@ -batch: - - ./azure/ai/discovery/_workspace - - ./azure/ai/discovery/_bookshelf -directory: specification/discovery +# Pinned to the GA merge commit of Azure/azure-rest-api-specs PR #42884 +# ("[Microsoft Discovery] Add data-plane Discovery new GA version 2026-06-01"). +directory: specification/discovery/Discovery.Combined +commit: fbe3c49c541a2932f4a4cb348fb0798988f4aca4 +repo: Azure/azure-rest-api-specs +additionalDirectories: + - specification/discovery/Discovery.Common + - specification/discovery/Discovery.Workspace + - specification/discovery/Discovery.Bookshelf