diff --git a/sdk/ai/azure-ai-projects/CHANGELOG.md b/sdk/ai/azure-ai-projects/CHANGELOG.md index 0a9b847d4dec..329a1bb094d4 100644 --- a/sdk/ai/azure-ai-projects/CHANGELOG.md +++ b/sdk/ai/azure-ai-projects/CHANGELOG.md @@ -11,6 +11,12 @@ * New evaluator generation job operations on `.beta.evaluators`: `create_generation_job`, `get_generation_job`, `list_generation_jobs`, `cancel_generation_job`, `delete_generation_job`. * New methods on `.beta.agents` sub-client for code-based hosted agents: `update_agent_from_code()`, `create_agent_version_from_code()`, `download_agent_version_code()`, `download_agent_code()`. * New read-only property `content_hash` on `CodeConfiguration`, returning the SHA-256 hex digest of the uploaded code zip. +* New `.beta.models` sub-client with model version management operations: `list_versions`, `list`, `get`, `delete`, `create_version`. +* New `.beta.routines` sub-client with routine lifecycle operations: `create_or_update`, `get`, `list`, `enable`, `disable`, `delete`, `list_runs`. +* New agent optimization operations on `.beta.agents`: `create_optimization_job`, `get_optimization_job`, `list_optimization_jobs`, `cancel_optimization_job`, `delete_optimization_job`, `list_optimization_candidates`, `get_optimization_candidate`, `get_optimization_candidate_config`, `get_optimization_candidate_results`. +* New `MCP` protocol support in `AgentEndpointProtocol`. +* New `external` agent kind in `AgentKind` for external agents. +* New agent methods: `dispatch_async`, `create_async`, `patch_agent_details`. ### Breaking Changes @@ -29,6 +35,7 @@ Breaking changes in beta classes: * Renamed class `SkillObject` to `SkillDetails`. * Removed class `FabricIQPreviewToolParameters`. * Removed class `WorkIQPreviewToolParameters`. +* Renamed enum value `EvaluatorDefinitionType.RUBRICS` to `EvaluatorDefinitionType.RUBRIC`. ### Bugs Fixed diff --git a/sdk/ai/azure-ai-projects/apiview-properties.json b/sdk/ai/azure-ai-projects/apiview-properties.json index 354cbc4b7d65..6b220f8903f9 100644 --- a/sdk/ai/azure-ai-projects/apiview-properties.json +++ b/sdk/ai/azure-ai-projects/apiview-properties.json @@ -23,6 +23,7 @@ "azure.ai.projects.models.AgentIdentity": "Azure.AI.Projects.AgentIdentity", "azure.ai.projects.models.AgentObjectVersions": "Azure.AI.Projects.AgentObject.versions.anonymous", "azure.ai.projects.models.AgentSessionResource": "Azure.AI.Projects.AgentSessionResource", + "azure.ai.projects.models.AgentsPagedResultOptimizationCandidate": "Azure.AI.Projects.AgentsPagedResult", "azure.ai.projects.models.EvaluationTaxonomyInput": "Azure.AI.Projects.EvaluationTaxonomyInput", "azure.ai.projects.models.AgentTaxonomyInput": "Azure.AI.Projects.AgentTaxonomyInput", "azure.ai.projects.models.AgentVersionDetails": "Azure.AI.Projects.AgentVersionObject", @@ -32,8 +33,9 @@ "azure.ai.projects.models.ApiKeyCredentials": "Azure.AI.Projects.ApiKeyCredentials", "azure.ai.projects.models.ApplyPatchToolParam": "OpenAI.ApplyPatchToolParam", "azure.ai.projects.models.ApproximateLocation": "OpenAI.ApproximateLocation", + "azure.ai.projects.models.ArtifactProfile": "Azure.AI.Projects.ArtifactProfile", "azure.ai.projects.models.AutoCodeInterpreterToolParam": "OpenAI.AutoCodeInterpreterToolParam", - "azure.ai.projects.models.Target": "Azure.AI.Projects.Target", + "azure.ai.projects.models.EvaluationTarget": "Azure.AI.Projects.Target", "azure.ai.projects.models.AzureAIAgentTarget": "Azure.AI.Projects.AzureAIAgentTarget", "azure.ai.projects.models.AzureAIModelTarget": "Azure.AI.Projects.AzureAIModelTarget", "azure.ai.projects.models.Index": "Azure.AI.Projects.Index", @@ -45,7 +47,7 @@ "azure.ai.projects.models.AzureFunctionDefinitionFunction": "Azure.AI.Projects.AzureFunctionDefinition.function.anonymous", "azure.ai.projects.models.AzureFunctionStorageQueue": "Azure.AI.Projects.AzureFunctionStorageQueue", "azure.ai.projects.models.AzureFunctionTool": "Azure.AI.Projects.AzureFunctionTool", - "azure.ai.projects.models.TargetConfig": "Azure.AI.Projects.TargetConfig", + "azure.ai.projects.models.RedTeamTargetConfig": "Azure.AI.Projects.RedTeamTargetConfig", "azure.ai.projects.models.AzureOpenAIModelConfiguration": "Azure.AI.Projects.AzureOpenAIModelConfiguration", "azure.ai.projects.models.BingCustomSearchConfiguration": "Azure.AI.Projects.BingCustomSearchConfiguration", "azure.ai.projects.models.BingCustomSearchPreviewTool": "Azure.AI.Projects.BingCustomSearchPreviewTool", @@ -60,6 +62,8 @@ "azure.ai.projects.models.BrowserAutomationPreviewTool": "Azure.AI.Projects.BrowserAutomationPreviewTool", "azure.ai.projects.models.BrowserAutomationToolConnectionParameters": "Azure.AI.Projects.BrowserAutomationToolConnectionParameters", "azure.ai.projects.models.BrowserAutomationToolParameters": "Azure.AI.Projects.BrowserAutomationToolParameters", + "azure.ai.projects.models.CandidateDeployConfig": "Azure.AI.Projects.CandidateDeployConfig", + "azure.ai.projects.models.CandidateResults": "Azure.AI.Projects.CandidateResults", "azure.ai.projects.models.CaptureStructuredOutputsTool": "Azure.AI.Projects.CaptureStructuredOutputsTool", "azure.ai.projects.models.ChartCoordinate": "Azure.AI.Projects.ChartCoordinate", "azure.ai.projects.models.MemoryItem": "Azure.AI.Projects.MemoryItem", @@ -87,6 +91,7 @@ "azure.ai.projects.models.CosmosDBIndex": "Azure.AI.Projects.CosmosDBIndex", "azure.ai.projects.models.CreateAgentVersionFromCodeContent": "Azure.AI.Projects.CreateAgentVersionFromCodeContent", "azure.ai.projects.models.CreateAgentVersionFromCodeMetadata": "Azure.AI.Projects.CreateAgentVersionFromCodeMetadata", + "azure.ai.projects.models.CreateAsyncResponse": "Azure.AI.Projects.createAsync.Response.anonymous", "azure.ai.projects.models.Trigger": "Azure.AI.Projects.Trigger", "azure.ai.projects.models.CronTrigger": "Azure.AI.Projects.CronTrigger", "azure.ai.projects.models.CustomCredential": "Azure.AI.Projects.CustomCredential", @@ -100,6 +105,7 @@ "azure.ai.projects.models.DataGenerationJobInputs": "Azure.AI.Projects.DataGenerationJobInputs", "azure.ai.projects.models.DataGenerationJobOptions": "Azure.AI.Projects.DataGenerationJobOptions", "azure.ai.projects.models.DataGenerationJobOutput": "Azure.AI.Projects.DataGenerationJobOutput", + "azure.ai.projects.models.DataGenerationJobOutputOptions": "Azure.AI.Projects.DataGenerationJobOutputOptions", "azure.ai.projects.models.DataGenerationJobResult": "Azure.AI.Projects.DataGenerationJobResult", "azure.ai.projects.models.DataGenerationModelOptions": "Azure.AI.Projects.DataGenerationModelOptions", "azure.ai.projects.models.DataGenerationTokenUsage": "Azure.AI.Projects.DataGenerationTokenUsage", @@ -107,22 +113,31 @@ "azure.ai.projects.models.DatasetDataGenerationJobOutput": "Azure.AI.Projects.DatasetDataGenerationJobOutput", "azure.ai.projects.models.DatasetDataGenerationJobSource": "Azure.AI.Projects.DatasetDataGenerationJobSource", "azure.ai.projects.models.DatasetEvaluatorGenerationJobSource": "Azure.AI.Projects.DatasetEvaluatorGenerationJobSource", + "azure.ai.projects.models.DatasetItem": "Azure.AI.Projects.DatasetItem", + "azure.ai.projects.models.DatasetRef": "Azure.AI.Projects.DatasetRef", "azure.ai.projects.models.DatasetReference": "Azure.AI.Projects.DatasetReference", "azure.ai.projects.models.DatasetVersion": "Azure.AI.Projects.DatasetVersion", "azure.ai.projects.models.DeleteAgentResponse": "Azure.AI.Projects.DeleteAgentResponse", "azure.ai.projects.models.DeleteAgentVersionResponse": "Azure.AI.Projects.DeleteAgentVersionResponse", + "azure.ai.projects.models.DeleteMemoryResponse": "Azure.AI.Projects.DeleteMemoryResponse", "azure.ai.projects.models.DeleteMemoryStoreResult": "Azure.AI.Projects.DeleteMemoryStoreResponse", "azure.ai.projects.models.DeleteSkillResult": "Azure.AI.Projects.DeleteSkillResponse", "azure.ai.projects.models.Deployment": "Azure.AI.Projects.Deployment", + "azure.ai.projects.models.Dimension": "Azure.AI.Projects.Dimension", + "azure.ai.projects.models.DispatchRoutineResponse": "Azure.AI.Projects.DispatchRoutineResponse", "azure.ai.projects.models.EmbeddingConfiguration": "Azure.AI.Projects.EmbeddingConfiguration", "azure.ai.projects.models.EntraAuthorizationScheme": "Azure.AI.Projects.EntraAuthorizationScheme", "azure.ai.projects.models.EntraIDCredentials": "Azure.AI.Projects.EntraIDCredentials", + "azure.ai.projects.models.IsolationKeySource": "Azure.AI.Projects.IsolationKeySource", + "azure.ai.projects.models.EntraIsolationKeySource": "Azure.AI.Projects.EntraIsolationKeySource", "azure.ai.projects.models.EvalResult": "Azure.AI.Projects.EvalResult", + "azure.ai.projects.models.EvalRunOutputItemResult": "Azure.AI.Projects.EvalRunOutputItemResult", "azure.ai.projects.models.EvalRunResultCompareItem": "Azure.AI.Projects.EvalRunResultCompareItem", "azure.ai.projects.models.EvalRunResultComparison": "Azure.AI.Projects.EvalRunResultComparison", "azure.ai.projects.models.EvalRunResultSummary": "Azure.AI.Projects.EvalRunResultSummary", "azure.ai.projects.models.EvaluationComparisonInsightRequest": "Azure.AI.Projects.EvaluationComparisonInsightRequest", "azure.ai.projects.models.EvaluationComparisonInsightResult": "Azure.AI.Projects.EvaluationComparisonInsightResult", + "azure.ai.projects.models.EvaluationCriterion": "Azure.AI.Projects.EvaluationCriterion", "azure.ai.projects.models.InsightSample": "Azure.AI.Projects.InsightSample", "azure.ai.projects.models.EvaluationResultSample": "Azure.AI.Projects.EvaluationResultSample", "azure.ai.projects.models.EvaluationRule": "Azure.AI.Projects.EvaluationRule", @@ -132,12 +147,14 @@ "azure.ai.projects.models.ScheduleTask": "Azure.AI.Projects.ScheduleTask", "azure.ai.projects.models.EvaluationScheduleTask": "Azure.AI.Projects.EvaluationScheduleTask", "azure.ai.projects.models.EvaluationTaxonomy": "Azure.AI.Projects.EvaluationTaxonomy", + "azure.ai.projects.models.EvaluatorCredentialRequest": "Azure.AI.Projects.EvaluatorCredentialRequest", "azure.ai.projects.models.EvaluatorGenerationArtifacts": "Azure.AI.Projects.EvaluatorGenerationArtifacts", "azure.ai.projects.models.EvaluatorGenerationInputs": "Azure.AI.Projects.EvaluatorGenerationInputs", "azure.ai.projects.models.EvaluatorGenerationJob": "Azure.AI.Projects.EvaluatorGenerationJob", "azure.ai.projects.models.EvaluatorGenerationTokenUsage": "Azure.AI.Projects.EvaluatorGenerationTokenUsage", "azure.ai.projects.models.EvaluatorMetric": "Azure.AI.Projects.EvaluatorMetric", "azure.ai.projects.models.EvaluatorVersion": "Azure.AI.Projects.EvaluatorVersion", + "azure.ai.projects.models.ExternalAgentDefinition": "Azure.AI.Projects.ExternalAgentDefinition", "azure.ai.projects.models.FabricDataAgentToolParameters": "Azure.AI.Projects.FabricDataAgentToolParameters", "azure.ai.projects.models.FabricIQPreviewTool": "Azure.AI.Projects.FabricIQPreviewTool", "azure.ai.projects.models.FieldMapping": "Azure.AI.Projects.FieldMapping", @@ -148,10 +165,14 @@ "azure.ai.projects.models.VersionSelectionRule": "Azure.AI.Projects.VersionSelectionRule", "azure.ai.projects.models.FixedRatioVersionSelectionRule": "Azure.AI.Projects.FixedRatioVersionSelectionRule", "azure.ai.projects.models.FolderDatasetVersion": "Azure.AI.Projects.FolderDatasetVersion", + "azure.ai.projects.models.FoundryModelWarning": "Azure.AI.Projects.FoundryModelWarning", "azure.ai.projects.models.FunctionShellToolParam": "OpenAI.FunctionShellToolParam", "azure.ai.projects.models.FunctionShellToolParamEnvironmentContainerReferenceParam": "OpenAI.FunctionShellToolParamEnvironmentContainerReferenceParam", "azure.ai.projects.models.FunctionShellToolParamEnvironmentLocalEnvironmentParam": "OpenAI.FunctionShellToolParamEnvironmentLocalEnvironmentParam", "azure.ai.projects.models.FunctionTool": "OpenAI.FunctionTool", + "azure.ai.projects.models.RoutineTrigger": "Azure.AI.Projects.RoutineTrigger", + "azure.ai.projects.models.GitHubIssueOpenedRoutineTrigger": "Azure.AI.Projects.GitHubIssueOpenedRoutineTrigger", + "azure.ai.projects.models.HeaderIsolationKeySource": "Azure.AI.Projects.HeaderIsolationKeySource", "azure.ai.projects.models.TelemetryEndpointAuth": "Azure.AI.Projects.TelemetryEndpointAuth", "azure.ai.projects.models.HeaderTelemetryEndpointAuth": "Azure.AI.Projects.HeaderTelemetryEndpointAuth", "azure.ai.projects.models.HostedAgentDefinition": "Azure.AI.Projects.HostedAgentDefinition", @@ -168,8 +189,15 @@ "azure.ai.projects.models.InsightScheduleTask": "Azure.AI.Projects.InsightScheduleTask", "azure.ai.projects.models.InsightsMetadata": "Azure.AI.Projects.InsightsMetadata", "azure.ai.projects.models.InsightSummary": "Azure.AI.Projects.InsightSummary", + "azure.ai.projects.models.RoutineDispatchPayload": "Azure.AI.Projects.RoutineDispatchPayload", + "azure.ai.projects.models.InvokeAgentInvocationsApiDispatchPayload": "Azure.AI.Projects.InvokeAgentInvocationsApiDispatchPayload", + "azure.ai.projects.models.RoutineAction": "Azure.AI.Projects.RoutineAction", + "azure.ai.projects.models.InvokeAgentInvocationsApiRoutineAction": "Azure.AI.Projects.InvokeAgentInvocationsApiRoutineAction", + "azure.ai.projects.models.InvokeAgentResponsesApiDispatchPayload": "Azure.AI.Projects.InvokeAgentResponsesApiDispatchPayload", + "azure.ai.projects.models.InvokeAgentResponsesApiRoutineAction": "Azure.AI.Projects.InvokeAgentResponsesApiRoutineAction", "azure.ai.projects.models.LocalShellToolParam": "OpenAI.LocalShellToolParam", "azure.ai.projects.models.LocalSkillParam": "OpenAI.LocalSkillParam", + "azure.ai.projects.models.LoraConfig": "Azure.AI.Projects.LoraConfig", "azure.ai.projects.models.ManagedAgentIdentityBlueprintReference": "Azure.AI.Projects.ManagedAgentIdentityBlueprintReference", "azure.ai.projects.models.ManagedAzureAISearchIndex": "Azure.AI.Projects.ManagedAzureAISearchIndex", "azure.ai.projects.models.MCPTool": "OpenAI.MCPTool", @@ -189,9 +217,14 @@ "azure.ai.projects.models.MemoryStoreUpdateCompletedResult": "Azure.AI.Projects.MemoryStoreUpdateCompletedResult", "azure.ai.projects.models.MemoryStoreUpdateResult": "Azure.AI.Projects.MemoryStoreUpdateResponse", "azure.ai.projects.models.MicrosoftFabricPreviewTool": "Azure.AI.Projects.MicrosoftFabricPreviewTool", + "azure.ai.projects.models.ModelCredentialRequest": "Azure.AI.Projects.ModelCredentialRequest", "azure.ai.projects.models.ModelDeployment": "Azure.AI.Projects.ModelDeployment", "azure.ai.projects.models.ModelDeploymentSku": "Azure.AI.Projects.Sku", + "azure.ai.projects.models.ModelPendingUploadRequest": "Azure.AI.Projects.ModelPendingUploadRequest", + "azure.ai.projects.models.ModelPendingUploadResponse": "Azure.AI.Projects.ModelPendingUploadResponse", "azure.ai.projects.models.ModelSamplingParams": "Azure.AI.Projects.ModelSamplingParams", + "azure.ai.projects.models.ModelSourceData": "Azure.AI.Projects.ModelSourceData", + "azure.ai.projects.models.ModelVersion": "Azure.AI.Projects.ModelVersion", "azure.ai.projects.models.MonthlyRecurrenceSchedule": "Azure.AI.Projects.MonthlyRecurrenceSchedule", "azure.ai.projects.models.NoAuthenticationCredentials": "Azure.AI.Projects.NoAuthenticationCredentials", "azure.ai.projects.models.OneTimeTrigger": "Azure.AI.Projects.OneTimeTrigger", @@ -204,10 +237,20 @@ "azure.ai.projects.models.OpenApiProjectConnectionAuthDetails": "Azure.AI.Projects.OpenApiProjectConnectionAuthDetails", "azure.ai.projects.models.OpenApiProjectConnectionSecurityScheme": "Azure.AI.Projects.OpenApiProjectConnectionSecurityScheme", "azure.ai.projects.models.OpenApiTool": "Azure.AI.Projects.OpenApiTool", + "azure.ai.projects.models.OptimizationAgentDefinition": "Azure.AI.Projects.OptimizationAgentDefinition", + "azure.ai.projects.models.OptimizationAgentSkill": "Azure.AI.Projects.OptimizationAgentSkill", + "azure.ai.projects.models.OptimizationCandidate": "Azure.AI.Projects.OptimizationCandidate", + "azure.ai.projects.models.OptimizationJob": "Azure.AI.Projects.OptimizationJob", + "azure.ai.projects.models.OptimizationJobInputs": "Azure.AI.Projects.OptimizationJobInputs", + "azure.ai.projects.models.OptimizationJobProgress": "Azure.AI.Projects.OptimizationJobProgress", + "azure.ai.projects.models.OptimizationJobResult": "Azure.AI.Projects.OptimizationJobResult", + "azure.ai.projects.models.OptimizationOptions": "Azure.AI.Projects.OptimizationOptions", + "azure.ai.projects.models.OptimizationTaskResult": "Azure.AI.Projects.OptimizationTaskResult", "azure.ai.projects.models.TelemetryEndpoint": "Azure.AI.Projects.TelemetryEndpoint", "azure.ai.projects.models.OtlpTelemetryEndpoint": "Azure.AI.Projects.OtlpTelemetryEndpoint", "azure.ai.projects.models.PendingUploadRequest": "Azure.AI.Projects.PendingUploadRequest", "azure.ai.projects.models.PendingUploadResult": "Azure.AI.Projects.PendingUploadResponse", + "azure.ai.projects.models.ProceduralMemoryItem": "Azure.AI.Projects.ProceduralMemoryItem", "azure.ai.projects.models.PromptAgentDefinition": "Azure.AI.Projects.PromptAgentDefinition", "azure.ai.projects.models.PromptAgentDefinitionTextOptions": "Azure.AI.Projects.PromptAgentDefinitionTextOptions", "azure.ai.projects.models.PromptBasedEvaluatorDefinition": "Azure.AI.Projects.PromptBasedEvaluatorDefinition", @@ -221,10 +264,13 @@ "azure.ai.projects.models.RedTeam": "Azure.AI.Projects.RedTeam", "azure.ai.projects.models.ResponseUsageInputTokensDetails": "OpenAI.ResponseUsageInputTokensDetails", "azure.ai.projects.models.ResponseUsageOutputTokensDetails": "OpenAI.ResponseUsageOutputTokensDetails", + "azure.ai.projects.models.Routine": "Azure.AI.Projects.Routine", + "azure.ai.projects.models.RoutineRun": "Azure.AI.Projects.RoutineRun", + "azure.ai.projects.models.RoutineRunDiagnostics": "Azure.AI.Projects.RoutineRunDiagnostics", "azure.ai.projects.models.RubricBasedEvaluatorDefinition": "Azure.AI.Projects.RubricBasedEvaluatorDefinition", - "azure.ai.projects.models.RubricCriterion": "Azure.AI.Projects.RubricCriterion", "azure.ai.projects.models.SASCredentials": "Azure.AI.Projects.SASCredentials", "azure.ai.projects.models.Schedule": "Azure.AI.Projects.Schedule", + "azure.ai.projects.models.ScheduleRoutineTrigger": "Azure.AI.Projects.ScheduleRoutineTrigger", "azure.ai.projects.models.ScheduleRun": "Azure.AI.Projects.ScheduleRun", "azure.ai.projects.models.SessionDirectoryEntry": "Azure.AI.Projects.SessionDirectoryEntry", "azure.ai.projects.models.SessionDirectoryListResult": "Azure.AI.Projects.SessionDirectoryListResponse", @@ -240,6 +286,7 @@ "azure.ai.projects.models.SpecificFunctionShellParam": "OpenAI.SpecificFunctionShellParam", "azure.ai.projects.models.StructuredInputDefinition": "Azure.AI.Projects.StructuredInputDefinition", "azure.ai.projects.models.StructuredOutputDefinition": "Azure.AI.Projects.StructuredOutputDefinition", + "azure.ai.projects.models.SystemDataV3": "Azure.AI.Projects.SystemDataV3", "azure.ai.projects.models.TaxonomyCategory": "Azure.AI.Projects.TaxonomyCategory", "azure.ai.projects.models.TaxonomySubCategory": "Azure.AI.Projects.TaxonomySubCategory", "azure.ai.projects.models.TelemetryConfig": "Azure.AI.Projects.TelemetryConfig", @@ -247,6 +294,7 @@ "azure.ai.projects.models.TextResponseFormatJsonObject": "OpenAI.TextResponseFormatConfigurationResponseFormatJsonObject", "azure.ai.projects.models.TextResponseFormatJsonSchema": "OpenAI.TextResponseFormatJsonSchema", "azure.ai.projects.models.TextResponseFormatText": "OpenAI.TextResponseFormatConfigurationResponseFormatText", + "azure.ai.projects.models.TimerRoutineTrigger": "Azure.AI.Projects.TimerRoutineTrigger", "azure.ai.projects.models.ToolboxObject": "Azure.AI.Projects.ToolboxObject", "azure.ai.projects.models.ToolboxPolicies": "Azure.AI.Projects.ToolboxPolicies", "azure.ai.projects.models.ToolboxSearchPreviewTool": "Azure.AI.Projects.ToolboxSearchPreviewTool", @@ -261,12 +309,14 @@ "azure.ai.projects.models.ToolChoiceMCP": "OpenAI.ToolChoiceMCP", "azure.ai.projects.models.ToolChoiceWebSearchPreview": "OpenAI.ToolChoiceWebSearchPreview", "azure.ai.projects.models.ToolChoiceWebSearchPreview20250311": "OpenAI.ToolChoiceWebSearchPreview20250311", + "azure.ai.projects.models.ToolConfig": "Azure.AI.Projects.ToolConfig", "azure.ai.projects.models.ToolDescription": "Azure.AI.Projects.ToolDescription", "azure.ai.projects.models.ToolProjectConnection": "Azure.AI.Projects.ToolProjectConnection", "azure.ai.projects.models.ToolUseFineTuningDataGenerationJobOptions": "Azure.AI.Projects.ToolUseFineTuningDataGenerationJobOptions", "azure.ai.projects.models.TracesDataGenerationJobOptions": "Azure.AI.Projects.TracesDataGenerationJobOptions", "azure.ai.projects.models.TracesDataGenerationJobSource": "Azure.AI.Projects.TracesDataGenerationJobSource", "azure.ai.projects.models.TracesEvaluatorGenerationJobSource": "Azure.AI.Projects.TracesEvaluatorGenerationJobSource", + "azure.ai.projects.models.UpdateModelVersionRequest": "Azure.AI.Projects.UpdateModelVersionRequest", "azure.ai.projects.models.UpdateToolboxRequest": "Azure.AI.Projects.UpdateToolboxRequest", "azure.ai.projects.models.UserProfileMemoryItem": "Azure.AI.Projects.UserProfileMemoryItem", "azure.ai.projects.models.VersionIndicator": "Azure.AI.Projects.VersionIndicator", @@ -309,10 +359,15 @@ "azure.ai.projects.models.VersionSelectorType": "Azure.AI.Projects.VersionSelectorType", "azure.ai.projects.models.AgentEndpointProtocol": "Azure.AI.Projects.AgentEndpointProtocol", "azure.ai.projects.models.AgentEndpointAuthorizationSchemeType": "Azure.AI.Projects.AgentEndpointAuthorizationSchemeType", + "azure.ai.projects.models.IsolationKeySourceKind": "Azure.AI.Projects.IsolationKeySourceKind", "azure.ai.projects.models.VersionIndicatorType": "Azure.AI.Projects.VersionIndicatorType", "azure.ai.projects.models.AgentSessionStatus": "Azure.AI.Projects.AgentSessionStatus", "azure.ai.projects.models.PageOrder": "Azure.AI.Projects.PageOrder", "azure.ai.projects.models.SessionLogEventType": "Azure.AI.Projects.SessionLogEventType", + "azure.ai.projects.models.EvalRunOutputItemResultStatus": "Azure.AI.Projects.EvalRunOutputItemResultStatus", + "azure.ai.projects.models.OptimizationStrategy": "Azure.AI.Projects.OptimizationStrategy", + "azure.ai.projects.models.OptimizationMode": "Azure.AI.Projects.OptimizationMode", + "azure.ai.projects.models.JobStatus": "Azure.AI.Projects.JobStatus", "azure.ai.projects.models.EvaluationTaxonomyInputType": "Azure.AI.Projects.EvaluationTaxonomyInputType", "azure.ai.projects.models.RiskCategory": "Azure.AI.Projects.RiskCategory", "azure.ai.projects.models.EvaluatorType": "Azure.AI.Projects.EvaluatorType", @@ -320,8 +375,8 @@ "azure.ai.projects.models.EvaluatorDefinitionType": "Azure.AI.Projects.EvaluatorDefinitionType", "azure.ai.projects.models.EvaluatorMetricType": "Azure.AI.Projects.EvaluatorMetricType", "azure.ai.projects.models.EvaluatorMetricDirection": "Azure.AI.Projects.EvaluatorMetricDirection", + "azure.ai.projects.models.PendingUploadType": "Azure.AI.Projects.PendingUploadType", "azure.ai.projects.models.EvaluatorGenerationJobSourceType": "Azure.AI.Projects.EvaluatorGenerationJobSourceType", - "azure.ai.projects.models.JobStatus": "Azure.AI.Projects.JobStatus", "azure.ai.projects.models.OperationState": "Azure.Core.Foundations.OperationState", "azure.ai.projects.models.InsightType": "Azure.AI.Projects.InsightType", "azure.ai.projects.models.SampleType": "Azure.AI.Projects.SampleType", @@ -330,7 +385,17 @@ "azure.ai.projects.models.MemoryStoreKind": "Azure.AI.Projects.MemoryStoreKind", "azure.ai.projects.models.MemoryItemKind": "Azure.AI.Projects.MemoryItemKind", "azure.ai.projects.models.MemoryOperationKind": "Azure.AI.Projects.MemoryOperationKind", + "azure.ai.projects.models.FoundryModelWeightType": "Azure.AI.Projects.FoundryModelWeightType", + "azure.ai.projects.models.FoundryModelSourceType": "Azure.AI.Projects.FoundryModelSourceType", + "azure.ai.projects.models.FoundryModelArtifactProfileCategory": "Azure.AI.Projects.FoundryModelArtifactProfileCategory", + "azure.ai.projects.models.FoundryModelArtifactProfileSignal": "Azure.AI.Projects.FoundryModelArtifactProfileSignal", + "azure.ai.projects.models.FoundryModelWarningCode": "Azure.AI.Projects.FoundryModelWarningCode", "azure.ai.projects.models.AttackStrategy": "Azure.AI.Projects.AttackStrategy", + "azure.ai.projects.models.RoutineTriggerType": "Azure.AI.Projects.RoutineTriggerType", + "azure.ai.projects.models.RoutineActionType": "Azure.AI.Projects.RoutineActionType", + "azure.ai.projects.models.RoutineRunPhase": "Azure.AI.Projects.RoutineRunPhase", + "azure.ai.projects.models.RoutineAttemptSource": "Azure.AI.Projects.RoutineAttemptSource", + "azure.ai.projects.models.RoutineDispatchPayloadType": "Azure.AI.Projects.RoutineDispatchPayloadType", "azure.ai.projects.models.ScheduleProvisioningStatus": "Azure.AI.Projects.ScheduleProvisioningStatus", "azure.ai.projects.models.TriggerType": "Azure.AI.Projects.TriggerType", "azure.ai.projects.models.RecurrenceType": "Azure.AI.Projects.RecurrenceType", @@ -346,7 +411,6 @@ "azure.ai.projects.models.ConnectionType": "Azure.AI.Projects.ConnectionType", "azure.ai.projects.models.CredentialType": "Azure.AI.Projects.CredentialType", "azure.ai.projects.models.DatasetType": "Azure.AI.Projects.DatasetType", - "azure.ai.projects.models.PendingUploadType": "Azure.AI.Projects.PendingUploadType", "azure.ai.projects.models.DeploymentType": "Azure.AI.Projects.DeploymentType", "azure.ai.projects.models.IndexType": "Azure.AI.Projects.IndexType", "azure.ai.projects.models.MemoryStoreUpdateStatus": "Azure.AI.Projects.MemoryStoreUpdateStatus", diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/_utils/utils.py b/sdk/ai/azure-ai-projects/azure/ai/projects/_utils/utils.py index 74ca7f7b13ba..a25abbf8a518 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/_utils/utils.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/_utils/utils.py @@ -10,6 +10,7 @@ from .._utils.model_base import Model, SdkJSONEncoder + # file-like tuple could be `(filename, IO (or bytes))` or `(filename, IO (or bytes), content_type)` FileContent = Union[str, bytes, IO[str], IO[bytes]] diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py index 98ac9d539ab0..601211b35c2d 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_operations.py @@ -45,19 +45,26 @@ build_agents_get_version_request, build_agents_list_request, build_agents_list_versions_request, - build_beta_agents_create_agent_version_from_code_request, + build_beta_agents_cancel_optimization_job_request, + build_beta_agents_create_optimization_job_request, build_beta_agents_create_session_request, + build_beta_agents_create_version_from_code_request, + build_beta_agents_delete_optimization_job_request, build_beta_agents_delete_session_file_request, build_beta_agents_delete_session_request, build_beta_agents_download_agent_code_request, - build_beta_agents_download_agent_version_code_request, build_beta_agents_download_session_file_request, + build_beta_agents_get_optimization_candidate_config_request, + build_beta_agents_get_optimization_candidate_request, + build_beta_agents_get_optimization_candidate_results_request, + build_beta_agents_get_optimization_job_request, build_beta_agents_get_session_files_request, build_beta_agents_get_session_log_stream_request, build_beta_agents_get_session_request, + build_beta_agents_list_optimization_candidates_request, + build_beta_agents_list_optimization_jobs_request, build_beta_agents_list_sessions_request, build_beta_agents_patch_agent_details_request, - build_beta_agents_update_agent_from_code_request, build_beta_agents_upload_session_file_request, build_beta_datasets_cancel_generation_job_request, build_beta_datasets_create_generation_job_request, @@ -74,26 +81,49 @@ build_beta_evaluators_create_version_request, build_beta_evaluators_delete_generation_job_request, build_beta_evaluators_delete_version_request, + build_beta_evaluators_get_credentials_request, build_beta_evaluators_get_generation_job_request, build_beta_evaluators_get_version_request, build_beta_evaluators_list_generation_jobs_request, build_beta_evaluators_list_request, build_beta_evaluators_list_versions_request, + build_beta_evaluators_pending_upload_request, build_beta_evaluators_update_version_request, build_beta_insights_generate_request, build_beta_insights_get_request, build_beta_insights_list_request, + build_beta_memory_stores_create_memory_request, build_beta_memory_stores_create_request, + build_beta_memory_stores_delete_memory_request, build_beta_memory_stores_delete_request, build_beta_memory_stores_delete_scope_request, + build_beta_memory_stores_get_memory_request, build_beta_memory_stores_get_request, + build_beta_memory_stores_list_memories_request, build_beta_memory_stores_list_request, build_beta_memory_stores_search_memories_request, build_beta_memory_stores_update_memories_request, + build_beta_memory_stores_update_memory_request, build_beta_memory_stores_update_request, + build_beta_models_create_async_request, + build_beta_models_delete_request, + build_beta_models_get_credentials_request, + build_beta_models_get_request, + build_beta_models_list_request, + build_beta_models_list_versions_request, + build_beta_models_pending_upload_request, + build_beta_models_update_request, build_beta_red_teams_create_request, build_beta_red_teams_get_request, build_beta_red_teams_list_request, + build_beta_routines_create_or_update_request, + build_beta_routines_delete_request, + build_beta_routines_disable_request, + build_beta_routines_dispatch_async_request, + build_beta_routines_enable_request, + build_beta_routines_get_request, + build_beta_routines_list_request, + build_beta_routines_list_runs_request, build_beta_schedules_create_or_update_request, build_beta_schedules_delete_request, build_beta_schedules_get_request, @@ -170,7 +200,9 @@ def __init__(self, *args, **kwargs) -> None: self.evaluators = BetaEvaluatorsOperations(self._client, self._config, self._serialize, self._deserialize) self.insights = BetaInsightsOperations(self._client, self._config, self._serialize, self._deserialize) self.memory_stores = BetaMemoryStoresOperations(self._client, self._config, self._serialize, self._deserialize) + self.models = BetaModelsOperations(self._client, self._config, self._serialize, self._deserialize) self.red_teams = BetaRedTeamsOperations(self._client, self._config, self._serialize, self._deserialize) + self.routines = BetaRoutinesOperations(self._client, self._config, self._serialize, self._deserialize) self.schedules = BetaSchedulesOperations(self._client, self._config, self._serialize, self._deserialize) self.toolboxes = BetaToolboxesOperations(self._client, self._config, self._serialize, self._deserialize) self.skills = BetaSkillsOperations(self._client, self._config, self._serialize, self._deserialize) @@ -260,11 +292,19 @@ async def get(self, agent_name: str, **kwargs: Any) -> _models.AgentDetails: return deserialized # type: ignore @distributed_trace_async - async def delete(self, agent_name: str, **kwargs: Any) -> _models.DeleteAgentResponse: - """Deletes an agent. + async def delete( + self, agent_name: str, *, force: Optional[bool] = None, **kwargs: Any + ) -> _models.DeleteAgentResponse: + """Deletes an agent. For hosted agents, if any version has active sessions, the request is + rejected with HTTP 409 unless ``force`` is set to true. When force is true, all associated + sessions are cascade-deleted along with the agent and its versions. :param agent_name: The name of the agent to delete. Required. :type agent_name: str + :keyword force: For Hosted Agents, if true, force-deletes the agent even if its versions have + active sessions, cascading deletion to all associated sessions. This value is not relevant for + other Agent types. Defaults to false. Default value is None. + :paramtype force: bool :return: DeleteAgentResponse. The DeleteAgentResponse is compatible with MutableMapping :rtype: ~azure.ai.projects.models.DeleteAgentResponse :raises ~azure.core.exceptions.HttpResponseError: @@ -284,6 +324,7 @@ async def delete(self, agent_name: str, **kwargs: Any) -> _models.DeleteAgentRes _request = build_agents_delete_request( agent_name=agent_name, + force=force, api_version=self._config.api_version, headers=_headers, params=_params, @@ -337,7 +378,7 @@ def list( """Returns the list of all agents. :keyword kind: Filter agents by kind. If not provided, all agents are returned. Known values - are: "prompt", "hosted", and "workflow". Default value is None. + are: "prompt", "hosted", "workflow", and "external". Default value is None. :paramtype kind: str or ~azure.ai.projects.models.AgentKind :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the @@ -901,14 +942,20 @@ async def get_version(self, agent_name: str, agent_version: str, **kwargs: Any) @distributed_trace_async async def delete_version( - self, agent_name: str, agent_version: str, **kwargs: Any + self, agent_name: str, agent_version: str, *, force: Optional[bool] = None, **kwargs: Any ) -> _models.DeleteAgentVersionResponse: - """Deletes a specific version of an agent. + """Deletes a specific version of an agent. For hosted agents, if the version has active sessions, + the request is rejected with HTTP 409 unless ``force`` is set to true. When force is true, all + sessions associated with this version are cascade-deleted. :param agent_name: The name of the agent to delete. Required. :type agent_name: str :param agent_version: The version of the agent to delete. Required. :type agent_version: str + :keyword force: For Hosted Agents, if true, force-deletes the version even if it has active + sessions, cascading deletion to all associated sessions. This value is not relevant for other + Agent types. Defaults to false. Default value is None. + :paramtype force: bool :return: DeleteAgentVersionResponse. The DeleteAgentVersionResponse is compatible with MutableMapping :rtype: ~azure.ai.projects.models.DeleteAgentVersionResponse @@ -930,6 +977,7 @@ async def delete_version( _request = build_agents_delete_version_request( agent_name=agent_name, agent_version=agent_version, + force=force, api_version=self._config.api_version, headers=_headers, params=_params, @@ -3011,7 +3059,7 @@ async def create_or_update( return deserialized # type: ignore -class BetaAgentsOperations: +class BetaAgentsOperations: # pylint: disable=too-many-public-methods """ .. warning:: **DO NOT** instantiate this class directly. @@ -3028,155 +3076,6 @@ def __init__(self, *args, **kwargs) -> None: 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 update_agent_from_code( - self, - agent_name: str, - content: _models.CreateAgentVersionFromCodeContent, - *, - code_zip_sha256: str, - **kwargs: Any - ) -> _models.AgentDetails: - """Updates a code-based agent by uploading new code and creating a new version. If the code and - definition are unchanged (matched by x-ms-code-zip-sha256 header), returns the existing - version. The request body is multipart/form-data with a JSON metadata part and a binary code - part (part order is irrelevant). Maximum upload size is 250 MB. - - :param agent_name: The unique name that identifies the agent. Name can be used to - retrieve/update/delete the agent. - - * Must start and end with alphanumeric characters, - * Can contain hyphens in the middle - * Must not exceed 63 characters. Required. - :type agent_name: str - :param content: Required. - :type content: ~azure.ai.projects.models.CreateAgentVersionFromCodeContent - :keyword code_zip_sha256: SHA-256 hex digest of the uploaded code zip. Used for change - detection (dedup) and integrity verification. Required. - :paramtype code_zip_sha256: str - :return: AgentDetails. The AgentDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentDetails - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def update_agent_from_code( - self, agent_name: str, content: JSON, *, code_zip_sha256: str, **kwargs: Any - ) -> _models.AgentDetails: - """Updates a code-based agent by uploading new code and creating a new version. If the code and - definition are unchanged (matched by x-ms-code-zip-sha256 header), returns the existing - version. The request body is multipart/form-data with a JSON metadata part and a binary code - part (part order is irrelevant). Maximum upload size is 250 MB. - - :param agent_name: The unique name that identifies the agent. Name can be used to - retrieve/update/delete the agent. - - * Must start and end with alphanumeric characters, - * Can contain hyphens in the middle - * Must not exceed 63 characters. Required. - :type agent_name: str - :param content: Required. - :type content: JSON - :keyword code_zip_sha256: SHA-256 hex digest of the uploaded code zip. Used for change - detection (dedup) and integrity verification. Required. - :paramtype code_zip_sha256: str - :return: AgentDetails. The AgentDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentDetails - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def update_agent_from_code( - self, - agent_name: str, - content: Union[_models.CreateAgentVersionFromCodeContent, JSON], - *, - code_zip_sha256: str, - **kwargs: Any - ) -> _models.AgentDetails: - """Updates a code-based agent by uploading new code and creating a new version. If the code and - definition are unchanged (matched by x-ms-code-zip-sha256 header), returns the existing - version. The request body is multipart/form-data with a JSON metadata part and a binary code - part (part order is irrelevant). Maximum upload size is 250 MB. - - :param agent_name: The unique name that identifies the agent. Name can be used to - retrieve/update/delete the agent. - - * Must start and end with alphanumeric characters, - * Can contain hyphens in the middle - * Must not exceed 63 characters. Required. - :type agent_name: str - :param content: Is either a CreateAgentVersionFromCodeContent type or a JSON type. Required. - :type content: ~azure.ai.projects.models.CreateAgentVersionFromCodeContent or JSON - :keyword code_zip_sha256: SHA-256 hex digest of the uploaded code zip. Used for change - detection (dedup) and integrity verification. Required. - :paramtype code_zip_sha256: str - :return: AgentDetails. The AgentDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentDetails - :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.AgentDetails] = kwargs.pop("cls", None) - - _body = content.as_dict() if isinstance(content, _Model) else content - _file_fields: list[str] = ["code"] - _data_fields: list[str] = ["metadata"] - _files = prepare_multipart_form_data(_body, _file_fields, _data_fields) - - _request = build_beta_agents_update_agent_from_code_request( - agent_name=agent_name, - code_zip_sha256=code_zip_sha256, - api_version=self._config.api_version, - files=_files, - 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) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.AgentDetails, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - @overload async def patch_agent_details( self, @@ -3332,7 +3231,7 @@ async def patch_agent_details( return deserialized # type: ignore @overload - async def create_agent_version_from_code( + async def create_version_from_code( self, agent_name: str, content: _models.CreateAgentVersionFromCodeContent, @@ -3340,7 +3239,7 @@ async def create_agent_version_from_code( code_zip_sha256: str, **kwargs: Any ) -> _models.AgentVersionDetails: - """create_agent_version_from_code. + """create_version_from_code. :param agent_name: The unique name that identifies the agent. Name can be used to retrieve/update/delete the agent. @@ -3360,10 +3259,10 @@ async def create_agent_version_from_code( """ @overload - async def create_agent_version_from_code( + async def create_version_from_code( self, agent_name: str, content: JSON, *, code_zip_sha256: str, **kwargs: Any ) -> _models.AgentVersionDetails: - """create_agent_version_from_code. + """create_version_from_code. :param agent_name: The unique name that identifies the agent. Name can be used to retrieve/update/delete the agent. @@ -3383,7 +3282,7 @@ async def create_agent_version_from_code( """ @distributed_trace_async - async def create_agent_version_from_code( + async def create_version_from_code( self, agent_name: str, content: Union[_models.CreateAgentVersionFromCodeContent, JSON], @@ -3391,7 +3290,7 @@ async def create_agent_version_from_code( code_zip_sha256: str, **kwargs: Any ) -> _models.AgentVersionDetails: - """create_agent_version_from_code. + """create_version_from_code. :param agent_name: The unique name that identifies the agent. Name can be used to retrieve/update/delete the agent. @@ -3427,7 +3326,7 @@ async def create_agent_version_from_code( _data_fields: list[str] = ["metadata"] _files = prepare_multipart_form_data(_body, _file_fields, _data_fields) - _request = build_beta_agents_create_agent_version_from_code_request( + _request = build_beta_agents_create_version_from_code_request( agent_name=agent_name, code_zip_sha256=code_zip_sha256, api_version=self._config.api_version, @@ -3472,86 +3371,23 @@ async def create_agent_version_from_code( return deserialized # type: ignore @distributed_trace_async - async def download_agent_version_code( - self, agent_name: str, agent_version: str, **kwargs: Any + async def download_agent_code( + self, agent_name: str, *, agent_version: Optional[str] = None, **kwargs: Any ) -> AsyncIterator[bytes]: - """Download the code zip for a specific version of a code-based hosted agent. Returns the - previously-uploaded zip (``application/zip``). The SHA-256 digest of the returned bytes matches - the ``content_hash`` on the agent version's ``code_configuration``. - - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param agent_version: The version of the agent whose code zip should be downloaded. Required. - :type agent_version: str - :return: AsyncIterator[bytes] - :rtype: AsyncIterator[bytes] - :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[AsyncIterator[bytes]] = kwargs.pop("cls", None) - - _request = build_beta_agents_download_agent_version_code_request( - agent_name=agent_name, - agent_version=agent_version, - 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", 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]: - 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) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore + """Download the code zip for a code-based hosted agent. + Returns the previously-uploaded zip (``application/zip``). - return deserialized # type: ignore + If ``agent_version`` is supplied, returns that version's code zip; otherwise + returns the latest version's code zip. - @distributed_trace_async - async def download_agent_code(self, agent_name: str, **kwargs: Any) -> AsyncIterator[bytes]: - """Download the code zip for the latest version of a code-based hosted agent. Returns the - previously-uploaded zip (``application/zip``). The SHA-256 digest of the returned bytes matches - the ``content_hash`` on the latest version's ``code_configuration``. + The SHA-256 digest of the returned bytes matches the ``content_hash`` on the + resolved version's ``code_configuration``. - :param agent_name: The name of the agent whose latest-version code zip should be downloaded. - Required. + :param agent_name: The name of the agent. Required. :type agent_name: str + :keyword agent_version: The version of the agent whose code zip should be downloaded. + If omitted, the latest version's code zip is returned. Default value is None. + :paramtype agent_version: str :return: AsyncIterator[bytes] :rtype: AsyncIterator[bytes] :raises ~azure.core.exceptions.HttpResponseError: @@ -3571,6 +3407,7 @@ async def download_agent_code(self, agent_name: str, **kwargs: Any) -> AsyncIter _request = build_beta_agents_download_agent_code_request( agent_name=agent_name, + agent_version=agent_version, api_version=self._config.api_version, headers=_headers, params=_params, @@ -3602,6 +3439,7 @@ async def download_agent_code(self, agent_name: str, **kwargs: Any) -> AsyncIter raise HttpResponseError(response=response, model=error) response_headers = {} + response_headers["x-ms-agent-version"] = self._deserialize("str", response.headers.get("x-ms-agent-version")) response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) deserialized = response.iter_bytes() if _decompress else response.iter_raw() @@ -4098,7 +3936,14 @@ async def get_session_log_stream( @distributed_trace_async async def _upload_session_file( - self, agent_name: str, agent_session_id: str, content: bytes, *, path: str, **kwargs: Any + self, + agent_name: str, + agent_session_id: str, + content: bytes, + *, + path: str, + user_isolation_key: Optional[str] = None, + **kwargs: Any ) -> _models.SessionFileWriteResult: """Upload a file to the session sandbox via binary stream. Maximum file size is 50 MB. Uploads exceeding this limit return 413 Payload Too Large. @@ -4112,6 +3957,9 @@ async def _upload_session_file( :keyword path: The destination file path within the sandbox, relative to the session home directory. Required. :paramtype path: str + :keyword user_isolation_key: Opaque per-user isolation key used to scope endpoint-scoped data + (responses, conversations, sessions) to a specific end user. Default value is None. + :paramtype user_isolation_key: str :return: SessionFileWriteResult. The SessionFileWriteResult is compatible with MutableMapping :rtype: ~azure.ai.projects.models.SessionFileWriteResult :raises ~azure.core.exceptions.HttpResponseError: @@ -4136,6 +3984,7 @@ async def _upload_session_file( agent_name=agent_name, agent_session_id=agent_session_id, path=path, + user_isolation_key=user_isolation_key, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -4180,7 +4029,13 @@ async def _upload_session_file( @distributed_trace_async async def download_session_file( - self, agent_name: str, agent_session_id: str, *, path: str, **kwargs: Any + self, + agent_name: str, + agent_session_id: str, + *, + path: str, + user_isolation_key: Optional[str] = None, + **kwargs: Any ) -> AsyncIterator[bytes]: """Download a file from the session sandbox as a binary stream. @@ -4191,6 +4046,9 @@ async def download_session_file( :keyword path: The file path to download from the sandbox, relative to the session home directory. Required. :paramtype path: str + :keyword user_isolation_key: Opaque per-user isolation key used to scope endpoint-scoped data + (responses, conversations, sessions) to a specific end user. Default value is None. + :paramtype user_isolation_key: str :return: AsyncIterator[bytes] :rtype: AsyncIterator[bytes] :raises ~azure.core.exceptions.HttpResponseError: @@ -4212,6 +4070,7 @@ async def download_session_file( agent_name=agent_name, agent_session_id=agent_session_id, path=path, + user_isolation_key=user_isolation_key, api_version=self._config.api_version, headers=_headers, params=_params, @@ -4251,7 +4110,13 @@ async def download_session_file( @distributed_trace_async async def get_session_files( - self, agent_name: str, agent_session_id: str, *, path: str, **kwargs: Any + self, + agent_name: str, + agent_session_id: str, + *, + path: str, + user_isolation_key: Optional[str] = None, + **kwargs: Any ) -> _models.SessionDirectoryListResult: """List files and directories at a given path in the session sandbox. Returns only the immediate children of the specified directory (non-recursive). @@ -4262,6 +4127,9 @@ async def get_session_files( :type agent_session_id: str :keyword path: The directory path to list, relative to the session home directory. Required. :paramtype path: str + :keyword user_isolation_key: Opaque per-user isolation key used to scope endpoint-scoped data + (responses, conversations, sessions) to a specific end user. Default value is None. + :paramtype user_isolation_key: str :return: SessionDirectoryListResult. The SessionDirectoryListResult is compatible with MutableMapping :rtype: ~azure.ai.projects.models.SessionDirectoryListResult @@ -4284,6 +4152,7 @@ async def get_session_files( agent_name=agent_name, agent_session_id=agent_session_id, path=path, + user_isolation_key=user_isolation_key, api_version=self._config.api_version, headers=_headers, params=_params, @@ -4326,7 +4195,14 @@ async def get_session_files( @distributed_trace_async async def delete_session_file( - self, agent_name: str, agent_session_id: str, *, path: str, recursive: Optional[bool] = None, **kwargs: Any + self, + agent_name: str, + agent_session_id: str, + *, + path: str, + recursive: Optional[bool] = None, + user_isolation_key: Optional[str] = None, + **kwargs: Any ) -> None: """Delete a file or directory from the session sandbox. If ``recursive`` is false (default) and the target is a non-empty directory, the API returns 409 Conflict. @@ -4341,6 +4217,9 @@ async def delete_session_file( :keyword recursive: Whether to recursively delete directory contents. Defaults to false. Default value is None. :paramtype recursive: bool + :keyword user_isolation_key: Opaque per-user isolation key used to scope endpoint-scoped data + (responses, conversations, sessions) to a specific end user. Default value is None. + :paramtype user_isolation_key: str :return: None :rtype: None :raises ~azure.core.exceptions.HttpResponseError: @@ -4363,6 +4242,7 @@ async def delete_session_file( agent_session_id=agent_session_id, path=path, recursive=recursive, + user_isolation_key=user_isolation_key, api_version=self._config.api_version, headers=_headers, params=_params, @@ -4390,36 +4270,184 @@ async def delete_session_file( if cls: return cls(pipeline_response, None, {}) # type: ignore + @overload + async def create_optimization_job( + self, + job: _models.OptimizationJob, + *, + operation_id: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.OptimizationJob: + """Creates an agent optimization job. -class BetaEvaluationTaxonomiesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. + Create an optimization job. Returns 201 with the queued job. Honours ``Operation-Id`` for + idempotent retry. - Instead, you should access the following operations through - :class:`~azure.ai.projects.aio.AIProjectClient`'s - :attr:`evaluation_taxonomies` attribute. - """ + :param job: The job to create. Required. + :type job: ~azure.ai.projects.models.OptimizationJob + :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the + server creates the job unconditionally. Default value is None. + :paramtype operation_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: OptimizationJob. The OptimizationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.OptimizationJob + :raises ~azure.core.exceptions.HttpResponseError: + """ - 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: AIProjectClientConfiguration = 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_optimization_job( + self, job: JSON, *, operation_id: Optional[str] = None, content_type: str = "application/json", **kwargs: Any + ) -> _models.OptimizationJob: + """Creates an agent optimization job. - @distributed_trace_async - async def get(self, name: str, **kwargs: Any) -> _models.EvaluationTaxonomy: - """Get an evaluation run by name. + Create an optimization job. Returns 201 with the queued job. Honours ``Operation-Id`` for + idempotent retry. - :param name: The name of the resource. Required. - :type name: str - :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationTaxonomy - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, + :param job: The job to create. Required. + :type job: JSON + :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the + server creates the job unconditionally. Default value is None. + :paramtype operation_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: OptimizationJob. The OptimizationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.OptimizationJob + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_optimization_job( + self, + job: IO[bytes], + *, + operation_id: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.OptimizationJob: + """Creates an agent optimization job. + + Create an optimization job. Returns 201 with the queued job. Honours ``Operation-Id`` for + idempotent retry. + + :param job: The job to create. Required. + :type job: IO[bytes] + :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the + server creates the job unconditionally. Default value is None. + :paramtype operation_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: OptimizationJob. The OptimizationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.OptimizationJob + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_optimization_job( + self, job: Union[_models.OptimizationJob, JSON, IO[bytes]], *, operation_id: Optional[str] = None, **kwargs: Any + ) -> _models.OptimizationJob: + """Creates an agent optimization job. + + Create an optimization job. Returns 201 with the queued job. Honours ``Operation-Id`` for + idempotent retry. + + :param job: The job to create. Is one of the following types: OptimizationJob, JSON, IO[bytes] + Required. + :type job: ~azure.ai.projects.models.OptimizationJob or JSON or IO[bytes] + :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the + server creates the job unconditionally. Default value is None. + :paramtype operation_id: str + :return: OptimizationJob. The OptimizationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.OptimizationJob + :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.OptimizationJob] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(job, (IOBase, bytes)): + _content = job + else: + _content = json.dumps(job, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_beta_agents_create_optimization_job_request( + operation_id=operation_id, + 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 [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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.OptimizationJob, response.json()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_optimization_job(self, job_id: str, **kwargs: Any) -> _models.OptimizationJob: + """Get info about an agent optimization job. + + Get an optimization job by id. Emits ``Retry-After`` while the job is non-terminal. + + :param job_id: The ID of the job. Required. + :type job_id: str + :return: OptimizationJob. The OptimizationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.OptimizationJob + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, @@ -4429,10 +4457,10 @@ async def get(self, name: str, **kwargs: Any) -> _models.EvaluationTaxonomy: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.EvaluationTaxonomy] = kwargs.pop("cls", None) + cls: ClsType[_models.OptimizationJob] = kwargs.pop("cls", None) - _request = build_beta_evaluation_taxonomies_get_request( - name=name, + _request = build_beta_agents_get_optimization_job_request( + job_id=job_id, api_version=self._config.api_version, headers=_headers, params=_params, @@ -4457,36 +4485,68 @@ async def get(self, name: str, **kwargs: Any) -> _models.EvaluationTaxonomy: except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.EvaluationTaxonomy, response.json()) + deserialized = _deserialize(_models.OptimizationJob, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore @distributed_trace - def list( - self, *, input_name: Optional[str] = None, input_type: Optional[str] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.EvaluationTaxonomy"]: - """List evaluation taxonomies. + def list_optimization_jobs( + self, + *, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + before: Optional[str] = None, + status: Optional[Union[str, _models.JobStatus]] = None, + agent_name: Optional[str] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.OptimizationJob"]: + """Returns a list of agent optimization jobs. - :keyword input_name: Filter by the evaluation input name. Default value is None. - :paramtype input_name: str - :keyword input_type: Filter by taxonomy input type. Default value is None. - :paramtype input_type: str - :return: An iterator like instance of EvaluationTaxonomy - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.EvaluationTaxonomy] + List optimization jobs. Supports cursor pagination and optional ``status`` / ``agent_name`` + filters. + + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :keyword status: Filter to jobs in this lifecycle state. Known values are: "queued", + "in_progress", "succeeded", "failed", and "cancelled". Default value is None. + :paramtype status: str or ~azure.ai.projects.models.JobStatus + :keyword agent_name: Filter to jobs targeting this agent name. Default value is None. + :paramtype agent_name: str + :return: An iterator like instance of OptimizationJob + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.OptimizationJob] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.EvaluationTaxonomy]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.OptimizationJob]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -4496,60 +4556,37 @@ def list( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: - - _request = build_beta_evaluation_taxonomies_list_request( - input_name=input_name, - input_type=input_type, - 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, - headers=_headers, - ) - 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) + def prepare_request(_continuation_token=None): + _request = build_beta_agents_list_optimization_jobs_request( + limit=limit, + order=order, + after=_continuation_token, + before=before, + status=status, + agent_name=agent_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) return _request async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() list_of_elem = _deserialize( - List[_models.EvaluationTaxonomy], - deserialized.get("value", []), + List[_models.OptimizationJob], + deserialized.get("data", []), ) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + return deserialized.get("last_id") or None, AsyncList(list_of_elem) - async def get_next(next_link=None): - _request = prepare_request(next_link) + async def get_next(_continuation_token=None): + _request = prepare_request(_continuation_token) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access @@ -4559,20 +4596,26 @@ async def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) return pipeline_response return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def delete(self, name: str, **kwargs: Any) -> None: - """Delete an evaluation taxonomy by name. + async def cancel_optimization_job(self, job_id: str, **kwargs: Any) -> _models.OptimizationJob: + """Cancels an agent optimization job. - :param name: The name of the resource. Required. - :type name: str - :return: None - :rtype: None + Request cancellation. Idempotent on terminal states. + + :param job_id: The ID of the job to cancel. Required. + :type job_id: str + :return: OptimizationJob. The OptimizationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.OptimizationJob :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4586,10 +4629,10 @@ async def delete(self, name: str, **kwargs: Any) -> None: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models.OptimizationJob] = kwargs.pop("cls", None) - _request = build_beta_evaluation_taxonomies_delete_request( - name=name, + _request = build_beta_agents_cancel_optimization_job_request( + job_id=job_id, api_version=self._config.api_version, headers=_headers, params=_params, @@ -4599,87 +4642,131 @@ async def delete(self, name: str, **kwargs: Any) -> None: } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 [204]: + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.OptimizationJob, response.json()) if cls: - return cls(pipeline_response, None, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - @overload - async def create( - self, name: str, taxonomy: _models.EvaluationTaxonomy, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationTaxonomy: - """Create an evaluation taxonomy. + return deserialized # type: ignore - :param name: The name of the evaluation taxonomy. Required. - :type name: str - :param taxonomy: The evaluation taxonomy. Required. - :type taxonomy: ~azure.ai.projects.models.EvaluationTaxonomy - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationTaxonomy - :raises ~azure.core.exceptions.HttpResponseError: - """ + @distributed_trace_async + async def delete_optimization_job(self, job_id: str, **kwargs: Any) -> None: + """Deletes an agent optimization job. - @overload - async def create( - self, name: str, taxonomy: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationTaxonomy: - """Create an evaluation taxonomy. + Delete the job and its candidate artifacts. Cancels first if non-terminal. - :param name: The name of the evaluation taxonomy. Required. - :type name: str - :param taxonomy: The evaluation taxonomy. Required. - :type taxonomy: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationTaxonomy + :param job_id: The ID of the job to delete. Required. + :type job_id: str + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) - @overload - async def create( - self, name: str, taxonomy: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationTaxonomy: - """Create an evaluation taxonomy. + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - :param name: The name of the evaluation taxonomy. Required. - :type name: str - :param taxonomy: The evaluation taxonomy. Required. - :type taxonomy: 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: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationTaxonomy - :raises ~azure.core.exceptions.HttpResponseError: - """ + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_beta_agents_delete_optimization_job_request( + job_id=job_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) + + _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 [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async - async def create( - self, name: str, taxonomy: Union[_models.EvaluationTaxonomy, JSON, IO[bytes]], **kwargs: Any - ) -> _models.EvaluationTaxonomy: - """Create an evaluation taxonomy. + async def list_optimization_candidates( + self, + job_id: str, + *, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + after: Optional[str] = None, + before: Optional[str] = None, + **kwargs: Any + ) -> _models.AgentsPagedResultOptimizationCandidate: + """Returns a list of candidates for an optimization job. - :param name: The name of the evaluation taxonomy. Required. - :type name: str - :param taxonomy: The evaluation taxonomy. Is one of the following types: EvaluationTaxonomy, - JSON, IO[bytes] Required. - :type taxonomy: ~azure.ai.projects.models.EvaluationTaxonomy or JSON or IO[bytes] - :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationTaxonomy + List candidates produced by a job. + + :param job_id: The optimization job id. Required. + :type job_id: str + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword after: A cursor for use in pagination. ``after`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include after=obj_foo in order to fetch the next page of the list. Default + value is None. + :paramtype after: str + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :return: AgentsPagedResultOptimizationCandidate. The AgentsPagedResultOptimizationCandidate is + compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentsPagedResultOptimizationCandidate :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4690,24 +4777,18 @@ async def create( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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.EvaluationTaxonomy] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(taxonomy, (IOBase, bytes)): - _content = taxonomy - else: - _content = json.dumps(taxonomy, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + cls: ClsType[_models.AgentsPagedResultOptimizationCandidate] = kwargs.pop("cls", None) - _request = build_beta_evaluation_taxonomies_create_request( - name=name, - content_type=content_type, + _request = build_beta_agents_list_optimization_candidates_request( + job_id=job_id, + limit=limit, + order=order, + after=after, + before=before, api_version=self._config.api_version, - content=_content, headers=_headers, params=_params, ) @@ -4724,92 +4805,43 @@ async def create( 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 except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.EvaluationTaxonomy, response.json()) + deserialized = _deserialize(_models.AgentsPagedResultOptimizationCandidate, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @overload - async def update( - self, name: str, taxonomy: _models.EvaluationTaxonomy, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationTaxonomy: - """Update an evaluation taxonomy. - - :param name: The name of the evaluation taxonomy. Required. - :type name: str - :param taxonomy: The evaluation taxonomy. Required. - :type taxonomy: ~azure.ai.projects.models.EvaluationTaxonomy - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationTaxonomy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def update( - self, name: str, taxonomy: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationTaxonomy: - """Update an evaluation taxonomy. - - :param name: The name of the evaluation taxonomy. Required. - :type name: str - :param taxonomy: The evaluation taxonomy. Required. - :type taxonomy: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationTaxonomy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def update( - self, name: str, taxonomy: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationTaxonomy: - """Update an evaluation taxonomy. - - :param name: The name of the evaluation taxonomy. Required. - :type name: str - :param taxonomy: The evaluation taxonomy. Required. - :type taxonomy: 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: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationTaxonomy - :raises ~azure.core.exceptions.HttpResponseError: - """ - @distributed_trace_async - async def update( - self, name: str, taxonomy: Union[_models.EvaluationTaxonomy, JSON, IO[bytes]], **kwargs: Any - ) -> _models.EvaluationTaxonomy: - """Update an evaluation taxonomy. + async def get_optimization_candidate( + self, job_id: str, candidate_id: str, **kwargs: Any + ) -> _models.OptimizationCandidate: + """Get a candidate by id. - :param name: The name of the evaluation taxonomy. Required. - :type name: str - :param taxonomy: The evaluation taxonomy. Is one of the following types: EvaluationTaxonomy, - JSON, IO[bytes] Required. - :type taxonomy: ~azure.ai.projects.models.EvaluationTaxonomy or JSON or IO[bytes] - :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationTaxonomy + Get a single candidate manifest and aggregated evaluation summary. + + :param job_id: The optimization job id. Required. + :type job_id: str + :param candidate_id: The candidate id. Required. + :type candidate_id: str + :return: OptimizationCandidate. The OptimizationCandidate is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.OptimizationCandidate :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4820,24 +4852,15 @@ async def update( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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.EvaluationTaxonomy] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(taxonomy, (IOBase, bytes)): - _content = taxonomy - else: - _content = json.dumps(taxonomy, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + cls: ClsType[_models.OptimizationCandidate] = kwargs.pop("cls", None) - _request = build_beta_evaluation_taxonomies_update_request( - name=name, - content_type=content_type, + _request = build_beta_agents_get_optimization_candidate_request( + job_id=job_id, + candidate_id=candidate_id, api_version=self._config.api_version, - content=_content, headers=_headers, params=_params, ) @@ -4861,27 +4884,176 @@ async def update( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.EvaluationTaxonomy, response.json()) + deserialized = _deserialize(_models.OptimizationCandidate, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + @distributed_trace_async + async def get_optimization_candidate_config( + self, job_id: str, candidate_id: str, **kwargs: Any + ) -> _models.CandidateDeployConfig: + """Get candidate deploy config. -class BetaEvaluatorsOperations: - """ + Get the candidate's deploy config JSON. Used to compose ``agents.create_version(...)`` from a + candidate. + + :param job_id: The optimization job id. Required. + :type job_id: str + :param candidate_id: The candidate id. Required. + :type candidate_id: str + :return: CandidateDeployConfig. The CandidateDeployConfig is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.CandidateDeployConfig + :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.CandidateDeployConfig] = kwargs.pop("cls", None) + + _request = build_beta_agents_get_optimization_candidate_config_request( + job_id=job_id, + candidate_id=candidate_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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.CandidateDeployConfig, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_optimization_candidate_results( + self, job_id: str, candidate_id: str, **kwargs: Any + ) -> _models.CandidateResults: + """Get candidate evaluation results. + + Get full per-task evaluation results for a candidate. + + :param job_id: The optimization job id. Required. + :type job_id: str + :param candidate_id: The candidate id. Required. + :type candidate_id: str + :return: CandidateResults. The CandidateResults is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.CandidateResults + :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.CandidateResults] = kwargs.pop("cls", None) + + _request = build_beta_agents_get_optimization_candidate_results_request( + job_id=job_id, + candidate_id=candidate_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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.CandidateResults, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class BetaEvaluationTaxonomiesOperations: + """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.ai.projects.aio.AIProjectClient`'s - :attr:`evaluators` attribute. + :attr:`evaluation_taxonomies` attribute. """ def __init__(self, *args, **kwargs) -> None: @@ -4891,34 +5063,85 @@ def __init__(self, *args, **kwargs) -> None: 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_versions( - self, - name: str, - *, - type: Optional[Union[Literal["builtin"], Literal["custom"], Literal["all"], str]] = None, - limit: Optional[int] = None, - **kwargs: Any - ) -> AsyncItemPaged["_models.EvaluatorVersion"]: - """List all versions of the given evaluator. + @distributed_trace_async + async def get(self, name: str, **kwargs: Any) -> _models.EvaluationTaxonomy: + """Get an evaluation run by name. :param name: The name of the resource. Required. :type name: str - :keyword type: Filter evaluators by type. Possible values: 'all', 'custom', 'builtin'. Is one - of the following types: Literal["builtin"], Literal["custom"], Literal["all"], str Default - value is None. - :paramtype type: str or str or str or str - :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and - 100, and the default is 20. Default value is None. - :paramtype limit: int - :return: An iterator like instance of EvaluatorVersion - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.EvaluatorVersion] + :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationTaxonomy :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[List[_models.EvaluatorVersion]] = kwargs.pop("cls", None) + cls: ClsType[_models.EvaluationTaxonomy] = kwargs.pop("cls", None) + + _request = build_beta_evaluation_taxonomies_get_request( + name=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.EvaluationTaxonomy, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, *, input_name: Optional[str] = None, input_type: Optional[str] = None, **kwargs: Any + ) -> AsyncItemPaged["_models.EvaluationTaxonomy"]: + """List evaluation taxonomies. + + :keyword input_name: Filter by the evaluation input name. Default value is None. + :paramtype input_name: str + :keyword input_type: Filter by taxonomy input type. Default value is None. + :paramtype input_type: str + :return: An iterator like instance of EvaluationTaxonomy + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.EvaluationTaxonomy] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.EvaluationTaxonomy]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -4931,10 +5154,9 @@ def list_versions( def prepare_request(next_link=None): if not next_link: - _request = build_beta_evaluators_list_versions_request( - name=name, - type=type, - limit=limit, + _request = build_beta_evaluation_taxonomies_list_request( + input_name=input_name, + input_type=input_type, api_version=self._config.api_version, headers=_headers, params=_params, @@ -4974,7 +5196,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() list_of_elem = _deserialize( - List[_models.EvaluatorVersion], + List[_models.EvaluationTaxonomy], deserialized.get("value", []), ) if cls: @@ -4998,32 +5220,16 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - @distributed_trace - def list( - self, - *, - type: Optional[Union[Literal["builtin"], Literal["custom"], Literal["all"], str]] = None, - limit: Optional[int] = None, - **kwargs: Any - ) -> AsyncItemPaged["_models.EvaluatorVersion"]: - """List the latest version of each evaluator. + @distributed_trace_async + async def delete(self, name: str, **kwargs: Any) -> None: + """Delete an evaluation taxonomy by name. - :keyword type: Filter evaluators by type. Possible values: 'all', 'custom', 'builtin'. Is one - of the following types: Literal["builtin"], Literal["custom"], Literal["all"], str Default - value is None. - :paramtype type: str or str or str or str - :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and - 100, and the default is 20. Default value is None. - :paramtype limit: int - :return: An iterator like instance of EvaluatorVersion - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.EvaluatorVersion] + :param name: The name of the resource. Required. + :type name: str + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.EvaluatorVersion]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -5032,169 +5238,13 @@ def list( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: - - _request = build_beta_evaluators_list_request( - type=type, - limit=limit, - 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, - headers=_headers, - ) - 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.EvaluatorVersion], - 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_version(self, name: str, version: str, **kwargs: Any) -> _models.EvaluatorVersion: - """Get the specific version of the EvaluatorVersion. The service returns 404 Not Found error if - the EvaluatorVersion does not exist. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the EvaluatorVersion to retrieve. Required. - :type version: str - :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorVersion - :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.EvaluatorVersion] = kwargs.pop("cls", None) - - _request = build_beta_evaluators_get_version_request( - name=name, - version=version, - 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.EvaluatorVersion, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete_version(self, name: str, version: str, **kwargs: Any) -> None: - """Delete the specific version of the EvaluatorVersion. The service returns 204 No Content if the - EvaluatorVersion was deleted successfully or if the EvaluatorVersion does not exist. - - :param name: The name of the resource. Required. - :type name: str - :param version: The version of the EvaluatorVersion to delete. Required. - :type version: str - :return: None - :rtype: None - :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 {} + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_beta_evaluators_delete_version_request( + _request = build_beta_evaluation_taxonomies_delete_request( name=name, - version=version, api_version=self._config.api_version, headers=_headers, params=_params, @@ -5219,77 +5269,72 @@ async def delete_version(self, name: str, version: str, **kwargs: Any) -> None: return cls(pipeline_response, None, {}) # type: ignore @overload - async def create_version( - self, - name: str, - evaluator_version: _models.EvaluatorVersion, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.EvaluatorVersion: - """Create a new EvaluatorVersion with auto incremented version id. + async def create( + self, name: str, taxonomy: _models.EvaluationTaxonomy, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluationTaxonomy: + """Create an evaluation taxonomy. - :param name: The name of the resource. Required. + :param name: The name of the evaluation taxonomy. Required. :type name: str - :param evaluator_version: Required. - :type evaluator_version: ~azure.ai.projects.models.EvaluatorVersion + :param taxonomy: The evaluation taxonomy. Required. + :type taxonomy: ~azure.ai.projects.models.EvaluationTaxonomy :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorVersion + :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationTaxonomy :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_version( - self, name: str, evaluator_version: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluatorVersion: - """Create a new EvaluatorVersion with auto incremented version id. + async def create( + self, name: str, taxonomy: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluationTaxonomy: + """Create an evaluation taxonomy. - :param name: The name of the resource. Required. + :param name: The name of the evaluation taxonomy. Required. :type name: str - :param evaluator_version: Required. - :type evaluator_version: JSON + :param taxonomy: The evaluation taxonomy. Required. + :type taxonomy: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorVersion + :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationTaxonomy :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_version( - self, name: str, evaluator_version: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluatorVersion: - """Create a new EvaluatorVersion with auto incremented version id. + async def create( + self, name: str, taxonomy: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluationTaxonomy: + """Create an evaluation taxonomy. - :param name: The name of the resource. Required. + :param name: The name of the evaluation taxonomy. Required. :type name: str - :param evaluator_version: Required. - :type evaluator_version: IO[bytes] + :param taxonomy: The evaluation taxonomy. Required. + :type taxonomy: 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: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorVersion + :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationTaxonomy :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def create_version( - self, name: str, evaluator_version: Union[_models.EvaluatorVersion, JSON, IO[bytes]], **kwargs: Any - ) -> _models.EvaluatorVersion: - """Create a new EvaluatorVersion with auto incremented version id. + async def create( + self, name: str, taxonomy: Union[_models.EvaluationTaxonomy, JSON, IO[bytes]], **kwargs: Any + ) -> _models.EvaluationTaxonomy: + """Create an evaluation taxonomy. - :param name: The name of the resource. Required. + :param name: The name of the evaluation taxonomy. Required. :type name: str - :param evaluator_version: Is one of the following types: EvaluatorVersion, JSON, IO[bytes] - Required. - :type evaluator_version: ~azure.ai.projects.models.EvaluatorVersion or JSON or IO[bytes] - :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorVersion + :param taxonomy: The evaluation taxonomy. Is one of the following types: EvaluationTaxonomy, + JSON, IO[bytes] Required. + :type taxonomy: ~azure.ai.projects.models.EvaluationTaxonomy or JSON or IO[bytes] + :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationTaxonomy :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5304,16 +5349,16 @@ async def create_version( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.EvaluatorVersion] = kwargs.pop("cls", None) + cls: ClsType[_models.EvaluationTaxonomy] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(evaluator_version, (IOBase, bytes)): - _content = evaluator_version + if isinstance(taxonomy, (IOBase, bytes)): + _content = taxonomy else: - _content = json.dumps(evaluator_version, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(taxonomy, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_evaluators_create_version_request( + _request = build_beta_evaluation_taxonomies_create_request( name=name, content_type=content_type, api_version=self._config.api_version, @@ -5334,7 +5379,7 @@ async def create_version( response = pipeline_response.http_response - if response.status_code not in [201]: + if response.status_code not in [200, 201]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -5346,7 +5391,7 @@ async def create_version( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.EvaluatorVersion, response.json()) + deserialized = _deserialize(_models.EvaluationTaxonomy, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -5354,96 +5399,72 @@ async def create_version( return deserialized # type: ignore @overload - async def update_version( - self, - name: str, - version: str, - evaluator_version: _models.EvaluatorVersion, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.EvaluatorVersion: - """Update an existing EvaluatorVersion with the given version id. + async def update( + self, name: str, taxonomy: _models.EvaluationTaxonomy, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluationTaxonomy: + """Update an evaluation taxonomy. - :param name: The name of the resource. Required. + :param name: The name of the evaluation taxonomy. Required. :type name: str - :param version: The version of the EvaluatorVersion to update. Required. - :type version: str - :param evaluator_version: Evaluator resource. Required. - :type evaluator_version: ~azure.ai.projects.models.EvaluatorVersion + :param taxonomy: The evaluation taxonomy. Required. + :type taxonomy: ~azure.ai.projects.models.EvaluationTaxonomy :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorVersion + :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationTaxonomy :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def update_version( - self, name: str, version: str, evaluator_version: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluatorVersion: - """Update an existing EvaluatorVersion with the given version id. + async def update( + self, name: str, taxonomy: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluationTaxonomy: + """Update an evaluation taxonomy. - :param name: The name of the resource. Required. + :param name: The name of the evaluation taxonomy. Required. :type name: str - :param version: The version of the EvaluatorVersion to update. Required. - :type version: str - :param evaluator_version: Evaluator resource. Required. - :type evaluator_version: JSON + :param taxonomy: The evaluation taxonomy. Required. + :type taxonomy: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorVersion + :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationTaxonomy :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def update_version( - self, - name: str, - version: str, - evaluator_version: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.EvaluatorVersion: - """Update an existing EvaluatorVersion with the given version id. + async def update( + self, name: str, taxonomy: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluationTaxonomy: + """Update an evaluation taxonomy. - :param name: The name of the resource. Required. + :param name: The name of the evaluation taxonomy. Required. :type name: str - :param version: The version of the EvaluatorVersion to update. Required. - :type version: str - :param evaluator_version: Evaluator resource. Required. - :type evaluator_version: IO[bytes] + :param taxonomy: The evaluation taxonomy. Required. + :type taxonomy: 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: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorVersion + :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationTaxonomy :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def update_version( - self, - name: str, - version: str, - evaluator_version: Union[_models.EvaluatorVersion, JSON, IO[bytes]], - **kwargs: Any - ) -> _models.EvaluatorVersion: - """Update an existing EvaluatorVersion with the given version id. + async def update( + self, name: str, taxonomy: Union[_models.EvaluationTaxonomy, JSON, IO[bytes]], **kwargs: Any + ) -> _models.EvaluationTaxonomy: + """Update an evaluation taxonomy. - :param name: The name of the resource. Required. + :param name: The name of the evaluation taxonomy. Required. :type name: str - :param version: The version of the EvaluatorVersion to update. Required. - :type version: str - :param evaluator_version: Evaluator resource. Is one of the following types: EvaluatorVersion, + :param taxonomy: The evaluation taxonomy. Is one of the following types: EvaluationTaxonomy, JSON, IO[bytes] Required. - :type evaluator_version: ~azure.ai.projects.models.EvaluatorVersion or JSON or IO[bytes] - :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorVersion + :type taxonomy: ~azure.ai.projects.models.EvaluationTaxonomy or JSON or IO[bytes] + :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationTaxonomy :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5458,18 +5479,17 @@ async def update_version( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.EvaluatorVersion] = kwargs.pop("cls", None) + cls: ClsType[_models.EvaluationTaxonomy] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(evaluator_version, (IOBase, bytes)): - _content = evaluator_version + if isinstance(taxonomy, (IOBase, bytes)): + _content = taxonomy else: - _content = json.dumps(evaluator_version, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(taxonomy, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_evaluators_update_version_request( + _request = build_beta_evaluation_taxonomies_update_request( name=name, - version=version, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -5501,112 +5521,60 @@ async def update_version( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.EvaluatorVersion, response.json()) + deserialized = _deserialize(_models.EvaluationTaxonomy, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @overload - async def create_generation_job( - self, - job: _models.EvaluatorGenerationJob, - *, - operation_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.EvaluatorGenerationJob: - """Creates an evaluator generation job. - - Creates an evaluator generation job. The service generates rubric-based evaluator definitions - from the provided source materials asynchronously. - - :param job: The job to create. Required. - :type job: ~azure.ai.projects.models.EvaluatorGenerationJob - :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the - server creates the job unconditionally. Default value is None. - :paramtype operation_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob - :raises ~azure.core.exceptions.HttpResponseError: - """ - @overload - async def create_generation_job( - self, job: JSON, *, operation_id: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluatorGenerationJob: - """Creates an evaluator generation job. +class BetaEvaluatorsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - Creates an evaluator generation job. The service generates rubric-based evaluator definitions - from the provided source materials asynchronously. + Instead, you should access the following operations through + :class:`~azure.ai.projects.aio.AIProjectClient`'s + :attr:`evaluators` attribute. + """ - :param job: The job to create. Required. - :type job: JSON - :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the - server creates the job unconditionally. Default value is None. - :paramtype operation_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob - :raises ~azure.core.exceptions.HttpResponseError: - """ + 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: AIProjectClientConfiguration = 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_generation_job( + @distributed_trace + def list_versions( self, - job: IO[bytes], + name: str, *, - operation_id: Optional[str] = None, - content_type: str = "application/json", + type: Optional[Union[Literal["builtin"], Literal["custom"], Literal["all"], str]] = None, + limit: Optional[int] = None, **kwargs: Any - ) -> _models.EvaluatorGenerationJob: - """Creates an evaluator generation job. - - Creates an evaluator generation job. The service generates rubric-based evaluator definitions - from the provided source materials asynchronously. + ) -> AsyncItemPaged["_models.EvaluatorVersion"]: + """List all versions of the given evaluator. - :param job: The job to create. Required. - :type job: IO[bytes] - :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the - server creates the job unconditionally. Default value is None. - :paramtype operation_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob + :param name: The name of the resource. Required. + :type name: str + :keyword type: Filter evaluators by type. Possible values: 'all', 'custom', 'builtin'. Is one + of the following types: Literal["builtin"], Literal["custom"], Literal["all"], str Default + value is None. + :paramtype type: str or str or str or str + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. Default value is None. + :paramtype limit: int + :return: An iterator like instance of EvaluatorVersion + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.EvaluatorVersion] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - @distributed_trace_async - async def create_generation_job( - self, - job: Union[_models.EvaluatorGenerationJob, JSON, IO[bytes]], - *, - operation_id: Optional[str] = None, - **kwargs: Any - ) -> _models.EvaluatorGenerationJob: - """Creates an evaluator generation job. - - Creates an evaluator generation job. The service generates rubric-based evaluator definitions - from the provided source materials asynchronously. + cls: ClsType[List[_models.EvaluatorVersion]] = kwargs.pop("cls", None) - :param job: The job to create. Is one of the following types: EvaluatorGenerationJob, JSON, - IO[bytes] Required. - :type job: ~azure.ai.projects.models.EvaluatorGenerationJob or JSON or IO[bytes] - :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the - server creates the job unconditionally. Default value is None. - :paramtype operation_id: str - :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob - :raises ~azure.core.exceptions.HttpResponseError: - """ error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -5615,25 +5583,210 @@ async def create_generation_job( } 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.EvaluatorGenerationJob] = kwargs.pop("cls", None) + def prepare_request(next_link=None): + if not next_link: - content_type = content_type or "application/json" - _content = None - if isinstance(job, (IOBase, bytes)): - _content = job - else: - _content = json.dumps(job, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _request = build_beta_evaluators_list_versions_request( + name=name, + type=type, + limit=limit, + 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) - _request = build_beta_evaluators_create_generation_job_request( - operation_id=operation_id, - content_type=content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, + 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, + headers=_headers, + ) + 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.EvaluatorVersion], + 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 + def list( + self, + *, + type: Optional[Union[Literal["builtin"], Literal["custom"], Literal["all"], str]] = None, + limit: Optional[int] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.EvaluatorVersion"]: + """List the latest version of each evaluator. + + :keyword type: Filter evaluators by type. Possible values: 'all', 'custom', 'builtin'. Is one + of the following types: Literal["builtin"], Literal["custom"], Literal["all"], str Default + value is None. + :paramtype type: str or str or str or str + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. Default value is None. + :paramtype limit: int + :return: An iterator like instance of EvaluatorVersion + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.EvaluatorVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.EvaluatorVersion]] = 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_beta_evaluators_list_request( + type=type, + limit=limit, + 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, + headers=_headers, + ) + 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.EvaluatorVersion], + 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_version(self, name: str, version: str, **kwargs: Any) -> _models.EvaluatorVersion: + """Get the specific version of the EvaluatorVersion. The service returns 404 Not Found error if + the EvaluatorVersion does not exist. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the EvaluatorVersion to retrieve. Required. + :type version: str + :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorVersion + :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.EvaluatorVersion] = kwargs.pop("cls", None) + + _request = build_beta_evaluators_get_version_request( + name=name, + version=version, + api_version=self._config.api_version, + headers=_headers, params=_params, ) path_format_arguments = { @@ -5649,43 +5802,36 @@ async def create_generation_job( response = pipeline_response.http_response - if response.status_code not in [201]: + 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) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.EvaluatorGenerationJob, response.json()) + deserialized = _deserialize(_models.EvaluatorVersion, response.json()) if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore @distributed_trace_async - async def get_generation_job(self, job_id: str, **kwargs: Any) -> _models.EvaluatorGenerationJob: - """Get info about an evaluator generation job. - - Gets the details of an evaluator generation job by its ID. + async def delete_version(self, name: str, version: str, **kwargs: Any) -> None: + """Delete the specific version of the EvaluatorVersion. The service returns 204 No Content if the + EvaluatorVersion was deleted successfully or if the EvaluatorVersion does not exist. - :param job_id: The ID of the job. Required. - :type job_id: str - :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob + :param name: The name of the resource. Required. + :type name: str + :param version: The version of the EvaluatorVersion to delete. Required. + :type version: str + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5699,10 +5845,11 @@ async def get_generation_job(self, job_id: str, **kwargs: Any) -> _models.Evalua _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.EvaluatorGenerationJob] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_beta_evaluators_get_generation_job_request( - job_id=job_id, + _request = build_beta_evaluators_delete_version_request( + name=name, + version=version, api_version=self._config.api_version, headers=_headers, params=_params, @@ -5712,148 +5859,92 @@ async def get_generation_job(self, job_id: str, **kwargs: Any) -> _models.Evalua } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _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 + if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.EvaluatorGenerationJob, response.json()) + raise HttpResponseError(response=response) if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore + return cls(pipeline_response, None, {}) # type: ignore - @distributed_trace - def list_generation_jobs( + @overload + async def create_version( self, + name: str, + evaluator_version: _models.EvaluatorVersion, *, - limit: Optional[int] = None, - order: Optional[Union[str, _models.PageOrder]] = None, - before: Optional[str] = None, - category: Optional[Union[str, _models.EvaluatorCategory]] = None, + content_type: str = "application/json", **kwargs: Any - ) -> AsyncItemPaged["_models.EvaluatorGenerationJob"]: - """Returns a list of evaluator generation jobs. - - Returns a list of evaluator generation jobs. + ) -> _models.EvaluatorVersion: + """Create a new EvaluatorVersion with auto incremented version id. - :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and - 100, and the - default is 20. Default value is None. - :paramtype limit: int - :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for - ascending order and``desc`` - for descending order. Known values are: "asc" and "desc". Default value is None. - :paramtype order: str or ~azure.ai.projects.models.PageOrder - :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your - place in the list. - For instance, if you make a list request and receive 100 objects, ending with obj_foo, your - subsequent call can include before=obj_foo in order to fetch the previous page of the list. - Default value is None. - :paramtype before: str - :keyword category: Filter evaluator generation jobs by category. Known values are: "quality", - "safety", and "agents". Default value is None. - :paramtype category: str or ~azure.ai.projects.models.EvaluatorCategory - :return: An iterator like instance of EvaluatorGenerationJob - :rtype: - ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.EvaluatorGenerationJob] + :param name: The name of the resource. Required. + :type name: str + :param evaluator_version: Required. + :type evaluator_version: ~azure.ai.projects.models.EvaluatorVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorVersion :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.EvaluatorGenerationJob]] = 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(_continuation_token=None): - - _request = build_beta_evaluators_list_generation_jobs_request( - limit=limit, - order=order, - after=_continuation_token, - before=before, - category=category, - 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) - return _request - - async def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize( - List[_models.EvaluatorGenerationJob], - deserialized.get("data", []), - ) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("last_id") or None, AsyncList(list_of_elem) - - async def get_next(_continuation_token=None): - _request = prepare_request(_continuation_token) - _stream = False - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response + @overload + async def create_version( + self, name: str, evaluator_version: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluatorVersion: + """Create a new EvaluatorVersion with auto incremented version id. - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) + :param name: The name of the resource. Required. + :type name: str + :param evaluator_version: Required. + :type evaluator_version: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ - return pipeline_response + @overload + async def create_version( + self, name: str, evaluator_version: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluatorVersion: + """Create a new EvaluatorVersion with auto incremented version id. - return AsyncItemPaged(get_next, extract_data) + :param name: The name of the resource. Required. + :type name: str + :param evaluator_version: Required. + :type evaluator_version: 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: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace_async - async def cancel_generation_job(self, job_id: str, **kwargs: Any) -> _models.EvaluatorGenerationJob: - """Cancels an evaluator generation job. - - Cancels an evaluator generation job by its ID. + async def create_version( + self, name: str, evaluator_version: Union[_models.EvaluatorVersion, JSON, IO[bytes]], **kwargs: Any + ) -> _models.EvaluatorVersion: + """Create a new EvaluatorVersion with auto incremented version id. - :param job_id: The ID of the job to cancel. Required. - :type job_id: str - :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob + :param name: The name of the resource. Required. + :type name: str + :param evaluator_version: Is one of the following types: EvaluatorVersion, JSON, IO[bytes] + Required. + :type evaluator_version: ~azure.ai.projects.models.EvaluatorVersion or JSON or IO[bytes] + :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorVersion :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5864,14 +5955,24 @@ async def cancel_generation_job(self, job_id: str, **kwargs: Any) -> _models.Eva } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.EvaluatorGenerationJob] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.EvaluatorVersion] = kwargs.pop("cls", None) - _request = build_beta_evaluators_cancel_generation_job_request( - job_id=job_id, + content_type = content_type or "application/json" + _content = None + if isinstance(evaluator_version, (IOBase, bytes)): + _content = evaluator_version + else: + _content = json.dumps(evaluator_version, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_beta_evaluators_create_version_request( + name=name, + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -5888,160 +5989,116 @@ async def cancel_generation_job(self, job_id: str, **kwargs: Any) -> _models.Eva response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [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) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) + raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.EvaluatorGenerationJob, response.json()) + deserialized = _deserialize(_models.EvaluatorVersion, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @distributed_trace_async - async def delete_generation_job(self, job_id: str, **kwargs: Any) -> None: - """Deletes an evaluator generation job by its ID. Deletes the job record only; the generated - evaluator (if any) is preserved. + @overload + async def update_version( + self, + name: str, + version: str, + evaluator_version: _models.EvaluatorVersion, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EvaluatorVersion: + """Update an existing EvaluatorVersion with the given version id. - :param job_id: The ID of the job to delete. Required. - :type job_id: str - :return: None - :rtype: None + :param name: The name of the resource. Required. + :type name: str + :param version: The version of the EvaluatorVersion to update. Required. + :type version: str + :param evaluator_version: Evaluator resource. Required. + :type evaluator_version: ~azure.ai.projects.models.EvaluatorVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorVersion :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 {} + @overload + async def update_version( + self, name: str, version: str, evaluator_version: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluatorVersion: + """Update an existing EvaluatorVersion with the given version id. - cls: ClsType[None] = kwargs.pop("cls", None) + :param name: The name of the resource. Required. + :type name: str + :param version: The version of the EvaluatorVersion to update. Required. + :type version: str + :param evaluator_version: Evaluator resource. Required. + :type evaluator_version: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ - _request = build_beta_evaluators_delete_generation_job_request( - job_id=job_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) + @overload + async def update_version( + self, + name: str, + version: str, + evaluator_version: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EvaluatorVersion: + """Update an existing EvaluatorVersion with the given version id. - _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 [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - -class BetaInsightsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.ai.projects.aio.AIProjectClient`'s - :attr:`insights` 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: AIProjectClientConfiguration = 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 generate( - self, insight: _models.Insight, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Insight: - """Generate Insights. - - :param insight: Complete evaluation configuration including data source, evaluators, and result - settings. Required. - :type insight: ~azure.ai.projects.models.Insight - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Insight. The Insight is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Insight - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def generate( - self, insight: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Insight: - """Generate Insights. - - :param insight: Complete evaluation configuration including data source, evaluators, and result - settings. Required. - :type insight: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Insight. The Insight is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Insight - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def generate( - self, insight: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Insight: - """Generate Insights. - - :param insight: Complete evaluation configuration including data source, evaluators, and result - settings. Required. - :type insight: IO[bytes] + :param name: The name of the resource. Required. + :type name: str + :param version: The version of the EvaluatorVersion to update. Required. + :type version: str + :param evaluator_version: Evaluator resource. Required. + :type evaluator_version: 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: Insight. The Insight is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Insight + :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorVersion :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def generate(self, insight: Union[_models.Insight, JSON, IO[bytes]], **kwargs: Any) -> _models.Insight: - """Generate Insights. + async def update_version( + self, + name: str, + version: str, + evaluator_version: Union[_models.EvaluatorVersion, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.EvaluatorVersion: + """Update an existing EvaluatorVersion with the given version id. - :param insight: Complete evaluation configuration including data source, evaluators, and result - settings. Is one of the following types: Insight, JSON, IO[bytes] Required. - :type insight: ~azure.ai.projects.models.Insight or JSON or IO[bytes] - :return: Insight. The Insight is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Insight + :param name: The name of the resource. Required. + :type name: str + :param version: The version of the EvaluatorVersion to update. Required. + :type version: str + :param evaluator_version: Evaluator resource. Is one of the following types: EvaluatorVersion, + JSON, IO[bytes] Required. + :type evaluator_version: ~azure.ai.projects.models.EvaluatorVersion or JSON or IO[bytes] + :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorVersion :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6056,16 +6113,18 @@ async def generate(self, insight: Union[_models.Insight, JSON, IO[bytes]], **kwa _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Insight] = kwargs.pop("cls", None) + cls: ClsType[_models.EvaluatorVersion] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None - if isinstance(insight, (IOBase, bytes)): - _content = insight + if isinstance(evaluator_version, (IOBase, bytes)): + _content = evaluator_version else: - _content = json.dumps(insight, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(evaluator_version, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_insights_generate_request( + _request = build_beta_evaluators_update_version_request( + name=name, + version=version, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -6085,42 +6144,123 @@ async def generate(self, insight: Union[_models.Insight, JSON, IO[bytes]], **kwa response = pipeline_response.http_response - if response.status_code not in [201]: + 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) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) + raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.Insight, response.json()) + deserialized = _deserialize(_models.EvaluatorVersion, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + @overload + async def pending_upload( + self, + name: str, + version: str, + pending_upload_request: _models.PendingUploadRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PendingUploadResult: + """Start a new or get an existing pending upload of an evaluator for a specific version. + + :param name: Required. + :type name: str + :param version: The specific version id of the EvaluatorVersion to operate on. Required. + :type version: str + :param pending_upload_request: The pending upload request parameters. Required. + :type pending_upload_request: ~azure.ai.projects.models.PendingUploadRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PendingUploadResult. The PendingUploadResult is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def pending_upload( + self, + name: str, + version: str, + pending_upload_request: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PendingUploadResult: + """Start a new or get an existing pending upload of an evaluator for a specific version. + + :param name: Required. + :type name: str + :param version: The specific version id of the EvaluatorVersion to operate on. Required. + :type version: str + :param pending_upload_request: The pending upload request parameters. Required. + :type pending_upload_request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PendingUploadResult. The PendingUploadResult is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def pending_upload( + self, + name: str, + version: str, + pending_upload_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PendingUploadResult: + """Start a new or get an existing pending upload of an evaluator for a specific version. + + :param name: Required. + :type name: str + :param version: The specific version id of the EvaluatorVersion to operate on. Required. + :type version: str + :param pending_upload_request: The pending upload request parameters. Required. + :type pending_upload_request: 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: PendingUploadResult. The PendingUploadResult is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + @distributed_trace_async - async def get( - self, insight_id: str, *, include_coordinates: Optional[bool] = None, **kwargs: Any - ) -> _models.Insight: - """Get a specific insight by Id. + async def pending_upload( + self, + name: str, + version: str, + pending_upload_request: Union[_models.PendingUploadRequest, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.PendingUploadResult: + """Start a new or get an existing pending upload of an evaluator for a specific version. - :param insight_id: The unique identifier for the insights report. Required. - :type insight_id: str - :keyword include_coordinates: Whether to include coordinates for visualization in the response. - Defaults to false. Default value is None. - :paramtype include_coordinates: bool - :return: Insight. The Insight is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Insight + :param name: Required. + :type name: str + :param version: The specific version id of the EvaluatorVersion to operate on. Required. + :type version: str + :param pending_upload_request: The pending upload request parameters. Is one of the following + types: PendingUploadRequest, JSON, IO[bytes] Required. + :type pending_upload_request: ~azure.ai.projects.models.PendingUploadRequest or JSON or + IO[bytes] + :return: PendingUploadResult. The PendingUploadResult is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6131,15 +6271,25 @@ async def get( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.Insight] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PendingUploadResult] = kwargs.pop("cls", None) - _request = build_beta_insights_get_request( - insight_id=insight_id, - include_coordinates=include_coordinates, + content_type = content_type or "application/json" + _content = None + if isinstance(pending_upload_request, (IOBase, bytes)): + _content = pending_upload_request + else: + _content = json.dumps(pending_upload_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_beta_evaluators_pending_upload_request( + name=name, + version=version, + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -6172,237 +6322,111 @@ async def get( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.Insight, response.json()) + deserialized = _deserialize(_models.PendingUploadResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @distributed_trace - def list( + @overload + async def get_credentials( self, + name: str, + version: str, + credential_request: _models.EvaluatorCredentialRequest, *, - type: Optional[Union[str, _models.InsightType]] = None, - eval_id: Optional[str] = None, - run_id: Optional[str] = None, - agent_name: Optional[str] = None, - include_coordinates: Optional[bool] = None, - **kwargs: Any - ) -> AsyncItemPaged["_models.Insight"]: - """List all insights in reverse chronological order (newest first). - - :keyword type: Filter by the type of analysis. Known values are: "EvaluationRunClusterInsight", - "AgentClusterInsight", and "EvaluationComparison". Default value is None. - :paramtype type: str or ~azure.ai.projects.models.InsightType - :keyword eval_id: Filter by the evaluation ID. Default value is None. - :paramtype eval_id: str - :keyword run_id: Filter by the evaluation run ID. Default value is None. - :paramtype run_id: str - :keyword agent_name: Filter by the agent name. Default value is None. - :paramtype agent_name: str - :keyword include_coordinates: Whether to include coordinates for visualization in the response. - Defaults to false. Default value is None. - :paramtype include_coordinates: bool - :return: An iterator like instance of Insight - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.Insight] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.Insight]] = 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_beta_insights_list_request( - type=type, - eval_id=eval_id, - run_id=run_id, - agent_name=agent_name, - include_coordinates=include_coordinates, - 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, - headers=_headers, - ) - 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.Insight], - 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) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return AsyncItemPaged(get_next, extract_data) - - -class BetaMemoryStoresOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.ai.projects.aio.AIProjectClient`'s - :attr:`memory_stores` 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: AIProjectClientConfiguration = 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( - self, - *, - name: str, - definition: _models.MemoryStoreDefinition, content_type: str = "application/json", - description: Optional[str] = None, - metadata: Optional[dict[str, str]] = None, **kwargs: Any - ) -> _models.MemoryStoreDetails: - """Create a memory store. + ) -> _models.DatasetCredential: + """Get the SAS credential to access the storage account associated with an Evaluator version. - :keyword name: The name of the memory store. Required. - :paramtype name: str - :keyword definition: The memory store definition. Required. - :paramtype definition: ~azure.ai.projects.models.MemoryStoreDefinition + :param name: Required. + :type name: str + :param version: The specific version id of the EvaluatorVersion to operate on. Required. + :type version: str + :param credential_request: The credential request parameters. Required. + :type credential_request: ~azure.ai.projects.models.EvaluatorCredentialRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword description: A human-readable description of the memory store. Default value is None. - :paramtype description: str - :keyword metadata: Arbitrary key-value metadata to associate with the memory store. Default - value is None. - :paramtype metadata: dict[str, str] - :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :return: DatasetCredential. The DatasetCredential is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetCredential :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.MemoryStoreDetails: - """Create a memory store. + async def get_credentials( + self, + name: str, + version: str, + credential_request: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DatasetCredential: + """Get the SAS credential to access the storage account associated with an Evaluator version. - :param body: Required. - :type body: JSON + :param name: Required. + :type name: str + :param version: The specific version id of the EvaluatorVersion to operate on. Required. + :type version: str + :param credential_request: The credential request parameters. Required. + :type credential_request: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :return: DatasetCredential. The DatasetCredential is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetCredential :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create( - self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.MemoryStoreDetails: - """Create a memory store. + async def get_credentials( + self, + name: str, + version: str, + credential_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DatasetCredential: + """Get the SAS credential to access the storage account associated with an Evaluator version. - :param body: Required. - :type body: IO[bytes] + :param name: Required. + :type name: str + :param version: The specific version id of the EvaluatorVersion to operate on. Required. + :type version: str + :param credential_request: The credential request parameters. Required. + :type credential_request: 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: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :return: DatasetCredential. The DatasetCredential is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetCredential :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def create( + async def get_credentials( self, - body: Union[JSON, IO[bytes]] = _Unset, - *, - name: str = _Unset, - definition: _models.MemoryStoreDefinition = _Unset, - description: Optional[str] = None, - metadata: Optional[dict[str, str]] = None, + name: str, + version: str, + credential_request: Union[_models.EvaluatorCredentialRequest, JSON, IO[bytes]], **kwargs: Any - ) -> _models.MemoryStoreDetails: - """Create a memory store. + ) -> _models.DatasetCredential: + """Get the SAS credential to access the storage account associated with an Evaluator version. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword name: The name of the memory store. Required. - :paramtype name: str - :keyword definition: The memory store definition. Required. - :paramtype definition: ~azure.ai.projects.models.MemoryStoreDefinition - :keyword description: A human-readable description of the memory store. Default value is None. - :paramtype description: str - :keyword metadata: Arbitrary key-value metadata to associate with the memory store. Default - value is None. - :paramtype metadata: dict[str, str] - :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :param name: Required. + :type name: str + :param version: The specific version id of the EvaluatorVersion to operate on. Required. + :type version: str + :param credential_request: The credential request parameters. Is one of the following types: + EvaluatorCredentialRequest, JSON, IO[bytes] Required. + :type credential_request: ~azure.ai.projects.models.EvaluatorCredentialRequest or JSON or + IO[bytes] + :return: DatasetCredential. The DatasetCredential is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetCredential :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6417,23 +6441,18 @@ async def create( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.MemoryStoreDetails] = kwargs.pop("cls", None) + cls: ClsType[_models.DatasetCredential] = kwargs.pop("cls", None) - if body is _Unset: - if name is _Unset: - raise TypeError("missing required argument: name") - if definition is _Unset: - raise TypeError("missing required argument: definition") - body = {"definition": definition, "description": description, "metadata": metadata, "name": name} - 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 + if isinstance(credential_request, (IOBase, bytes)): + _content = credential_request else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(credential_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_memory_stores_create_request( + _request = build_beta_evaluators_get_credentials_request( + name=name, + version=version, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -6469,7 +6488,7 @@ async def create( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.MemoryStoreDetails, response.json()) + deserialized = _deserialize(_models.DatasetCredential, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -6477,91 +6496,102 @@ async def create( return deserialized # type: ignore @overload - async def update( + async def create_generation_job( self, - name: str, + job: _models.EvaluatorGenerationJob, *, + operation_id: Optional[str] = None, content_type: str = "application/json", - description: Optional[str] = None, - metadata: Optional[dict[str, str]] = None, **kwargs: Any - ) -> _models.MemoryStoreDetails: - """Update a memory store. + ) -> _models.EvaluatorGenerationJob: + """Creates an evaluator generation job. - :param name: The name of the memory store to update. Required. - :type 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 description: A human-readable description of the memory store. Default value is None. - :paramtype description: str - :keyword metadata: Arbitrary key-value metadata to associate with the memory store. Default - value is None. - :paramtype metadata: dict[str, str] - :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDetails + Creates an evaluator generation job. The service generates rubric-based evaluator definitions + from the provided source materials asynchronously. + + :param job: The job to create. Required. + :type job: ~azure.ai.projects.models.EvaluatorGenerationJob + :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the + server creates the job unconditionally. Default value is None. + :paramtype operation_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def update( - self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.MemoryStoreDetails: - """Update a memory store. + async def create_generation_job( + self, job: JSON, *, operation_id: Optional[str] = None, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluatorGenerationJob: + """Creates an evaluator generation job. - :param name: The name of the memory store to update. Required. - :type name: str - :param body: Required. - :type body: JSON + Creates an evaluator generation job. The service generates rubric-based evaluator definitions + from the provided source materials asynchronously. + + :param job: The job to create. Required. + :type job: JSON + :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the + server creates the job unconditionally. Default value is None. + :paramtype operation_id: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def update( - self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.MemoryStoreDetails: - """Update a memory store. + async def create_generation_job( + self, + job: IO[bytes], + *, + operation_id: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EvaluatorGenerationJob: + """Creates an evaluator generation job. - :param name: The name of the memory store to update. Required. - :type name: str - :param body: Required. - :type body: IO[bytes] + Creates an evaluator generation job. The service generates rubric-based evaluator definitions + from the provided source materials asynchronously. + + :param job: The job to create. Required. + :type job: IO[bytes] + :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the + server creates the job unconditionally. Default value is None. + :paramtype operation_id: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str - :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def update( + async def create_generation_job( self, - name: str, - body: Union[JSON, IO[bytes]] = _Unset, + job: Union[_models.EvaluatorGenerationJob, JSON, IO[bytes]], *, - description: Optional[str] = None, - metadata: Optional[dict[str, str]] = None, + operation_id: Optional[str] = None, **kwargs: Any - ) -> _models.MemoryStoreDetails: - """Update a memory store. + ) -> _models.EvaluatorGenerationJob: + """Creates an evaluator generation job. - :param name: The name of the memory store to update. Required. - :type name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword description: A human-readable description of the memory store. Default value is None. - :paramtype description: str - :keyword metadata: Arbitrary key-value metadata to associate with the memory store. Default - value is None. - :paramtype metadata: dict[str, str] - :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDetails + Creates an evaluator generation job. The service generates rubric-based evaluator definitions + from the provided source materials asynchronously. + + :param job: The job to create. Is one of the following types: EvaluatorGenerationJob, JSON, + IO[bytes] Required. + :type job: ~azure.ai.projects.models.EvaluatorGenerationJob or JSON or IO[bytes] + :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the + server creates the job unconditionally. Default value is None. + :paramtype operation_id: str + :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6576,20 +6606,17 @@ async def update( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.MemoryStoreDetails] = kwargs.pop("cls", None) + cls: ClsType[_models.EvaluatorGenerationJob] = kwargs.pop("cls", None) - if body is _Unset: - body = {"description": description, "metadata": metadata} - 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 + if isinstance(job, (IOBase, bytes)): + _content = job else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(job, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_memory_stores_update_request( - name=name, + _request = build_beta_evaluators_create_generation_job_request( + operation_id=operation_id, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -6609,7 +6636,7 @@ async def update( response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [201]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -6622,24 +6649,30 @@ async def update( ) raise HttpResponseError(response=response, model=error) + response_headers = {} + response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.MemoryStoreDetails, response.json()) + deserialized = _deserialize(_models.EvaluatorGenerationJob, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore @distributed_trace_async - async def get(self, name: str, **kwargs: Any) -> _models.MemoryStoreDetails: - """Retrieve a memory store. + async def get_generation_job(self, job_id: str, **kwargs: Any) -> _models.EvaluatorGenerationJob: + """Get info about an evaluator generation job. - :param name: The name of the memory store to retrieve. Required. - :type name: str - :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDetails + Gets the details of an evaluator generation job by its ID. + + :param job_id: The ID of the job. Required. + :type job_id: str + :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6653,10 +6686,10 @@ async def get(self, name: str, **kwargs: Any) -> _models.MemoryStoreDetails: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.MemoryStoreDetails] = kwargs.pop("cls", None) + cls: ClsType[_models.EvaluatorGenerationJob] = kwargs.pop("cls", None) - _request = build_beta_memory_stores_get_request( - name=name, + _request = build_beta_evaluators_get_generation_job_request( + job_id=job_id, api_version=self._config.api_version, headers=_headers, params=_params, @@ -6687,26 +6720,31 @@ async def get(self, name: str, **kwargs: Any) -> _models.MemoryStoreDetails: ) raise HttpResponseError(response=response, model=error) + response_headers = {} + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.MemoryStoreDetails, response.json()) + deserialized = _deserialize(_models.EvaluatorGenerationJob, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore @distributed_trace - def list( + def list_generation_jobs( self, *, limit: Optional[int] = None, order: Optional[Union[str, _models.PageOrder]] = None, before: Optional[str] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.MemoryStoreDetails"]: - """List all memory stores. + ) -> AsyncItemPaged["_models.EvaluatorGenerationJob"]: + """Returns a list of evaluator generation jobs. + + Returns a list of evaluator generation jobs. :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the @@ -6722,14 +6760,15 @@ def list( subsequent call can include before=obj_foo in order to fetch the previous page of the list. Default value is None. :paramtype before: str - :return: An iterator like instance of MemoryStoreDetails - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.MemoryStoreDetails] + :return: An iterator like instance of EvaluatorGenerationJob + :rtype: + ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.EvaluatorGenerationJob] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.MemoryStoreDetails]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.EvaluatorGenerationJob]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -6741,7 +6780,7 @@ def list( def prepare_request(_continuation_token=None): - _request = build_beta_memory_stores_list_request( + _request = build_beta_evaluators_list_generation_jobs_request( limit=limit, order=order, after=_continuation_token, @@ -6759,7 +6798,7 @@ def prepare_request(_continuation_token=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() list_of_elem = _deserialize( - List[_models.MemoryStoreDetails], + List[_models.EvaluatorGenerationJob], deserialized.get("data", []), ) if cls: @@ -6788,13 +6827,15 @@ async def get_next(_continuation_token=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def delete(self, name: str, **kwargs: Any) -> _models.DeleteMemoryStoreResult: - """Delete a memory store. + async def cancel_generation_job(self, job_id: str, **kwargs: Any) -> _models.EvaluatorGenerationJob: + """Cancels an evaluator generation job. - :param name: The name of the memory store to delete. Required. - :type name: str - :return: DeleteMemoryStoreResult. The DeleteMemoryStoreResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.DeleteMemoryStoreResult + Cancels an evaluator generation job by its ID. + + :param job_id: The ID of the job to cancel. Required. + :type job_id: str + :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6808,10 +6849,10 @@ async def delete(self, name: str, **kwargs: Any) -> _models.DeleteMemoryStoreRes _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.DeleteMemoryStoreResult] = kwargs.pop("cls", None) + cls: ClsType[_models.EvaluatorGenerationJob] = kwargs.pop("cls", None) - _request = build_beta_memory_stores_delete_request( - name=name, + _request = build_beta_evaluators_cancel_generation_job_request( + job_id=job_id, api_version=self._config.api_version, headers=_headers, params=_params, @@ -6845,64 +6886,22 @@ async def delete(self, name: str, **kwargs: Any) -> _models.DeleteMemoryStoreRes if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.DeleteMemoryStoreResult, response.json()) + deserialized = _deserialize(_models.EvaluatorGenerationJob, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @overload - async def _search_memories( - self, - name: str, - *, - scope: str, - content_type: str = "application/json", - items: Optional[List[dict[str, Any]]] = None, - previous_search_id: Optional[str] = None, - options: Optional[_models.MemorySearchOptions] = None, - **kwargs: Any - ) -> _models.MemoryStoreSearchResult: ... - @overload - async def _search_memories( - self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.MemoryStoreSearchResult: ... - @overload - async def _search_memories( - self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.MemoryStoreSearchResult: ... - @distributed_trace_async - async def _search_memories( - self, - name: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - scope: str = _Unset, - items: Optional[List[dict[str, Any]]] = None, - previous_search_id: Optional[str] = None, - options: Optional[_models.MemorySearchOptions] = None, - **kwargs: Any - ) -> _models.MemoryStoreSearchResult: - """Search for relevant memories from a memory store based on conversation context. + async def delete_generation_job(self, job_id: str, **kwargs: Any) -> None: + """Deletes an evaluator generation job by its ID. Deletes the job record only; the generated + evaluator (if any) is preserved. - :param name: The name of the memory store to search. Required. - :type name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword scope: The namespace that logically groups and isolates memories, such as a user ID. - Required. - :paramtype scope: str - :keyword items: Items for which to search for relevant memories. Default value is None. - :paramtype items: list[dict[str, any]] - :keyword previous_search_id: The unique ID of the previous search request, enabling incremental - memory search from where the last operation left off. Default value is None. - :paramtype previous_search_id: str - :keyword options: Memory search options. Default value is None. - :paramtype options: ~azure.ai.projects.models.MemorySearchOptions - :return: MemoryStoreSearchResult. The MemoryStoreSearchResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreSearchResult + :param job_id: The ID of the job to delete. Required. + :type job_id: str + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6913,31 +6912,142 @@ async def _search_memories( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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.MemoryStoreSearchResult] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_beta_evaluators_delete_generation_job_request( + job_id=job_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) + + _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 [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + +class BetaInsightsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.aio.AIProjectClient`'s + :attr:`insights` 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: AIProjectClientConfiguration = 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 generate( + self, insight: _models.Insight, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Insight: + """Generate Insights. + + :param insight: Complete evaluation configuration including data source, evaluators, and result + settings. Required. + :type insight: ~azure.ai.projects.models.Insight + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Insight. The Insight is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Insight + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def generate( + self, insight: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Insight: + """Generate Insights. + + :param insight: Complete evaluation configuration including data source, evaluators, and result + settings. Required. + :type insight: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Insight. The Insight is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Insight + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def generate( + self, insight: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Insight: + """Generate Insights. + + :param insight: Complete evaluation configuration including data source, evaluators, and result + settings. Required. + :type insight: 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: Insight. The Insight is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Insight + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def generate(self, insight: Union[_models.Insight, JSON, IO[bytes]], **kwargs: Any) -> _models.Insight: + """Generate Insights. + + :param insight: Complete evaluation configuration including data source, evaluators, and result + settings. Is one of the following types: Insight, JSON, IO[bytes] Required. + :type insight: ~azure.ai.projects.models.Insight or JSON or IO[bytes] + :return: Insight. The Insight is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Insight + :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.Insight] = kwargs.pop("cls", None) - if body is _Unset: - if scope is _Unset: - raise TypeError("missing required argument: scope") - body = { - "items": items, - "options": options, - "previous_search_id": previous_search_id, - "scope": scope, - } - 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 + if isinstance(insight, (IOBase, bytes)): + _content = insight else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(insight, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_memory_stores_search_memories_request( - name=name, + _request = build_beta_insights_generate_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -6957,7 +7067,7 @@ async def _search_memories( response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [201]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -6973,24 +7083,28 @@ async def _search_memories( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.MemoryStoreSearchResult, response.json()) + deserialized = _deserialize(_models.Insight, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - async def _update_memories_initial( - self, - name: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - scope: str = _Unset, - items: Optional[List[dict[str, Any]]] = None, - previous_update_id: Optional[str] = None, - update_delay: Optional[int] = None, - **kwargs: Any - ) -> AsyncIterator[bytes]: + @distributed_trace_async + async def get( + self, insight_id: str, *, include_coordinates: Optional[bool] = None, **kwargs: Any + ) -> _models.Insight: + """Get a specific insight by Id. + + :param insight_id: The unique identifier for the insights report. Required. + :type insight_id: str + :keyword include_coordinates: Whether to include coordinates for visualization in the response. + Defaults to false. Default value is None. + :paramtype include_coordinates: bool + :return: Insight. The Insight is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Insight + :raises ~azure.core.exceptions.HttpResponseError: + """ error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -6999,34 +7113,15 @@ async def _update_memories_initial( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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 scope is _Unset: - raise TypeError("missing required argument: scope") - body = { - "items": items, - "previous_update_id": previous_update_id, - "scope": scope, - "update_delay": update_delay, - } - 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 + cls: ClsType[_models.Insight] = kwargs.pop("cls", None) - _request = build_beta_memory_stores_update_memories_request( - name=name, - content_type=content_type, + _request = build_beta_insights_get_request( + insight_id=insight_id, + include_coordinates=include_coordinates, api_version=self._config.api_version, - content=_content, headers=_headers, params=_params, ) @@ -7036,18 +7131,19 @@ async def _update_memories_initial( _request.url = self._client.format_url(_request.url, **path_format_arguments) _decompress = kwargs.pop("decompress", True) - _stream = 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 [202]: - try: - await response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass + 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) error = _failsafe_deserialize( _models.ApiErrorResponse, @@ -7055,210 +7151,3194 @@ async def _update_memories_initial( ) raise HttpResponseError(response=response, model=error) - 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 _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Insight, response.json()) if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @overload - async def _begin_update_memories( + @distributed_trace + def list( self, - name: str, *, - scope: str, - content_type: str = "application/json", - items: Optional[List[dict[str, Any]]] = None, - previous_update_id: Optional[str] = None, - update_delay: Optional[int] = None, + type: Optional[Union[str, _models.InsightType]] = None, + eval_id: Optional[str] = None, + run_id: Optional[str] = None, + agent_name: Optional[str] = None, + include_coordinates: Optional[bool] = None, **kwargs: Any - ) -> AsyncLROPoller[_models.MemoryStoreUpdateCompletedResult]: ... - @overload - async def _begin_update_memories( - self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[_models.MemoryStoreUpdateCompletedResult]: ... - @overload - async def _begin_update_memories( - self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> AsyncLROPoller[_models.MemoryStoreUpdateCompletedResult]: ... + ) -> AsyncItemPaged["_models.Insight"]: + """List all insights in reverse chronological order (newest first). - @distributed_trace_async - async def _begin_update_memories( - self, - name: str, + :keyword type: Filter by the type of analysis. Known values are: "EvaluationRunClusterInsight", + "AgentClusterInsight", and "EvaluationComparison". Default value is None. + :paramtype type: str or ~azure.ai.projects.models.InsightType + :keyword eval_id: Filter by the evaluation ID. Default value is None. + :paramtype eval_id: str + :keyword run_id: Filter by the evaluation run ID. Default value is None. + :paramtype run_id: str + :keyword agent_name: Filter by the agent name. Default value is None. + :paramtype agent_name: str + :keyword include_coordinates: Whether to include coordinates for visualization in the response. + Defaults to false. Default value is None. + :paramtype include_coordinates: bool + :return: An iterator like instance of Insight + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.Insight] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Insight]] = 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_beta_insights_list_request( + type=type, + eval_id=eval_id, + run_id=run_id, + agent_name=agent_name, + include_coordinates=include_coordinates, + 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, + headers=_headers, + ) + 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.Insight], + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class BetaMemoryStoresOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.aio.AIProjectClient`'s + :attr:`memory_stores` 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: AIProjectClientConfiguration = 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( + self, + *, + name: str, + definition: _models.MemoryStoreDefinition, + content_type: str = "application/json", + description: Optional[str] = None, + metadata: Optional[dict[str, str]] = None, + **kwargs: Any + ) -> _models.MemoryStoreDetails: + """Create a memory store. + + :keyword name: The name of the memory store. Required. + :paramtype name: str + :keyword definition: The memory store definition. Required. + :paramtype definition: ~azure.ai.projects.models.MemoryStoreDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword description: A human-readable description of the memory store. Default value is None. + :paramtype description: str + :keyword metadata: Arbitrary key-value metadata to associate with the memory store. Default + value is None. + :paramtype metadata: dict[str, str] + :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryStoreDetails: + """Create a memory store. + + :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: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryStoreDetails: + """Create a memory store. + + :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: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create( + self, body: Union[JSON, IO[bytes]] = _Unset, *, - scope: str = _Unset, - items: Optional[List[dict[str, Any]]] = None, - previous_update_id: Optional[str] = None, - update_delay: Optional[int] = None, + name: str = _Unset, + definition: _models.MemoryStoreDefinition = _Unset, + description: Optional[str] = None, + metadata: Optional[dict[str, str]] = None, **kwargs: Any - ) -> AsyncLROPoller[_models.MemoryStoreUpdateCompletedResult]: - """Update memory store with conversation memories. + ) -> _models.MemoryStoreDetails: + """Create a memory store. + + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword name: The name of the memory store. Required. + :paramtype name: str + :keyword definition: The memory store definition. Required. + :paramtype definition: ~azure.ai.projects.models.MemoryStoreDefinition + :keyword description: A human-readable description of the memory store. Default value is None. + :paramtype description: str + :keyword metadata: Arbitrary key-value metadata to associate with the memory store. Default + value is None. + :paramtype metadata: dict[str, str] + :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :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.MemoryStoreDetails] = kwargs.pop("cls", None) + + if body is _Unset: + if name is _Unset: + raise TypeError("missing required argument: name") + if definition is _Unset: + raise TypeError("missing required argument: definition") + body = {"definition": definition, "description": description, "metadata": metadata, "name": name} + 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_beta_memory_stores_create_request( + 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]: + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MemoryStoreDetails, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update( + self, + name: str, + *, + content_type: str = "application/json", + description: Optional[str] = None, + metadata: Optional[dict[str, str]] = None, + **kwargs: Any + ) -> _models.MemoryStoreDetails: + """Update a memory store. + + :param name: The name of the memory store to update. Required. + :type 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 description: A human-readable description of the memory store. Default value is None. + :paramtype description: str + :keyword metadata: Arbitrary key-value metadata to associate with the memory store. Default + value is None. + :paramtype metadata: dict[str, str] + :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryStoreDetails: + """Update a memory store. + + :param name: The name of the memory store to update. Required. + :type 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: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryStoreDetails: + """Update a memory store. + + :param name: The name of the memory store to update. Required. + :type 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: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, + name: str, + body: Union[JSON, IO[bytes]] = _Unset, + *, + description: Optional[str] = None, + metadata: Optional[dict[str, str]] = None, + **kwargs: Any + ) -> _models.MemoryStoreDetails: + """Update a memory store. + + :param name: The name of the memory store to update. Required. + :type name: str + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword description: A human-readable description of the memory store. Default value is None. + :paramtype description: str + :keyword metadata: Arbitrary key-value metadata to associate with the memory store. Default + value is None. + :paramtype metadata: dict[str, str] + :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :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.MemoryStoreDetails] = kwargs.pop("cls", None) + + if body is _Unset: + body = {"description": description, "metadata": metadata} + 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_beta_memory_stores_update_request( + name=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]: + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MemoryStoreDetails, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get(self, name: str, **kwargs: Any) -> _models.MemoryStoreDetails: + """Retrieve a memory store. + + :param name: The name of the memory store to retrieve. Required. + :type name: str + :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :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.MemoryStoreDetails] = kwargs.pop("cls", None) + + _request = build_beta_memory_stores_get_request( + name=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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MemoryStoreDetails, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, + *, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + before: Optional[str] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.MemoryStoreDetails"]: + """List all memory stores. + + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :return: An iterator like instance of MemoryStoreDetails + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.MemoryStoreDetails] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.MemoryStoreDetails]] = 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(_continuation_token=None): + + _request = build_beta_memory_stores_list_request( + limit=limit, + order=order, + after=_continuation_token, + before=before, + 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) + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.MemoryStoreDetails], + deserialized.get("data", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("last_id") or None, AsyncList(list_of_elem) + + async def get_next(_continuation_token=None): + _request = prepare_request(_continuation_token) + + _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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def delete(self, name: str, **kwargs: Any) -> _models.DeleteMemoryStoreResult: + """Delete a memory store. + + :param name: The name of the memory store to delete. Required. + :type name: str + :return: DeleteMemoryStoreResult. The DeleteMemoryStoreResult is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DeleteMemoryStoreResult + :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.DeleteMemoryStoreResult] = kwargs.pop("cls", None) + + _request = build_beta_memory_stores_delete_request( + name=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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.DeleteMemoryStoreResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def _search_memories( + self, + name: str, + *, + scope: str, + content_type: str = "application/json", + items: Optional[List[dict[str, Any]]] = None, + previous_search_id: Optional[str] = None, + options: Optional[_models.MemorySearchOptions] = None, + **kwargs: Any + ) -> _models.MemoryStoreSearchResult: ... + @overload + async def _search_memories( + self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryStoreSearchResult: ... + @overload + async def _search_memories( + self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryStoreSearchResult: ... + + @distributed_trace_async + async def _search_memories( + self, + name: str, + body: Union[JSON, IO[bytes]] = _Unset, + *, + scope: str = _Unset, + items: Optional[List[dict[str, Any]]] = None, + previous_search_id: Optional[str] = None, + options: Optional[_models.MemorySearchOptions] = None, + **kwargs: Any + ) -> _models.MemoryStoreSearchResult: + """Search for relevant memories from a memory store based on conversation context. + + :param name: The name of the memory store to search. Required. + :type name: str + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword scope: The namespace that logically groups and isolates memories, such as a user ID. + Required. + :paramtype scope: str + :keyword items: Items for which to search for relevant memories. Default value is None. + :paramtype items: list[dict[str, any]] + :keyword previous_search_id: The unique ID of the previous search request, enabling incremental + memory search from where the last operation left off. Default value is None. + :paramtype previous_search_id: str + :keyword options: Memory search options. Default value is None. + :paramtype options: ~azure.ai.projects.models.MemorySearchOptions + :return: MemoryStoreSearchResult. The MemoryStoreSearchResult is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreSearchResult + :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.MemoryStoreSearchResult] = kwargs.pop("cls", None) + + if body is _Unset: + if scope is _Unset: + raise TypeError("missing required argument: scope") + body = { + "items": items, + "options": options, + "previous_search_id": previous_search_id, + "scope": scope, + } + 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_beta_memory_stores_search_memories_request( + name=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]: + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MemoryStoreSearchResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + async def _update_memories_initial( + self, + name: str, + body: Union[JSON, IO[bytes]] = _Unset, + *, + scope: str = _Unset, + items: Optional[List[dict[str, Any]]] = None, + previous_update_id: Optional[str] = None, + update_delay: Optional[int] = 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 scope is _Unset: + raise TypeError("missing required argument: scope") + body = { + "items": items, + "previous_update_id": previous_update_id, + "scope": scope, + "update_delay": update_delay, + } + 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_beta_memory_stores_update_memories_request( + name=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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + 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_update_memories( + self, + name: str, + *, + scope: str, + content_type: str = "application/json", + items: Optional[List[dict[str, Any]]] = None, + previous_update_id: Optional[str] = None, + update_delay: Optional[int] = None, + **kwargs: Any + ) -> AsyncLROPoller[_models.MemoryStoreUpdateCompletedResult]: ... + @overload + async def _begin_update_memories( + self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.MemoryStoreUpdateCompletedResult]: ... + @overload + async def _begin_update_memories( + self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> AsyncLROPoller[_models.MemoryStoreUpdateCompletedResult]: ... + + @distributed_trace_async + async def _begin_update_memories( + self, + name: str, + body: Union[JSON, IO[bytes]] = _Unset, + *, + scope: str = _Unset, + items: Optional[List[dict[str, Any]]] = None, + previous_update_id: Optional[str] = None, + update_delay: Optional[int] = None, + **kwargs: Any + ) -> AsyncLROPoller[_models.MemoryStoreUpdateCompletedResult]: + """Update memory store with conversation memories. + + :param name: The name of the memory store to update. Required. + :type name: str + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword scope: The namespace that logically groups and isolates memories, such as a user ID. + Required. + :paramtype scope: str + :keyword items: Conversation items to be stored in memory. Default value is None. + :paramtype items: list[dict[str, any]] + :keyword previous_update_id: The unique ID of the previous update request, enabling incremental + memory updates from where the last operation left off. Default value is None. + :paramtype previous_update_id: str + :keyword update_delay: Timeout period before processing the memory update in seconds. + If a new update request is received during this period, it will cancel the current request and + reset the timeout. + Set to 0 to immediately trigger the update without delay. + Defaults to 300 (5 minutes). Default value is None. + :paramtype update_delay: int + :return: An instance of AsyncLROPoller that returns MemoryStoreUpdateCompletedResult. The + MemoryStoreUpdateCompletedResult is compatible with MutableMapping + :rtype: + ~azure.core.polling.AsyncLROPoller[~azure.ai.projects.models.MemoryStoreUpdateCompletedResult] + :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.MemoryStoreUpdateCompletedResult] = 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._update_memories_initial( + name=name, + body=body, + scope=scope, + items=items, + previous_update_id=previous_update_id, + update_delay=update_delay, + 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.MemoryStoreUpdateCompletedResult, 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.MemoryStoreUpdateCompletedResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return AsyncLROPoller[_models.MemoryStoreUpdateCompletedResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @overload + async def delete_scope( + self, name: str, *, scope: str, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryStoreDeleteScopeResult: + """Delete all memories associated with a specific scope from a memory store. + + :param name: The name of the memory store. Required. + :type name: str + :keyword scope: The namespace that logically groups and isolates memories to delete, such as a + user ID. Required. + :paramtype scope: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: MemoryStoreDeleteScopeResult. The MemoryStoreDeleteScopeResult is compatible with + MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDeleteScopeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def delete_scope( + self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryStoreDeleteScopeResult: + """Delete all memories associated with a specific scope from a memory store. + + :param name: The name of the memory store. Required. + :type 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: MemoryStoreDeleteScopeResult. The MemoryStoreDeleteScopeResult is compatible with + MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDeleteScopeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def delete_scope( + self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryStoreDeleteScopeResult: + """Delete all memories associated with a specific scope from a memory store. + + :param name: The name of the memory store. Required. + :type 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: MemoryStoreDeleteScopeResult. The MemoryStoreDeleteScopeResult is compatible with + MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDeleteScopeResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def delete_scope( + self, name: str, body: Union[JSON, IO[bytes]] = _Unset, *, scope: str = _Unset, **kwargs: Any + ) -> _models.MemoryStoreDeleteScopeResult: + """Delete all memories associated with a specific scope from a memory store. + + :param name: The name of the memory store. Required. + :type name: str + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword scope: The namespace that logically groups and isolates memories to delete, such as a + user ID. Required. + :paramtype scope: str + :return: MemoryStoreDeleteScopeResult. The MemoryStoreDeleteScopeResult is compatible with + MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDeleteScopeResult + :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.MemoryStoreDeleteScopeResult] = kwargs.pop("cls", None) + + if body is _Unset: + if scope is _Unset: + raise TypeError("missing required argument: scope") + body = {"scope": scope} + 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_beta_memory_stores_delete_scope_request( + name=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]: + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MemoryStoreDeleteScopeResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_memory( + self, + name: str, + *, + scope: str, + content: str, + kind: Union[str, _models.MemoryItemKind], + content_type: str = "application/json", + **kwargs: Any + ) -> _models.MemoryItem: + """Create a memory item in a memory store. + + :param name: The name of the memory store. Required. + :type name: str + :keyword scope: The namespace that logically groups and isolates memories, such as a user ID. + Required. + :paramtype scope: str + :keyword content: The content of the memory. Required. + :paramtype content: str + :keyword kind: The kind of the memory item. Known values are: "user_profile", "chat_summary", + and "procedural". Required. + :paramtype kind: str or ~azure.ai.projects.models.MemoryItemKind + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: MemoryItem. The MemoryItem is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryItem + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_memory( + self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryItem: + """Create a memory item in a memory store. + + :param name: The name of the memory store. Required. + :type 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: MemoryItem. The MemoryItem is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryItem + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_memory( + self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryItem: + """Create a memory item in a memory store. + + :param name: The name of the memory store. Required. + :type 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: MemoryItem. The MemoryItem is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryItem + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_memory( + self, + name: str, + body: Union[JSON, IO[bytes]] = _Unset, + *, + scope: str = _Unset, + content: str = _Unset, + kind: Union[str, _models.MemoryItemKind] = _Unset, + **kwargs: Any + ) -> _models.MemoryItem: + """Create a memory item in a memory store. + + :param name: The name of the memory store. Required. + :type name: str + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword scope: The namespace that logically groups and isolates memories, such as a user ID. + Required. + :paramtype scope: str + :keyword content: The content of the memory. Required. + :paramtype content: str + :keyword kind: The kind of the memory item. Known values are: "user_profile", "chat_summary", + and "procedural". Required. + :paramtype kind: str or ~azure.ai.projects.models.MemoryItemKind + :return: MemoryItem. The MemoryItem is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryItem + :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.MemoryItem] = kwargs.pop("cls", None) + + if body is _Unset: + if scope is _Unset: + raise TypeError("missing required argument: scope") + if content is _Unset: + raise TypeError("missing required argument: content") + if kind is _Unset: + raise TypeError("missing required argument: kind") + body = {"content": content, "kind": kind, "scope": scope} + 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_beta_memory_stores_create_memory_request( + name=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]: + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MemoryItem, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def update_memory( + self, name: str, memory_id: str, *, content: str, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryItem: + """Update a memory item in a memory store. + + :param name: The name of the memory store. Required. + :type name: str + :param memory_id: The ID of the memory item to update. Required. + :type memory_id: str + :keyword content: The updated content of the memory. Required. + :paramtype content: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: MemoryItem. The MemoryItem is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryItem + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update_memory( + self, name: str, memory_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryItem: + """Update a memory item in a memory store. + + :param name: The name of the memory store. Required. + :type name: str + :param memory_id: The ID of the memory item to update. Required. + :type memory_id: 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: MemoryItem. The MemoryItem is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryItem + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update_memory( + self, name: str, memory_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryItem: + """Update a memory item in a memory store. + + :param name: The name of the memory store. Required. + :type name: str + :param memory_id: The ID of the memory item to update. Required. + :type memory_id: 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: MemoryItem. The MemoryItem is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryItem + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update_memory( + self, name: str, memory_id: str, body: Union[JSON, IO[bytes]] = _Unset, *, content: str = _Unset, **kwargs: Any + ) -> _models.MemoryItem: + """Update a memory item in a memory store. + + :param name: The name of the memory store. Required. + :type name: str + :param memory_id: The ID of the memory item to update. Required. + :type memory_id: str + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword content: The updated content of the memory. Required. + :paramtype content: str + :return: MemoryItem. The MemoryItem is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryItem + :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.MemoryItem] = kwargs.pop("cls", None) + + if body is _Unset: + if content is _Unset: + raise TypeError("missing required argument: content") + body = {"content": content} + 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_beta_memory_stores_update_memory_request( + name=name, + memory_id=memory_id, + 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]: + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MemoryItem, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get_memory(self, name: str, memory_id: str, **kwargs: Any) -> _models.MemoryItem: + """Retrieve a memory item from a memory store. + + :param name: The name of the memory store. Required. + :type name: str + :param memory_id: The ID of the memory item to retrieve. Required. + :type memory_id: str + :return: MemoryItem. The MemoryItem is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryItem + :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.MemoryItem] = kwargs.pop("cls", None) + + _request = build_beta_memory_stores_get_memory_request( + name=name, + memory_id=memory_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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MemoryItem, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def list_memories( + self, + name: str, + *, + scope: str, + kind: Optional[Union[str, _models.MemoryItemKind]] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + before: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncItemPaged["_models.MemoryItem"]: + """List all memory items in a memory store. + + :param name: The name of the memory store. Required. + :type name: str + :keyword scope: The namespace that logically groups and isolates memories, such as a user ID. + Required. + :paramtype scope: str + :keyword kind: The kind of the memory item. Known values are: "user_profile", "chat_summary", + and "procedural". Default value is None. + :paramtype kind: str or ~azure.ai.projects.models.MemoryItemKind + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An iterator like instance of MemoryItem + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.MemoryItem] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def list_memories( + self, + name: str, + body: JSON, + *, + kind: Optional[Union[str, _models.MemoryItemKind]] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + before: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncItemPaged["_models.MemoryItem"]: + """List all memory items in a memory store. + + :param name: The name of the memory store. Required. + :type name: str + :param body: Required. + :type body: JSON + :keyword kind: The kind of the memory item. Known values are: "user_profile", "chat_summary", + and "procedural". Default value is None. + :paramtype kind: str or ~azure.ai.projects.models.MemoryItemKind + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An iterator like instance of MemoryItem + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.MemoryItem] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def list_memories( + self, + name: str, + body: IO[bytes], + *, + kind: Optional[Union[str, _models.MemoryItemKind]] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + before: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> AsyncItemPaged["_models.MemoryItem"]: + """List all memory items in a memory store. + + :param name: The name of the memory store. Required. + :type name: str + :param body: Required. + :type body: IO[bytes] + :keyword kind: The kind of the memory item. Known values are: "user_profile", "chat_summary", + and "procedural". Default value is None. + :paramtype kind: str or ~azure.ai.projects.models.MemoryItemKind + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An iterator like instance of MemoryItem + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.MemoryItem] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def list_memories( + self, + name: str, + body: Union[JSON, IO[bytes]] = _Unset, + *, + scope: str = _Unset, + kind: Optional[Union[str, _models.MemoryItemKind]] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + before: Optional[str] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.MemoryItem"]: + """List all memory items in a memory store. + + :param name: The name of the memory store. Required. + :type name: str + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword scope: The namespace that logically groups and isolates memories, such as a user ID. + Required. + :paramtype scope: str + :keyword kind: The kind of the memory item. Known values are: "user_profile", "chat_summary", + and "procedural". Default value is None. + :paramtype kind: str or ~azure.ai.projects.models.MemoryItemKind + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :return: An iterator like instance of MemoryItem + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.MemoryItem] + :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[List[_models.MemoryItem]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + 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 + + def prepare_request(_continuation_token=None): + if body is _Unset: + if scope is _Unset: + raise TypeError("missing required argument: scope") + body = {"scope": scope} + body = {k: v for k, v in body.items() if v is not None} + + _request = build_beta_memory_stores_list_memories_request( + name=name, + kind=kind, + limit=limit, + order=order, + after=_continuation_token, + before=before, + 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) + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.MemoryItem], + deserialized.get("data", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("last_id") or None, AsyncList(list_of_elem) + + async def get_next(_continuation_token=None): + _request = prepare_request(_continuation_token) + + _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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace_async + async def delete_memory(self, name: str, memory_id: str, **kwargs: Any) -> _models.DeleteMemoryResponse: + """Delete a memory item from a memory store. + + :param name: The name of the memory store. Required. + :type name: str + :param memory_id: The ID of the memory item to delete. Required. + :type memory_id: str + :return: DeleteMemoryResponse. The DeleteMemoryResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DeleteMemoryResponse + :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.DeleteMemoryResponse] = kwargs.pop("cls", None) + + _request = build_beta_memory_stores_delete_memory_request( + name=name, + memory_id=memory_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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.DeleteMemoryResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class BetaModelsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.aio.AIProjectClient`'s + :attr:`models` 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: AIProjectClientConfiguration = 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_versions(self, name: str, **kwargs: Any) -> AsyncItemPaged["_models.ModelVersion"]: + """List all versions of the given ModelVersion. + + :param name: The name of the resource. Required. + :type name: str + :return: An iterator like instance of ModelVersion + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.ModelVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ModelVersion]] = 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_beta_models_list_versions_request( + name=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) + + 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, + headers=_headers, + ) + 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.ModelVersion], + 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 + def list(self, **kwargs: Any) -> AsyncItemPaged["_models.ModelVersion"]: + """List the latest version of each ModelVersion. + + :return: An iterator like instance of ModelVersion + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.ModelVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ModelVersion]] = 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_beta_models_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, + headers=_headers, + ) + 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.ModelVersion], + 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(self, name: str, version: str, **kwargs: Any) -> _models.ModelVersion: + """Get the specific version of the ModelVersion. The service returns 404 Not Found error if the + ModelVersion does not exist. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the ModelVersion to retrieve. Required. + :type version: str + :return: ModelVersion. The ModelVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.ModelVersion + :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.ModelVersion] = kwargs.pop("cls", None) + + _request = build_beta_models_get_request( + name=name, + version=version, + 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.ModelVersion, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def delete(self, name: str, version: str, **kwargs: Any) -> None: + """Delete the specific version of the ModelVersion. The service returns 200 OK if the ModelVersion + was deleted successfully or if the ModelVersion does not exist. + + :param name: The name of the resource. Required. + :type name: str + :param version: The version of the ModelVersion to delete. Required. + :type version: str + :return: None + :rtype: None + :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[None] = kwargs.pop("cls", None) + + _request = build_beta_models_delete_request( + name=name, + version=version, + 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) + + _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) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + async def update( + self, + name: str, + version: str, + body: _models.UpdateModelVersionRequest, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> _models.ModelVersion: + """Update an existing ModelVersion with the given version id. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the UpdateModelVersionRequest to create or update. + Required. + :type version: str + :param body: The UpdateModelVersionRequest to create or update. Required. + :type body: ~azure.ai.projects.models.UpdateModelVersionRequest + :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: ModelVersion. The ModelVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.ModelVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, name: str, version: str, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> _models.ModelVersion: + """Update an existing ModelVersion with the given version id. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the UpdateModelVersionRequest to create or update. + Required. + :type version: str + :param body: The UpdateModelVersionRequest to create or update. Required. + :type body: 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: ModelVersion. The ModelVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.ModelVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def update( + self, + name: str, + version: str, + body: IO[bytes], + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> _models.ModelVersion: + """Update an existing ModelVersion with the given version id. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the UpdateModelVersionRequest to create or update. + Required. + :type version: str + :param body: The UpdateModelVersionRequest to create or update. Required. + :type body: 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: ModelVersion. The ModelVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.ModelVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update( + self, name: str, version: str, body: Union[_models.UpdateModelVersionRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.ModelVersion: + """Update an existing ModelVersion with the given version id. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the UpdateModelVersionRequest to create or update. + Required. + :type version: str + :param body: The UpdateModelVersionRequest to create or update. Is one of the following types: + UpdateModelVersionRequest, JSON, IO[bytes] Required. + :type body: ~azure.ai.projects.models.UpdateModelVersionRequest or JSON or IO[bytes] + :return: ModelVersion. The ModelVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.ModelVersion + :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.ModelVersion] = kwargs.pop("cls", None) + + content_type = content_type or "application/merge-patch+json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_beta_models_update_request( + name=name, + version=version, + 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.ModelVersion, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def create_async( + self, + name: str, + version: str, + body: _models.ModelVersion, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.CreateAsyncResponse: + """Creates a model version asynchronously with blob content validation. Returns 202 Accepted with + a Location header for polling. + + :param name: Name of the model. Required. + :type name: str + :param version: Version of the model. Required. + :type version: str + :param body: Model version to create. Required. + :type body: ~azure.ai.projects.models.ModelVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CreateAsyncResponse. The CreateAsyncResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.CreateAsyncResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_async( + self, name: str, version: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CreateAsyncResponse: + """Creates a model version asynchronously with blob content validation. Returns 202 Accepted with + a Location header for polling. + + :param name: Name of the model. Required. + :type name: str + :param version: Version of the model. Required. + :type version: str + :param body: Model version to create. 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: CreateAsyncResponse. The CreateAsyncResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.CreateAsyncResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create_async( + self, name: str, version: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CreateAsyncResponse: + """Creates a model version asynchronously with blob content validation. Returns 202 Accepted with + a Location header for polling. + + :param name: Name of the model. Required. + :type name: str + :param version: Version of the model. Required. + :type version: str + :param body: Model version to create. 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: CreateAsyncResponse. The CreateAsyncResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.CreateAsyncResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_async( + self, name: str, version: str, body: Union[_models.ModelVersion, JSON, IO[bytes]], **kwargs: Any + ) -> _models.CreateAsyncResponse: + """Creates a model version asynchronously with blob content validation. Returns 202 Accepted with + a Location header for polling. + + :param name: Name of the model. Required. + :type name: str + :param version: Version of the model. Required. + :type version: str + :param body: Model version to create. Is one of the following types: ModelVersion, JSON, + IO[bytes] Required. + :type body: ~azure.ai.projects.models.ModelVersion or JSON or IO[bytes] + :return: CreateAsyncResponse. The CreateAsyncResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.CreateAsyncResponse + :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.CreateAsyncResponse] = 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_beta_models_create_async_request( + name=name, + version=version, + 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 [202]: + 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) + + response_headers = {} + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.CreateAsyncResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @overload + async def pending_upload( + self, + name: str, + version: str, + body: _models.ModelPendingUploadRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ModelPendingUploadResponse: + """Start or retrieve a pending upload for a model version. + + :param name: Name of the model. Required. + :type name: str + :param version: Version of the model. Required. + :type version: str + :param body: Required. + :type body: ~azure.ai.projects.models.ModelPendingUploadRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ModelPendingUploadResponse. The ModelPendingUploadResponse is compatible with + MutableMapping + :rtype: ~azure.ai.projects.models.ModelPendingUploadResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def pending_upload( + self, name: str, version: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ModelPendingUploadResponse: + """Start or retrieve a pending upload for a model version. + + :param name: Name of the model. Required. + :type name: str + :param version: Version of the model. Required. + :type version: 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: ModelPendingUploadResponse. The ModelPendingUploadResponse is compatible with + MutableMapping + :rtype: ~azure.ai.projects.models.ModelPendingUploadResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def pending_upload( + self, name: str, version: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ModelPendingUploadResponse: + """Start or retrieve a pending upload for a model version. + + :param name: Name of the model. Required. + :type name: str + :param version: Version of the model. Required. + :type version: 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: ModelPendingUploadResponse. The ModelPendingUploadResponse is compatible with + MutableMapping + :rtype: ~azure.ai.projects.models.ModelPendingUploadResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def pending_upload( + self, name: str, version: str, body: Union[_models.ModelPendingUploadRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.ModelPendingUploadResponse: + """Start or retrieve a pending upload for a model version. + + :param name: Name of the model. Required. + :type name: str + :param version: Version of the model. Required. + :type version: str + :param body: Is one of the following types: ModelPendingUploadRequest, JSON, IO[bytes] + Required. + :type body: ~azure.ai.projects.models.ModelPendingUploadRequest or JSON or IO[bytes] + :return: ModelPendingUploadResponse. The ModelPendingUploadResponse is compatible with + MutableMapping + :rtype: ~azure.ai.projects.models.ModelPendingUploadResponse + :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.ModelPendingUploadResponse] = 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_beta_models_pending_upload_request( + name=name, + version=version, + 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]: + 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.ModelPendingUploadResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + async def get_credentials( + self, + name: str, + version: str, + body: _models.ModelCredentialRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DatasetCredential: + """Get credentials for a model version asset. + + :param name: Name of the model. Required. + :type name: str + :param version: Version of the model. Required. + :type version: str + :param body: Required. + :type body: ~azure.ai.projects.models.ModelCredentialRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: DatasetCredential. The DatasetCredential is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetCredential + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def get_credentials( + self, name: str, version: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.DatasetCredential: + """Get credentials for a model version asset. + + :param name: Name of the model. Required. + :type name: str + :param version: Version of the model. Required. + :type version: 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: DatasetCredential. The DatasetCredential is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetCredential + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def get_credentials( + self, name: str, version: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.DatasetCredential: + """Get credentials for a model version asset. + + :param name: Name of the model. Required. + :type name: str + :param version: Version of the model. Required. + :type version: 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: DatasetCredential. The DatasetCredential is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetCredential + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def get_credentials( + self, name: str, version: str, body: Union[_models.ModelCredentialRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.DatasetCredential: + """Get credentials for a model version asset. + + :param name: Name of the model. Required. + :type name: str + :param version: Version of the model. Required. + :type version: str + :param body: Is one of the following types: ModelCredentialRequest, JSON, IO[bytes] Required. + :type body: ~azure.ai.projects.models.ModelCredentialRequest or JSON or IO[bytes] + :return: DatasetCredential. The DatasetCredential is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetCredential + :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.DatasetCredential] = 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_beta_models_get_credentials_request( + name=name, + version=version, + 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]: + 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.DatasetCredential, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class BetaRedTeamsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.aio.AIProjectClient`'s + :attr:`red_teams` 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: AIProjectClientConfiguration = 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_async + async def get(self, name: str, **kwargs: Any) -> _models.RedTeam: + """Get a redteam by name. + + :param name: Identifier of the red team run. Required. + :type name: str + :return: RedTeam. The RedTeam is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.RedTeam + :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.RedTeam] = kwargs.pop("cls", None) + + _request = build_beta_red_teams_get_request( + name=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.RedTeam, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, **kwargs: Any) -> AsyncItemPaged["_models.RedTeam"]: + """List a redteam by name. + + :return: An iterator like instance of RedTeam + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.RedTeam] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.RedTeam]] = 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_beta_red_teams_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, + headers=_headers, + ) + 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 - :param name: The name of the memory store to update. Required. - :type name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword scope: The namespace that logically groups and isolates memories, such as a user ID. + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.RedTeam], + 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) + + @overload + async def create( + self, red_team: _models.RedTeam, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RedTeam: + """Creates a redteam run. + + :param red_team: Redteam to be run. Required. + :type red_team: ~azure.ai.projects.models.RedTeam + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RedTeam. The RedTeam is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.RedTeam + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create(self, red_team: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.RedTeam: + """Creates a redteam run. + + :param red_team: Redteam to be run. Required. + :type red_team: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RedTeam. The RedTeam is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.RedTeam + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def create( + self, red_team: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RedTeam: + """Creates a redteam run. + + :param red_team: Redteam to be run. Required. + :type red_team: 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: RedTeam. The RedTeam is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.RedTeam + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create(self, red_team: Union[_models.RedTeam, JSON, IO[bytes]], **kwargs: Any) -> _models.RedTeam: + """Creates a redteam run. + + :param red_team: Redteam to be run. Is one of the following types: RedTeam, JSON, IO[bytes] Required. - :paramtype scope: str - :keyword items: Conversation items to be stored in memory. Default value is None. - :paramtype items: list[dict[str, any]] - :keyword previous_update_id: The unique ID of the previous update request, enabling incremental - memory updates from where the last operation left off. Default value is None. - :paramtype previous_update_id: str - :keyword update_delay: Timeout period before processing the memory update in seconds. - If a new update request is received during this period, it will cancel the current request and - reset the timeout. - Set to 0 to immediately trigger the update without delay. - Defaults to 300 (5 minutes). Default value is None. - :paramtype update_delay: int - :return: An instance of AsyncLROPoller that returns MemoryStoreUpdateCompletedResult. The - MemoryStoreUpdateCompletedResult is compatible with MutableMapping - :rtype: - ~azure.core.polling.AsyncLROPoller[~azure.ai.projects.models.MemoryStoreUpdateCompletedResult] + :type red_team: ~azure.ai.projects.models.RedTeam or JSON or IO[bytes] + :return: RedTeam. The RedTeam is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.RedTeam :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.MemoryStoreUpdateCompletedResult] = 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._update_memories_initial( - name=name, - body=body, - scope=scope, - items=items, - previous_update_id=previous_update_id, - update_delay=update_delay, - 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") - ) + cls: ClsType[_models.RedTeam] = kwargs.pop("cls", None) - deserialized = _deserialize(_models.MemoryStoreUpdateCompletedResult, response.json().get("result", {})) - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized + content_type = content_type or "application/json" + _content = None + if isinstance(red_team, (IOBase, bytes)): + _content = red_team + else: + _content = json.dumps(red_team, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _request = build_beta_red_teams_create_request( + 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) - if polling is True: - polling_method: AsyncPollingMethod = cast( - AsyncPollingMethod, - AsyncLROBasePolling(lro_delay, path_format_arguments=path_format_arguments, **kwargs), + _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 [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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, ) - elif polling is False: - polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - polling_method = polling - if cont_token: - return AsyncLROPoller[_models.MemoryStoreUpdateCompletedResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return AsyncLROPoller[_models.MemoryStoreUpdateCompletedResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) + deserialized = _deserialize(_models.RedTeam, response.json()) - @overload - async def delete_scope( - self, name: str, *, scope: str, content_type: str = "application/json", **kwargs: Any - ) -> _models.MemoryStoreDeleteScopeResult: - """Delete all memories associated with a specific scope from a memory store. + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - :param name: The name of the memory store. Required. - :type name: str - :keyword scope: The namespace that logically groups and isolates memories to delete, such as a - user ID. Required. - :paramtype scope: str + return deserialized # type: ignore + + +class BetaRoutinesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.aio.AIProjectClient`'s + :attr:`routines` 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: AIProjectClientConfiguration = 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, + routine_name: str, + *, + triggers: dict[str, _models.RoutineTrigger], + action: _models.RoutineAction, + content_type: str = "application/json", + description: Optional[str] = None, + enabled: Optional[bool] = None, + **kwargs: Any + ) -> _models.Routine: + """Create or update a routine. + + :param routine_name: The unique name of the routine. Required. + :type routine_name: str + :keyword triggers: The triggers configured for the routine. In v1, exactly one trigger entry is + supported. Required. + :paramtype triggers: dict[str, ~azure.ai.projects.models.RoutineTrigger] + :keyword action: The action executed when the routine fires. Required. + :paramtype action: ~azure.ai.projects.models.RoutineAction :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: MemoryStoreDeleteScopeResult. The MemoryStoreDeleteScopeResult is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDeleteScopeResult + :keyword description: A human-readable description of the routine. Default value is None. + :paramtype description: str + :keyword enabled: Whether the routine is enabled. Default value is None. + :paramtype enabled: bool + :return: Routine. The Routine is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Routine :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def delete_scope( - self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.MemoryStoreDeleteScopeResult: - """Delete all memories associated with a specific scope from a memory store. + async def create_or_update( + self, routine_name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Routine: + """Create or update a routine. - :param name: The name of the memory store. Required. - :type name: str + :param routine_name: The unique name of the routine. Required. + :type routine_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: MemoryStoreDeleteScopeResult. The MemoryStoreDeleteScopeResult is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDeleteScopeResult + :return: Routine. The Routine is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Routine :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def delete_scope( - self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.MemoryStoreDeleteScopeResult: - """Delete all memories associated with a specific scope from a memory store. + async def create_or_update( + self, routine_name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Routine: + """Create or update a routine. - :param name: The name of the memory store. Required. - :type name: str + :param routine_name: The unique name of the routine. Required. + :type routine_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: MemoryStoreDeleteScopeResult. The MemoryStoreDeleteScopeResult is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDeleteScopeResult + :return: Routine. The Routine is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Routine :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def delete_scope( - self, name: str, body: Union[JSON, IO[bytes]] = _Unset, *, scope: str = _Unset, **kwargs: Any - ) -> _models.MemoryStoreDeleteScopeResult: - """Delete all memories associated with a specific scope from a memory store. + async def create_or_update( + self, + routine_name: str, + body: Union[JSON, IO[bytes]] = _Unset, + *, + triggers: dict[str, _models.RoutineTrigger] = _Unset, + action: _models.RoutineAction = _Unset, + description: Optional[str] = None, + enabled: Optional[bool] = None, + **kwargs: Any + ) -> _models.Routine: + """Create or update a routine. - :param name: The name of the memory store. Required. - :type name: str + :param routine_name: The unique name of the routine. Required. + :type routine_name: str :param body: Is either a JSON type or a IO[bytes] type. Required. :type body: JSON or IO[bytes] - :keyword scope: The namespace that logically groups and isolates memories to delete, such as a - user ID. Required. - :paramtype scope: str - :return: MemoryStoreDeleteScopeResult. The MemoryStoreDeleteScopeResult is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDeleteScopeResult + :keyword triggers: The triggers configured for the routine. In v1, exactly one trigger entry is + supported. Required. + :paramtype triggers: dict[str, ~azure.ai.projects.models.RoutineTrigger] + :keyword action: The action executed when the routine fires. Required. + :paramtype action: ~azure.ai.projects.models.RoutineAction + :keyword description: A human-readable description of the routine. Default value is None. + :paramtype description: str + :keyword enabled: Whether the routine is enabled. Default value is None. + :paramtype enabled: bool + :return: Routine. The Routine is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Routine :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -7273,12 +10353,14 @@ async def delete_scope( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.MemoryStoreDeleteScopeResult] = kwargs.pop("cls", None) + cls: ClsType[_models.Routine] = kwargs.pop("cls", None) if body is _Unset: - if scope is _Unset: - raise TypeError("missing required argument: scope") - body = {"scope": scope} + if triggers is _Unset: + raise TypeError("missing required argument: triggers") + if action is _Unset: + raise TypeError("missing required argument: action") + body = {"action": action, "description": description, "enabled": enabled, "triggers": triggers} body = {k: v for k, v in body.items() if v is not None} content_type = content_type or "application/json" _content = None @@ -7287,8 +10369,8 @@ async def delete_scope( else: _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_memory_stores_delete_scope_request( - name=name, + _request = build_beta_routines_create_or_update_request( + routine_name=routine_name, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -7308,55 +10390,322 @@ async def delete_scope( 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) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Routine, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def get(self, routine_name: str, **kwargs: Any) -> _models.Routine: + """Retrieve a routine. + + :param routine_name: The unique name of the routine. Required. + :type routine_name: str + :return: Routine. The Routine is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Routine + :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.Routine] = kwargs.pop("cls", None) + + _request = build_beta_routines_get_request( + routine_name=routine_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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Routine, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def enable(self, routine_name: str, **kwargs: Any) -> _models.Routine: + """Enable a routine. + + :param routine_name: The unique name of the routine. Required. + :type routine_name: str + :return: Routine. The Routine is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Routine + :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.Routine] = kwargs.pop("cls", None) + + _request = build_beta_routines_enable_request( + routine_name=routine_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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Routine, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace_async + async def disable(self, routine_name: str, **kwargs: Any) -> _models.Routine: + """Disable a routine. + + :param routine_name: The unique name of the routine. Required. + :type routine_name: str + :return: Routine. The Routine is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Routine + :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.Routine] = kwargs.pop("cls", None) + + _request = build_beta_routines_disable_request( + routine_name=routine_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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Routine, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, + *, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + before: Optional[str] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.Routine"]: + """List routines. + + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :return: An iterator like instance of Routine + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.Routine] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Routine]] = 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(_continuation_token=None): + + _request = build_beta_routines_list_request( + limit=limit, + order=order, + after=_continuation_token, + before=before, + api_version=self._config.api_version, + headers=_headers, + params=_params, ) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.MemoryStoreDeleteScopeResult, response.json()) + 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 - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.Routine], + deserialized.get("data", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("last_id") or None, AsyncList(list_of_elem) - return deserialized # type: ignore + async def get_next(_continuation_token=None): + _request = prepare_request(_continuation_token) + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response -class BetaRedTeamsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) - Instead, you should access the following operations through - :class:`~azure.ai.projects.aio.AIProjectClient`'s - :attr:`red_teams` attribute. - """ + return pipeline_response - 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: AIProjectClientConfiguration = 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") + return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def get(self, name: str, **kwargs: Any) -> _models.RedTeam: - """Get a redteam by name. + async def delete(self, routine_name: str, **kwargs: Any) -> None: + """Delete a routine. - :param name: Identifier of the red team run. Required. - :type name: str - :return: RedTeam. The RedTeam is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.RedTeam + :param routine_name: The unique name of the routine. Required. + :type routine_name: str + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -7370,10 +10719,10 @@ async def get(self, name: str, **kwargs: Any) -> _models.RedTeam: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.RedTeam] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_beta_red_teams_get_request( - name=name, + _request = build_beta_routines_delete_request( + routine_name=routine_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -7383,45 +10732,64 @@ async def get(self, name: str, **kwargs: Any) -> _models.RedTeam: } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _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 + if response.status_code not in [204]: 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.RedTeam, response.json()) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def list(self, **kwargs: Any) -> AsyncItemPaged["_models.RedTeam"]: - """List a redteam by name. - - :return: An iterator like instance of RedTeam - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.RedTeam] + def list_runs( + self, + routine_name: str, + *, + filter: Optional[str] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + before: Optional[str] = None, + **kwargs: Any + ) -> AsyncItemPaged["_models.RoutineRun"]: + """List prior runs for a routine. + + :param routine_name: The unique name of the routine. Required. + :type routine_name: str + :keyword filter: An optional MLflow search-runs filter expression applied within the routine's + experiment. Default value is None. + :paramtype filter: str + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :return: An iterator like instance of RoutineRun + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.RoutineRun] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.RedTeam]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.RoutineRun]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -7431,58 +10799,37 @@ def list(self, **kwargs: Any) -> AsyncItemPaged["_models.RedTeam"]: } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: - - _request = build_beta_red_teams_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, - headers=_headers, - ) - 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) + def prepare_request(_continuation_token=None): + _request = build_beta_routines_list_runs_request( + routine_name=routine_name, + filter=filter, + limit=limit, + order=order, + after=_continuation_token, + before=before, + 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) return _request async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() list_of_elem = _deserialize( - List[_models.RedTeam], - deserialized.get("value", []), + List[_models.RoutineRun], + deserialized.get("data", []), ) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + return deserialized.get("last_id") or None, AsyncList(list_of_elem) - async def get_next(next_link=None): - _request = prepare_request(next_link) + async def get_next(_continuation_token=None): + _request = prepare_request(_continuation_token) _stream = False pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access @@ -7492,67 +10839,96 @@ async def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) return pipeline_response return AsyncItemPaged(get_next, extract_data) @overload - async def create( - self, red_team: _models.RedTeam, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.RedTeam: - """Creates a redteam run. + async def dispatch_async( + self, + routine_name: str, + *, + content_type: str = "application/json", + payload: Optional[_models.RoutineDispatchPayload] = None, + **kwargs: Any + ) -> _models.DispatchRoutineResponse: + """Queue an asynchronous routine dispatch. - :param red_team: Redteam to be run. Required. - :type red_team: ~azure.ai.projects.models.RedTeam + :param routine_name: The unique name of the routine. Required. + :type routine_name: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: RedTeam. The RedTeam is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.RedTeam + :keyword payload: A direct action-input override sent downstream when testing a routine. + Default value is None. + :paramtype payload: ~azure.ai.projects.models.RoutineDispatchPayload + :return: DispatchRoutineResponse. The DispatchRoutineResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DispatchRoutineResponse :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create(self, red_team: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.RedTeam: - """Creates a redteam run. + async def dispatch_async( + self, routine_name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.DispatchRoutineResponse: + """Queue an asynchronous routine dispatch. - :param red_team: Redteam to be run. Required. - :type red_team: JSON + :param routine_name: The unique name of the routine. Required. + :type routine_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: RedTeam. The RedTeam is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.RedTeam + :return: DispatchRoutineResponse. The DispatchRoutineResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DispatchRoutineResponse :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create( - self, red_team: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.RedTeam: - """Creates a redteam run. + async def dispatch_async( + self, routine_name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.DispatchRoutineResponse: + """Queue an asynchronous routine dispatch. - :param red_team: Redteam to be run. Required. - :type red_team: IO[bytes] + :param routine_name: The unique name of the routine. Required. + :type routine_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: RedTeam. The RedTeam is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.RedTeam + :return: DispatchRoutineResponse. The DispatchRoutineResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DispatchRoutineResponse :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def create(self, red_team: Union[_models.RedTeam, JSON, IO[bytes]], **kwargs: Any) -> _models.RedTeam: - """Creates a redteam run. + async def dispatch_async( + self, + routine_name: str, + body: Union[JSON, IO[bytes]] = _Unset, + *, + payload: Optional[_models.RoutineDispatchPayload] = None, + **kwargs: Any + ) -> _models.DispatchRoutineResponse: + """Queue an asynchronous routine dispatch. - :param red_team: Redteam to be run. Is one of the following types: RedTeam, JSON, IO[bytes] - Required. - :type red_team: ~azure.ai.projects.models.RedTeam or JSON or IO[bytes] - :return: RedTeam. The RedTeam is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.RedTeam + :param routine_name: The unique name of the routine. Required. + :type routine_name: str + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword payload: A direct action-input override sent downstream when testing a routine. + Default value is None. + :paramtype payload: ~azure.ai.projects.models.RoutineDispatchPayload + :return: DispatchRoutineResponse. The DispatchRoutineResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DispatchRoutineResponse :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -7567,16 +10943,20 @@ async def create(self, red_team: Union[_models.RedTeam, JSON, IO[bytes]], **kwar _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedTeam] = kwargs.pop("cls", None) + cls: ClsType[_models.DispatchRoutineResponse] = kwargs.pop("cls", None) + if body is _Unset: + body = {"payload": payload} + 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(red_team, (IOBase, bytes)): - _content = red_team + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(red_team, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_red_teams_create_request( + _request = build_beta_routines_dispatch_async_request( + routine_name=routine_name, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -7596,7 +10976,7 @@ async def create(self, red_team: Union[_models.RedTeam, JSON, IO[bytes]], **kwar response = pipeline_response.http_response - if response.status_code not in [201]: + if response.status_code not in [200]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -7612,7 +10992,7 @@ async def create(self, red_team: Union[_models.RedTeam, JSON, IO[bytes]], **kwar if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.RedTeam, response.json()) + deserialized = _deserialize(_models.DispatchRoutineResponse, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch.py index 3c3e527771b4..c9b8cfff7731 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/_patch.py @@ -22,8 +22,10 @@ BetaEvaluationTaxonomiesOperations, BetaEvaluatorsOperations, BetaInsightsOperations, + BetaModelsOperations, BetaOperations as GeneratedBetaOperations, BetaRedTeamsOperations, + BetaRoutinesOperations, BetaSchedulesOperations, BetaSkillsOperations, BetaToolboxesOperations, @@ -50,8 +52,12 @@ class BetaOperations(GeneratedBetaOperations): """:class:`~azure.ai.projects.aio.operations.BetaInsightsOperations` operations""" memory_stores: BetaMemoryStoresOperations """:class:`~azure.ai.projects.aio.operations.BetaMemoryStoresOperations` operations""" + models: BetaModelsOperations + """:class:`~azure.ai.projects.aio.operations.BetaModelsOperations` operations""" red_teams: BetaRedTeamsOperations """:class:`~azure.ai.projects.aio.operations.BetaRedTeamsOperations` operations""" + routines: BetaRoutinesOperations + """:class:`~azure.ai.projects.aio.operations.BetaRoutinesOperations` operations""" schedules: BetaSchedulesOperations """:class:`~azure.ai.projects.aio.operations.BetaSchedulesOperations` operations""" toolboxes: BetaToolboxesOperations @@ -86,8 +92,10 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: "BetaEvaluatorsOperations", "BetaInsightsOperations", "BetaMemoryStoresOperations", + "BetaModelsOperations", "BetaOperations", "BetaRedTeamsOperations", + "BetaRoutinesOperations", "BetaSchedulesOperations", "BetaSkillsOperations", "BetaToolboxesOperations", diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/__init__.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/__init__.py index 58d3839bdce5..1b8c85aace5a 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/__init__.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/__init__.py @@ -33,11 +33,13 @@ AgentTaxonomyInput, AgentVersionDetails, AgenticIdentityPreviewCredentials, + AgentsPagedResultOptimizationCandidate, ApiError, ApiErrorResponse, ApiKeyCredentials, ApplyPatchToolParam, ApproximateLocation, + ArtifactProfile, AutoCodeInterpreterToolParam, AzureAIAgentTarget, AzureAIModelTarget, @@ -64,6 +66,8 @@ BrowserAutomationPreviewTool, BrowserAutomationToolConnectionParameters, BrowserAutomationToolParameters, + CandidateDeployConfig, + CandidateResults, CaptureStructuredOutputsTool, ChartCoordinate, ChatSummaryMemoryItem, @@ -87,6 +91,7 @@ CosmosDBIndex, CreateAgentVersionFromCodeContent, CreateAgentVersionFromCodeMetadata, + CreateAsyncResponse, CronTrigger, CustomCredential, CustomGrammarFormatParam, @@ -98,6 +103,7 @@ DataGenerationJobInputs, DataGenerationJobOptions, DataGenerationJobOutput, + DataGenerationJobOutputOptions, DataGenerationJobResult, DataGenerationJobSource, DataGenerationModelOptions, @@ -106,22 +112,30 @@ DatasetDataGenerationJobOutput, DatasetDataGenerationJobSource, DatasetEvaluatorGenerationJobSource, + DatasetItem, + DatasetRef, DatasetReference, DatasetVersion, DeleteAgentResponse, DeleteAgentVersionResponse, + DeleteMemoryResponse, DeleteMemoryStoreResult, DeleteSkillResult, Deployment, + Dimension, + DispatchRoutineResponse, EmbeddingConfiguration, EntraAuthorizationScheme, EntraIDCredentials, + EntraIsolationKeySource, EvalResult, + EvalRunOutputItemResult, EvalRunResultCompareItem, EvalRunResultComparison, EvalRunResultSummary, EvaluationComparisonInsightRequest, EvaluationComparisonInsightResult, + EvaluationCriterion, EvaluationResultSample, EvaluationRule, EvaluationRuleAction, @@ -129,8 +143,10 @@ EvaluationRunClusterInsightRequest, EvaluationRunClusterInsightResult, EvaluationScheduleTask, + EvaluationTarget, EvaluationTaxonomy, EvaluationTaxonomyInput, + EvaluatorCredentialRequest, EvaluatorDefinition, EvaluatorGenerationArtifacts, EvaluatorGenerationInputs, @@ -139,6 +155,7 @@ EvaluatorGenerationTokenUsage, EvaluatorMetric, EvaluatorVersion, + ExternalAgentDefinition, FabricDataAgentToolParameters, FabricIQPreviewTool, FieldMapping, @@ -148,11 +165,14 @@ FileSearchTool, FixedRatioVersionSelectionRule, FolderDatasetVersion, + FoundryModelWarning, FunctionShellToolParam, FunctionShellToolParamEnvironment, FunctionShellToolParamEnvironmentContainerReferenceParam, FunctionShellToolParamEnvironmentLocalEnvironmentParam, FunctionTool, + GitHubIssueOpenedRoutineTrigger, + HeaderIsolationKeySource, HeaderTelemetryEndpointAuth, HostedAgentDefinition, HourlyRecurrenceSchedule, @@ -172,8 +192,14 @@ InsightScheduleTask, InsightSummary, InsightsMetadata, + InvokeAgentInvocationsApiDispatchPayload, + InvokeAgentInvocationsApiRoutineAction, + InvokeAgentResponsesApiDispatchPayload, + InvokeAgentResponsesApiRoutineAction, + IsolationKeySource, LocalShellToolParam, LocalSkillParam, + LoraConfig, MCPTool, MCPToolFilter, MCPToolRequireApproval, @@ -194,9 +220,14 @@ MemoryStoreUpdateCompletedResult, MemoryStoreUpdateResult, MicrosoftFabricPreviewTool, + ModelCredentialRequest, ModelDeployment, ModelDeploymentSku, + ModelPendingUploadRequest, + ModelPendingUploadResponse, ModelSamplingParams, + ModelSourceData, + ModelVersion, MonthlyRecurrenceSchedule, NoAuthenticationCredentials, OneTimeTrigger, @@ -209,9 +240,19 @@ OpenApiProjectConnectionAuthDetails, OpenApiProjectConnectionSecurityScheme, OpenApiTool, + OptimizationAgentDefinition, + OptimizationAgentSkill, + OptimizationCandidate, + OptimizationJob, + OptimizationJobInputs, + OptimizationJobProgress, + OptimizationJobResult, + OptimizationOptions, + OptimizationTaskResult, OtlpTelemetryEndpoint, PendingUploadRequest, PendingUploadResult, + ProceduralMemoryItem, PromptAgentDefinition, PromptAgentDefinitionTextOptions, PromptBasedEvaluatorDefinition, @@ -224,12 +265,19 @@ RecurrenceSchedule, RecurrenceTrigger, RedTeam, + RedTeamTargetConfig, ResponseUsageInputTokensDetails, ResponseUsageOutputTokensDetails, + Routine, + RoutineAction, + RoutineDispatchPayload, + RoutineRun, + RoutineRunDiagnostics, + RoutineTrigger, RubricBasedEvaluatorDefinition, - RubricCriterion, SASCredentials, Schedule, + ScheduleRoutineTrigger, ScheduleRun, ScheduleTask, SessionDirectoryEntry, @@ -245,8 +293,7 @@ SpecificFunctionShellParam, StructuredInputDefinition, StructuredOutputDefinition, - Target, - TargetConfig, + SystemDataV3, TaxonomyCategory, TaxonomySubCategory, TelemetryConfig, @@ -256,6 +303,7 @@ TextResponseFormatJsonObject, TextResponseFormatJsonSchema, TextResponseFormatText, + TimerRoutineTrigger, Tool, ToolChoiceAllowed, ToolChoiceCodeInterpreter, @@ -268,6 +316,7 @@ ToolChoiceParam, ToolChoiceWebSearchPreview, ToolChoiceWebSearchPreview20250311, + ToolConfig, ToolDescription, ToolProjectConnection, ToolUseFineTuningDataGenerationJobOptions, @@ -279,6 +328,7 @@ TracesDataGenerationJobSource, TracesEvaluatorGenerationJobSource, Trigger, + UpdateModelVersionRequest, UpdateToolboxRequest, UserProfileMemoryItem, VersionIndicator, @@ -321,6 +371,7 @@ DatasetType, DayOfWeek, DeploymentType, + EvalRunOutputItemResultStatus, EvaluationRuleActionType, EvaluationRuleEventType, EvaluationTaxonomyInputType, @@ -330,12 +381,18 @@ EvaluatorMetricDirection, EvaluatorMetricType, EvaluatorType, + FoundryModelArtifactProfileCategory, + FoundryModelArtifactProfileSignal, + FoundryModelSourceType, + FoundryModelWarningCode, + FoundryModelWeightType, FunctionShellToolParamEnvironmentType, GrammarSyntax1, ImageGenAction, IndexType, InputFidelity, InsightType, + IsolationKeySourceKind, JobStatus, MemoryItemKind, MemoryOperationKind, @@ -344,11 +401,18 @@ MemoryStoreUpdateStatus, OpenApiAuthType, OperationState, + OptimizationMode, + OptimizationStrategy, PageOrder, PendingUploadType, RankerVersionType, RecurrenceType, RiskCategory, + RoutineActionType, + RoutineAttemptSource, + RoutineDispatchPayloadType, + RoutineRunPhase, + RoutineTriggerType, SampleType, ScheduleProvisioningStatus, ScheduleTaskType, @@ -391,11 +455,13 @@ "AgentTaxonomyInput", "AgentVersionDetails", "AgenticIdentityPreviewCredentials", + "AgentsPagedResultOptimizationCandidate", "ApiError", "ApiErrorResponse", "ApiKeyCredentials", "ApplyPatchToolParam", "ApproximateLocation", + "ArtifactProfile", "AutoCodeInterpreterToolParam", "AzureAIAgentTarget", "AzureAIModelTarget", @@ -422,6 +488,8 @@ "BrowserAutomationPreviewTool", "BrowserAutomationToolConnectionParameters", "BrowserAutomationToolParameters", + "CandidateDeployConfig", + "CandidateResults", "CaptureStructuredOutputsTool", "ChartCoordinate", "ChatSummaryMemoryItem", @@ -445,6 +513,7 @@ "CosmosDBIndex", "CreateAgentVersionFromCodeContent", "CreateAgentVersionFromCodeMetadata", + "CreateAsyncResponse", "CronTrigger", "CustomCredential", "CustomGrammarFormatParam", @@ -456,6 +525,7 @@ "DataGenerationJobInputs", "DataGenerationJobOptions", "DataGenerationJobOutput", + "DataGenerationJobOutputOptions", "DataGenerationJobResult", "DataGenerationJobSource", "DataGenerationModelOptions", @@ -464,22 +534,30 @@ "DatasetDataGenerationJobOutput", "DatasetDataGenerationJobSource", "DatasetEvaluatorGenerationJobSource", + "DatasetItem", + "DatasetRef", "DatasetReference", "DatasetVersion", "DeleteAgentResponse", "DeleteAgentVersionResponse", + "DeleteMemoryResponse", "DeleteMemoryStoreResult", "DeleteSkillResult", "Deployment", + "Dimension", + "DispatchRoutineResponse", "EmbeddingConfiguration", "EntraAuthorizationScheme", "EntraIDCredentials", + "EntraIsolationKeySource", "EvalResult", + "EvalRunOutputItemResult", "EvalRunResultCompareItem", "EvalRunResultComparison", "EvalRunResultSummary", "EvaluationComparisonInsightRequest", "EvaluationComparisonInsightResult", + "EvaluationCriterion", "EvaluationResultSample", "EvaluationRule", "EvaluationRuleAction", @@ -487,8 +565,10 @@ "EvaluationRunClusterInsightRequest", "EvaluationRunClusterInsightResult", "EvaluationScheduleTask", + "EvaluationTarget", "EvaluationTaxonomy", "EvaluationTaxonomyInput", + "EvaluatorCredentialRequest", "EvaluatorDefinition", "EvaluatorGenerationArtifacts", "EvaluatorGenerationInputs", @@ -497,6 +577,7 @@ "EvaluatorGenerationTokenUsage", "EvaluatorMetric", "EvaluatorVersion", + "ExternalAgentDefinition", "FabricDataAgentToolParameters", "FabricIQPreviewTool", "FieldMapping", @@ -506,11 +587,14 @@ "FileSearchTool", "FixedRatioVersionSelectionRule", "FolderDatasetVersion", + "FoundryModelWarning", "FunctionShellToolParam", "FunctionShellToolParamEnvironment", "FunctionShellToolParamEnvironmentContainerReferenceParam", "FunctionShellToolParamEnvironmentLocalEnvironmentParam", "FunctionTool", + "GitHubIssueOpenedRoutineTrigger", + "HeaderIsolationKeySource", "HeaderTelemetryEndpointAuth", "HostedAgentDefinition", "HourlyRecurrenceSchedule", @@ -530,8 +614,14 @@ "InsightScheduleTask", "InsightSummary", "InsightsMetadata", + "InvokeAgentInvocationsApiDispatchPayload", + "InvokeAgentInvocationsApiRoutineAction", + "InvokeAgentResponsesApiDispatchPayload", + "InvokeAgentResponsesApiRoutineAction", + "IsolationKeySource", "LocalShellToolParam", "LocalSkillParam", + "LoraConfig", "MCPTool", "MCPToolFilter", "MCPToolRequireApproval", @@ -552,9 +642,14 @@ "MemoryStoreUpdateCompletedResult", "MemoryStoreUpdateResult", "MicrosoftFabricPreviewTool", + "ModelCredentialRequest", "ModelDeployment", "ModelDeploymentSku", + "ModelPendingUploadRequest", + "ModelPendingUploadResponse", "ModelSamplingParams", + "ModelSourceData", + "ModelVersion", "MonthlyRecurrenceSchedule", "NoAuthenticationCredentials", "OneTimeTrigger", @@ -567,9 +662,19 @@ "OpenApiProjectConnectionAuthDetails", "OpenApiProjectConnectionSecurityScheme", "OpenApiTool", + "OptimizationAgentDefinition", + "OptimizationAgentSkill", + "OptimizationCandidate", + "OptimizationJob", + "OptimizationJobInputs", + "OptimizationJobProgress", + "OptimizationJobResult", + "OptimizationOptions", + "OptimizationTaskResult", "OtlpTelemetryEndpoint", "PendingUploadRequest", "PendingUploadResult", + "ProceduralMemoryItem", "PromptAgentDefinition", "PromptAgentDefinitionTextOptions", "PromptBasedEvaluatorDefinition", @@ -582,12 +687,19 @@ "RecurrenceSchedule", "RecurrenceTrigger", "RedTeam", + "RedTeamTargetConfig", "ResponseUsageInputTokensDetails", "ResponseUsageOutputTokensDetails", + "Routine", + "RoutineAction", + "RoutineDispatchPayload", + "RoutineRun", + "RoutineRunDiagnostics", + "RoutineTrigger", "RubricBasedEvaluatorDefinition", - "RubricCriterion", "SASCredentials", "Schedule", + "ScheduleRoutineTrigger", "ScheduleRun", "ScheduleTask", "SessionDirectoryEntry", @@ -603,8 +715,7 @@ "SpecificFunctionShellParam", "StructuredInputDefinition", "StructuredOutputDefinition", - "Target", - "TargetConfig", + "SystemDataV3", "TaxonomyCategory", "TaxonomySubCategory", "TelemetryConfig", @@ -614,6 +725,7 @@ "TextResponseFormatJsonObject", "TextResponseFormatJsonSchema", "TextResponseFormatText", + "TimerRoutineTrigger", "Tool", "ToolChoiceAllowed", "ToolChoiceCodeInterpreter", @@ -626,6 +738,7 @@ "ToolChoiceParam", "ToolChoiceWebSearchPreview", "ToolChoiceWebSearchPreview20250311", + "ToolConfig", "ToolDescription", "ToolProjectConnection", "ToolUseFineTuningDataGenerationJobOptions", @@ -637,6 +750,7 @@ "TracesDataGenerationJobSource", "TracesEvaluatorGenerationJobSource", "Trigger", + "UpdateModelVersionRequest", "UpdateToolboxRequest", "UserProfileMemoryItem", "VersionIndicator", @@ -676,6 +790,7 @@ "DatasetType", "DayOfWeek", "DeploymentType", + "EvalRunOutputItemResultStatus", "EvaluationRuleActionType", "EvaluationRuleEventType", "EvaluationTaxonomyInputType", @@ -685,12 +800,18 @@ "EvaluatorMetricDirection", "EvaluatorMetricType", "EvaluatorType", + "FoundryModelArtifactProfileCategory", + "FoundryModelArtifactProfileSignal", + "FoundryModelSourceType", + "FoundryModelWarningCode", + "FoundryModelWeightType", "FunctionShellToolParamEnvironmentType", "GrammarSyntax1", "ImageGenAction", "IndexType", "InputFidelity", "InsightType", + "IsolationKeySourceKind", "JobStatus", "MemoryItemKind", "MemoryOperationKind", @@ -699,11 +820,18 @@ "MemoryStoreUpdateStatus", "OpenApiAuthType", "OperationState", + "OptimizationMode", + "OptimizationStrategy", "PageOrder", "PendingUploadType", "RankerVersionType", "RecurrenceType", "RiskCategory", + "RoutineActionType", + "RoutineAttemptSource", + "RoutineDispatchPayloadType", + "RoutineRunPhase", + "RoutineTriggerType", "SampleType", "ScheduleProvisioningStatus", "ScheduleTaskType", diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_enums.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_enums.py index 40648951bbda..f728019a7cb4 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_enums.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_enums.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -17,19 +18,17 @@ class _AgentDefinitionOptInKeys(str, Enum, metaclass=CaseInsensitiveEnumMeta): """HOSTED_AGENTS_V1_PREVIEW.""" WORKFLOW_AGENTS_V1_PREVIEW = "WorkflowAgents=V1Preview" """WORKFLOW_AGENTS_V1_PREVIEW.""" - CONTAINER_AGENTS_V1_PREVIEW = "ContainerAgents=V1Preview" - """CONTAINER_AGENTS_V1_PREVIEW.""" AGENT_ENDPOINT_V1_PREVIEW = "AgentEndpoints=V1Preview" """AGENT_ENDPOINT_V1_PREVIEW.""" CODE_AGENTS_V1_PREVIEW = "CodeAgents=V1Preview" """CODE_AGENTS_V1_PREVIEW.""" + EXTERNAL_AGENTS_V1_PREVIEW = "ExternalAgents=V1Preview" + """EXTERNAL_AGENTS_V1_PREVIEW.""" class _FoundryFeaturesOptInKeys(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Type of _FoundryFeaturesOptInKeys.""" - SKILLS_V1_PREVIEW = "Skills=V1Preview" - """SKILLS_V1_PREVIEW.""" EVALUATIONS_V1_PREVIEW = "Evaluations=V1Preview" """EVALUATIONS_V1_PREVIEW.""" SCHEDULES_V1_PREVIEW = "Schedules=V1Preview" @@ -40,10 +39,16 @@ class _FoundryFeaturesOptInKeys(str, Enum, metaclass=CaseInsensitiveEnumMeta): """INSIGHTS_V1_PREVIEW.""" MEMORY_STORES_V1_PREVIEW = "MemoryStores=V1Preview" """MEMORY_STORES_V1_PREVIEW.""" - TOOLBOXES_V1_PREVIEW = "Toolboxes=V1Preview" - """TOOLBOXES_V1_PREVIEW.""" + ROUTINES_V1_PREVIEW = "Routines=V1Preview" + """ROUTINES_V1_PREVIEW.""" + SKILLS_V1_PREVIEW = "Skills=V1Preview" + """SKILLS_V1_PREVIEW.""" DATA_GENERATION_JOBS_V1_PREVIEW = "DataGenerationJobs=V1Preview" """DATA_GENERATION_JOBS_V1_PREVIEW.""" + MODELS_V1_PREVIEW = "Models=V1Preview" + """MODELS_V1_PREVIEW.""" + AGENTS_OPTIMIZATION_V1_PREVIEW = "AgentsOptimization=V1Preview" + """AGENTS_OPTIMIZATION_V1_PREVIEW.""" class AgentBlueprintReferenceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -73,6 +78,8 @@ class AgentEndpointProtocol(str, Enum, metaclass=CaseInsensitiveEnumMeta): """RESPONSES.""" A2A = "a2a" """A2A.""" + MCP = "mcp" + """MCP.""" INVOCATIONS = "invocations" """INVOCATIONS.""" @@ -86,6 +93,8 @@ class AgentKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): """HOSTED.""" WORKFLOW = "workflow" """WORKFLOW.""" + EXTERNAL = "external" + """EXTERNAL.""" class AgentObjectType(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -110,6 +119,8 @@ class AgentProtocol(str, Enum, metaclass=CaseInsensitiveEnumMeta): """ACTIVITY_PROTOCOL.""" RESPONSES = "responses" """RESPONSES.""" + MCP = "mcp" + """MCP.""" INVOCATIONS = "invocations" """INVOCATIONS.""" @@ -424,6 +435,17 @@ class DeploymentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Model deployment.""" +class EvalRunOutputItemResultStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The evaluation status for an evaluation run output item result.""" + + COMPLETED = "completed" + """The evaluator completed successfully for this result item.""" + ERRORED = "errored" + """The evaluator encountered an error for this result item.""" + SKIPPED = "skipped" + """The evaluator skipped this result item.""" + + class EvaluationRuleActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Type of the evaluation action.""" @@ -475,9 +497,9 @@ class EvaluatorDefinitionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Service-based evaluator.""" OPENAI_GRADERS = "openai_graders" """OpenAI graders.""" - RUBRICS = "rubrics" - """Rubric-based evaluator definition. Stores rubric criteria for both quality and safety - evaluators. Can be created via the generate API or manually via createVersion.""" + RUBRIC = "rubric" + """Rubric-based evaluator definition. Stores dimensions (the scoring blueprint) for both quality + and safety evaluators. Can be created via the generate API or manually via createVersion.""" class EvaluatorGenerationJobSourceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -526,6 +548,61 @@ class EvaluatorType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Custom evaluator.""" +class FoundryModelArtifactProfileCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The artifact profile category.""" + + DATA_ONLY = "DataOnly" + """Data only artifacts.""" + RUNTIME_DEPENDENT = "RuntimeDependent" + """Runtime dependent artifacts.""" + UNKNOWN = "Unknown" + """Unknown category.""" + + +class FoundryModelArtifactProfileSignal(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Signals detected in the model artifact.""" + + PICKLE_DESERIALIZATION = "PickleDeserialization" + """Pickle deserialization detected.""" + CUSTOM_PYTHON_CODE = "CustomPythonCode" + """Custom Python code detected.""" + DYNAMIC_OPS = "DynamicOps" + """Dynamic operations detected.""" + NATIVE_BINARY = "NativeBinary" + """Native binary code detected.""" + UNKNOWN_FORMAT = "UnknownFormat" + """Unknown format detected.""" + + +class FoundryModelSourceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The source type of the model.""" + + LOCAL_UPLOAD = "LocalUpload" + """Model was uploaded locally.""" + TRAINING_JOB = "TrainingJob" + """Model was produced by a training job.""" + + +class FoundryModelWarningCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Warning code for model artifacts.""" + + RUNTIME_DEPENDENT_ARTIFACT = "RuntimeDependentArtifact" + """Runtime dependent artifact warning.""" + UNCLASSIFIED_ARTIFACT = "UnclassifiedArtifact" + """Unclassified artifact warning.""" + + +class FoundryModelWeightType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The weight type of the model.""" + + FULL_WEIGHT = "FullWeight" + """Full weight model.""" + LO_RA = "LoRA" + """LoRA adapter weights.""" + DRAFT_MODEL = "DraftModel" + """Draft model weights.""" + + class FunctionShellToolParamEnvironmentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Type of FunctionShellToolParamEnvironmentType.""" @@ -592,6 +669,15 @@ class InsightType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Evaluation Comparison.""" +class IsolationKeySourceKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of IsolationKeySourceKind.""" + + ENTRA = "Entra" + """ENTRA.""" + HEADER = "Header" + """HEADER.""" + + class JobStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Extensible status values shared by Foundry jobs.""" @@ -614,6 +700,8 @@ class MemoryItemKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): """User profile information extracted from conversations.""" CHAT_SUMMARY = "chat_summary" """Summary of chat conversations.""" + PROCEDURAL = "procedural" + """Routine procedures extracted from conversations.""" class MemoryOperationKind(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -643,6 +731,8 @@ class MemoryStoreObjectType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """MEMORY_STORE_DELETED.""" MEMORY_STORE_SCOPE_DELETED = "memory_store.scope.deleted" """MEMORY_STORE_SCOPE_DELETED.""" + MEMORY_DELETED = "memory_store.item.deleted" + """MEMORY_DELETED.""" class MemoryStoreUpdateStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -691,6 +781,24 @@ class OperationState(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The operation has been canceled by the user.""" +class OptimizationMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Run mode for an optimization job.""" + + OPTIMIZE = "optimize" + """Full optimization: baseline + mutation strategies.""" + + +class OptimizationStrategy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Optimization strategy dimension.""" + + INSTRUCTION = "instruction" + """Instruction-tuning strategy — rewrites agent system prompts.""" + MODEL = "model" + """Model-selection strategy — evaluates alternative LLM deployments.""" + SKILL = "skill" + """Skill-tuning strategy — generates or modifies agent tool descriptions.""" + + class PageOrder(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Type of PageOrder.""" @@ -706,7 +814,10 @@ class PendingUploadType(str, Enum, metaclass=CaseInsensitiveEnumMeta): NONE = "None" """No pending upload.""" BLOB_REFERENCE = "BlobReference" - """Blob Reference is the only supported type.""" + """Deprecated: the service never read this value and silently ignored it. Use + TemporaryBlobReference instead.""" + TEMPORARY_BLOB_REFERENCE = "TemporaryBlobReference" + """Temporary blob reference.""" class RankerVersionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -756,6 +867,63 @@ class RiskCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): """Represents content that involves task adherence.""" +class RoutineActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The discriminator values supported for routine actions.""" + + INVOKE_AGENT_RESPONSES_API = "invoke_agent_responses_api" + """Dispatches through the responses API.""" + INVOKE_AGENT_INVOCATIONS_API = "invoke_agent_invocations_api" + """Dispatches through the raw invocations API.""" + + +class RoutineAttemptSource(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Known source paths that can produce a routine run.""" + + EVENT_FIRE = "event_fire" + """A dispatch fired from an event delivery.""" + MANUAL_DISPATCH = "manual_dispatch" + """A dispatch executed synchronously by a direct request.""" + QUEUED_DISPATCH = "queued_dispatch" + """A dispatch executed asynchronously from the dispatch queue.""" + SCHEDULE_DELIVERY = "schedule_delivery" + """A dispatch fired from a schedule delivery.""" + TIMER_DELIVERY = "timer_delivery" + """A dispatch fired from a timer delivery.""" + + +class RoutineDispatchPayloadType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The discriminator values supported for manual routine dispatch payloads.""" + + INVOKE_AGENT_RESPONSES_API = "invoke_agent_responses_api" + """A manual payload for a responses API routine dispatch.""" + INVOKE_AGENT_INVOCATIONS_API = "invoke_agent_invocations_api" + """A manual payload for an invocations API routine dispatch.""" + + +class RoutineRunPhase(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Known lifecycle phases recorded for a routine run.""" + + QUEUED = "queued" + """The run is queued for dispatch.""" + DISPATCHING = "dispatching" + """The run is currently being dispatched.""" + COMPLETED = "completed" + """The run finished successfully.""" + FAILED = "failed" + """The run finished with an error.""" + + +class RoutineTriggerType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The discriminator values supported for routine triggers.""" + + GITHUB_ISSUE_OPENED = "github_issue_opened" + """A GitHub issue-opened trigger.""" + SCHEDULE = "schedule" + """A recurring cron-based trigger.""" + TIMER = "timer" + """A one-shot timer trigger.""" + + class SampleType(str, Enum, metaclass=CaseInsensitiveEnumMeta): """The type of sample used in the analysis.""" diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_models.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_models.py index 3606e0a5d9b8..b73ace6881df 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_models.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_models.py @@ -34,12 +34,16 @@ FunctionShellToolParamEnvironmentType, IndexType, InsightType, + IsolationKeySourceKind, MemoryItemKind, MemoryStoreKind, MemoryStoreObjectType, OpenApiAuthType, PendingUploadType, RecurrenceType, + RoutineActionType, + RoutineDispatchPayloadType, + RoutineTriggerType, SampleType, ScheduleTaskType, TelemetryEndpointAuthType, @@ -115,6 +119,10 @@ class A2APreviewTool(Tool, discriminator="a2a_preview"): :vartype name: str :ivar description: Optional user-defined description for this tool or configuration. :vartype description: str + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] :ivar base_url: Base URL of the agent. :vartype base_url: str :ivar agent_card_path: The path to the agent card relative to the ``base_url``. If not @@ -132,6 +140,12 @@ class A2APreviewTool(Tool, discriminator="a2a_preview"): """Optional user-defined name for this tool or configuration.""" description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Optional user-defined description for this tool or configuration.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" base_url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Base URL of the agent.""" agent_card_path: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -147,6 +161,7 @@ def __init__( *, name: Optional[str] = None, description: Optional[str] = None, + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, base_url: Optional[str] = None, agent_card_path: Optional[str] = None, project_connection_id: Optional[str] = None, @@ -518,9 +533,9 @@ class AgentDefinition(_Model): """AgentDefinition. You probably want to use the sub-classes and not this class directly. Known sub-classes are: - HostedAgentDefinition, PromptAgentDefinition, WorkflowAgentDefinition + ExternalAgentDefinition, HostedAgentDefinition, PromptAgentDefinition, WorkflowAgentDefinition - :ivar kind: Required. Known values are: "prompt", "hosted", and "workflow". + :ivar kind: Required. Known values are: "prompt", "hosted", "workflow", and "external". :vartype kind: str or ~azure.ai.projects.models.AgentKind :ivar rai_config: Configuration for Responsible AI (RAI) content filtering and safety features. :vartype rai_config: ~azure.ai.projects.models.RaiConfig @@ -528,7 +543,7 @@ class AgentDefinition(_Model): __mapping__: dict[str, _Model] = {} kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) - """Required. Known values are: \"prompt\", \"hosted\", and \"workflow\".""" + """Required. Known values are: \"prompt\", \"hosted\", \"workflow\", and \"external\".""" rai_config: Optional["_models.RaiConfig"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Configuration for Responsible AI (RAI) content filtering and safety features.""" @@ -964,6 +979,51 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class AgentsPagedResultOptimizationCandidate(_Model): + """The response data for a requested list of items. + + :ivar data: The requested list of items. Required. + :vartype data: list[~azure.ai.projects.models.OptimizationCandidate] + :ivar first_id: The first ID represented in this list. + :vartype first_id: str + :ivar last_id: The last ID represented in this list. + :vartype last_id: str + :ivar has_more: A value indicating whether there are additional values available not captured + in this list. Required. + :vartype has_more: bool + """ + + data: list["_models.OptimizationCandidate"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The requested list of items. Required.""" + first_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The first ID represented in this list.""" + last_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The last ID represented in this list.""" + has_more: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A value indicating whether there are additional values available not captured in this list. + Required.""" + + @overload + def __init__( + self, + *, + data: list["_models.OptimizationCandidate"], + has_more: bool, + first_id: Optional[str] = None, + last_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + class EvaluationTaxonomyInput(_Model): """Input configuration for the evaluation taxonomy. @@ -1003,14 +1063,14 @@ class AgentTaxonomyInput(EvaluationTaxonomyInput, discriminator="agent"): :ivar type: Input type of the evaluation taxonomy. Required. Agent. :vartype type: str or ~azure.ai.projects.models.AGENT :ivar target: Target configuration for the agent. Required. - :vartype target: ~azure.ai.projects.models.Target + :vartype target: ~azure.ai.projects.models.EvaluationTarget :ivar risk_categories: List of risk categories to evaluate against. Required. :vartype risk_categories: list[str or ~azure.ai.projects.models.RiskCategory] """ type: Literal[EvaluationTaxonomyInputType.AGENT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """Input type of the evaluation taxonomy. Required. Agent.""" - target: "_models.Target" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + target: "_models.EvaluationTarget" = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Target configuration for the agent. Required.""" risk_categories: list[Union[str, "_models.RiskCategory"]] = rest_field( name="riskCategories", visibility=["read", "create", "update", "delete", "query"] @@ -1021,7 +1081,7 @@ class AgentTaxonomyInput(EvaluationTaxonomyInput, discriminator="agent"): def __init__( self, *, - target: "_models.Target", + target: "_models.EvaluationTarget", risk_categories: list[Union[str, "_models.RiskCategory"]], ) -> None: ... @@ -1392,6 +1452,45 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.type: Literal["approximate"] = "approximate" +class ArtifactProfile(_Model): + """Artifact profile of the model. + + :ivar category: The category of the artifact profile. Required. Known values are: "DataOnly", + "RuntimeDependent", and "Unknown". + :vartype category: str or ~azure.ai.projects.models.FoundryModelArtifactProfileCategory + :ivar signals: Signals detected in the model artifact. + :vartype signals: list[str or ~azure.ai.projects.models.FoundryModelArtifactProfileSignal] + """ + + category: Union[str, "_models.FoundryModelArtifactProfileCategory"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The category of the artifact profile. Required. Known values are: \"DataOnly\", + \"RuntimeDependent\", and \"Unknown\".""" + signals: Optional[list[Union[str, "_models.FoundryModelArtifactProfileSignal"]]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Signals detected in the model artifact.""" + + @overload + def __init__( + self, + *, + category: Union[str, "_models.FoundryModelArtifactProfileCategory"], + signals: Optional[list[Union[str, "_models.FoundryModelArtifactProfileSignal"]]] = 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 AutoCodeInterpreterToolParam(_Model): """Automatic Code Interpreter Tool Parameters. @@ -1438,7 +1537,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.type: Literal["auto"] = "auto" -class Target(_Model): +class EvaluationTarget(_Model): """Base class for targets with discriminator support. You probably want to use the sub-classes and not this class directly. Known sub-classes are: @@ -1470,7 +1569,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AzureAIAgentTarget(Target, discriminator="azure_ai_agent"): +class AzureAIAgentTarget(EvaluationTarget, discriminator="azure_ai_agent"): """Represents a target specifying an Azure AI agent. :ivar type: The type of target, always ``azure_ai_agent``. Required. Default value is @@ -1483,6 +1582,8 @@ class AzureAIAgentTarget(Target, discriminator="azure_ai_agent"): :ivar tool_descriptions: The parameters used to control the sampling behavior of the agent during text generation. :vartype tool_descriptions: list[~azure.ai.projects.models.ToolDescription] + :ivar tools: + :vartype tools: list[~azure.ai.projects.models.Tool] """ type: Literal["azure_ai_agent"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore @@ -1495,6 +1596,7 @@ class AzureAIAgentTarget(Target, discriminator="azure_ai_agent"): visibility=["read", "create", "update", "delete", "query"] ) """The parameters used to control the sampling behavior of the agent during text generation.""" + tools: Optional[list["_models.Tool"]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) @overload def __init__( @@ -1503,6 +1605,7 @@ def __init__( name: str, version: Optional[str] = None, tool_descriptions: Optional[list["_models.ToolDescription"]] = None, + tools: Optional[list["_models.Tool"]] = None, ) -> None: ... @overload @@ -1517,7 +1620,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.type = "azure_ai_agent" # type: ignore -class AzureAIModelTarget(Target, discriminator="azure_ai_model"): +class AzureAIModelTarget(EvaluationTarget, discriminator="azure_ai_model"): """Represents a target specifying an Azure AI model for operations requiring model selection. :ivar type: The type of target, always ``azure_ai_model``. Required. Default value is @@ -1679,6 +1782,10 @@ class AzureAISearchTool(Tool, discriminator="azure_ai_search"): :vartype name: str :ivar description: Optional user-defined description for this tool or configuration. :vartype description: str + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] :ivar azure_ai_search: The azure ai search index resource. Required. :vartype azure_ai_search: ~azure.ai.projects.models.AzureAISearchToolResource """ @@ -1689,6 +1796,12 @@ class AzureAISearchTool(Tool, discriminator="azure_ai_search"): """Optional user-defined name for this tool or configuration.""" description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Optional user-defined description for this tool or configuration.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" azure_ai_search: "_models.AzureAISearchToolResource" = rest_field( visibility=["read", "create", "update", "delete", "query"] ) @@ -1701,6 +1814,7 @@ def __init__( azure_ai_search: "_models.AzureAISearchToolResource", name: Optional[str] = None, description: Optional[str] = None, + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, ) -> None: ... @overload @@ -1914,6 +2028,10 @@ class AzureFunctionTool(Tool, discriminator="azure_function"): :vartype type: str or ~azure.ai.projects.models.AZURE_FUNCTION :ivar azure_function: The Azure Function Tool definition. Required. :vartype azure_function: ~azure.ai.projects.models.AzureFunctionDefinition + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] """ type: Literal[ToolType.AZURE_FUNCTION] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore @@ -1922,12 +2040,19 @@ class AzureFunctionTool(Tool, discriminator="azure_function"): visibility=["read", "create", "update", "delete", "query"] ) """The Azure Function Tool definition. Required.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" @overload def __init__( self, *, azure_function: "_models.AzureFunctionDefinition", + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, ) -> None: ... @overload @@ -1942,7 +2067,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.type = ToolType.AZURE_FUNCTION # type: ignore -class TargetConfig(_Model): +class RedTeamTargetConfig(_Model): """Abstract class for target configuration. You probably want to use the sub-classes and not this class directly. Known sub-classes are: @@ -1974,7 +2099,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AzureOpenAIModelConfiguration(TargetConfig, discriminator="AzureOpenAIModel"): +class AzureOpenAIModelConfiguration(RedTeamTargetConfig, discriminator="AzureOpenAIModel"): """Azure OpenAI model configuration. The API version would be selected by the service for querying the model. @@ -2078,6 +2203,10 @@ class BingCustomSearchPreviewTool(Tool, discriminator="bing_custom_search_previe :vartype name: str :ivar description: Optional user-defined description for this tool or configuration. :vartype description: str + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] :ivar bing_custom_search_preview: The bing custom search tool parameters. Required. :vartype bing_custom_search_preview: ~azure.ai.projects.models.BingCustomSearchToolParameters """ @@ -2089,6 +2218,12 @@ class BingCustomSearchPreviewTool(Tool, discriminator="bing_custom_search_previe """Optional user-defined name for this tool or configuration.""" description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Optional user-defined description for this tool or configuration.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" bing_custom_search_preview: "_models.BingCustomSearchToolParameters" = rest_field( visibility=["read", "create", "update", "delete", "query"] ) @@ -2101,6 +2236,7 @@ def __init__( bing_custom_search_preview: "_models.BingCustomSearchToolParameters", name: Optional[str] = None, description: Optional[str] = None, + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, ) -> None: ... @overload @@ -2240,6 +2376,10 @@ class BingGroundingTool(Tool, discriminator="bing_grounding"): :vartype name: str :ivar description: Optional user-defined description for this tool or configuration. :vartype description: str + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] :ivar bing_grounding: The bing grounding search tool parameters. Required. :vartype bing_grounding: ~azure.ai.projects.models.BingGroundingSearchToolParameters """ @@ -2250,6 +2390,12 @@ class BingGroundingTool(Tool, discriminator="bing_grounding"): """Optional user-defined name for this tool or configuration.""" description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Optional user-defined description for this tool or configuration.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" bing_grounding: "_models.BingGroundingSearchToolParameters" = rest_field( visibility=["read", "create", "update", "delete", "query"] ) @@ -2262,6 +2408,7 @@ def __init__( bing_grounding: "_models.BingGroundingSearchToolParameters", name: Optional[str] = None, description: Optional[str] = None, + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, ) -> None: ... @overload @@ -2403,6 +2550,10 @@ class BrowserAutomationPreviewTool(Tool, discriminator="browser_automation_previ :vartype name: str :ivar description: Optional user-defined description for this tool or configuration. :vartype description: str + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] :ivar browser_automation_preview: The Browser Automation Tool parameters. Required. :vartype browser_automation_preview: ~azure.ai.projects.models.BrowserAutomationToolParameters """ @@ -2414,6 +2565,12 @@ class BrowserAutomationPreviewTool(Tool, discriminator="browser_automation_previ """Optional user-defined name for this tool or configuration.""" description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Optional user-defined description for this tool or configuration.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" browser_automation_preview: "_models.BrowserAutomationToolParameters" = rest_field( visibility=["read", "create", "update", "delete", "query"] ) @@ -2426,6 +2583,7 @@ def __init__( browser_automation_preview: "_models.BrowserAutomationToolParameters", name: Optional[str] = None, description: Optional[str] = None, + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, ) -> None: ... @overload @@ -2500,6 +2658,87 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class CandidateDeployConfig(_Model): + """Deploy-config blob for a candidate. Suitable for setting OPTIMIZATION_CONFIG on a hosted-agent + version. + + :ivar instructions: System prompt / instructions. + :vartype instructions: str + :ivar model: Foundry deployment name. + :vartype model: str + :ivar temperature: Optional sampling temperature. + :vartype temperature: float + :ivar skills: Optional skill overrides. + :vartype skills: list[~azure.ai.projects.models.OptimizationAgentSkill] + """ + + instructions: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """System prompt / instructions.""" + model: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Foundry deployment name.""" + temperature: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Optional sampling temperature.""" + skills: Optional[list["_models.OptimizationAgentSkill"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Optional skill overrides.""" + + @overload + def __init__( + self, + *, + instructions: Optional[str] = None, + model: Optional[str] = None, + temperature: Optional[float] = None, + skills: Optional[list["_models.OptimizationAgentSkill"]] = 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 CandidateResults(_Model): + """Full per-task evaluation results for a candidate, returned by GET /candidates/{id}/results. + + :ivar candidate_id: Owning candidate id. Required. + :vartype candidate_id: str + :ivar results: Per-task evaluation rows. Required. + :vartype results: list[~azure.ai.projects.models.OptimizationTaskResult] + """ + + candidate_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Owning candidate id. Required.""" + results: list["_models.OptimizationTaskResult"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-task evaluation rows. Required.""" + + @overload + def __init__( + self, + *, + candidate_id: str, + results: list["_models.OptimizationTaskResult"], + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + class CaptureStructuredOutputsTool(Tool, discriminator="capture_structured_outputs"): """A tool for capturing structured outputs. @@ -2510,6 +2749,10 @@ class CaptureStructuredOutputsTool(Tool, discriminator="capture_structured_outpu :vartype name: str :ivar description: Optional user-defined description for this tool or configuration. :vartype description: str + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] :ivar outputs: The structured outputs to capture from the model. Required. :vartype outputs: ~azure.ai.projects.models.StructuredOutputDefinition """ @@ -2521,6 +2764,12 @@ class CaptureStructuredOutputsTool(Tool, discriminator="capture_structured_outpu """Optional user-defined name for this tool or configuration.""" description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Optional user-defined description for this tool or configuration.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" outputs: "_models.StructuredOutputDefinition" = rest_field( visibility=["read", "create", "update", "delete", "query"] ) @@ -2533,6 +2782,7 @@ def __init__( outputs: "_models.StructuredOutputDefinition", name: Optional[str] = None, description: Optional[str] = None, + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, ) -> None: ... @overload @@ -2589,7 +2839,7 @@ class MemoryItem(_Model): """A single memory item stored in the memory store, containing content and metadata. You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ChatSummaryMemoryItem, UserProfileMemoryItem + ChatSummaryMemoryItem, ProceduralMemoryItem, UserProfileMemoryItem :ivar memory_id: The unique ID of the memory item. Required. :vartype memory_id: str @@ -2600,8 +2850,8 @@ class MemoryItem(_Model): :vartype scope: str :ivar content: The content of the memory. Required. :vartype content: str - :ivar kind: The kind of the memory item. Required. Known values are: "user_profile" and - "chat_summary". + :ivar kind: The kind of the memory item. Required. Known values are: "user_profile", + "chat_summary", and "procedural". :vartype kind: str or ~azure.ai.projects.models.MemoryItemKind """ @@ -2617,7 +2867,8 @@ class MemoryItem(_Model): content: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The content of the memory. Required.""" kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) - """The kind of the memory item. Required. Known values are: \"user_profile\" and \"chat_summary\".""" + """The kind of the memory item. Required. Known values are: \"user_profile\", \"chat_summary\", + and \"procedural\".""" @overload def __init__( @@ -2810,7 +3061,7 @@ class EvaluatorDefinition(_Model): CodeBasedEvaluatorDefinition, PromptBasedEvaluatorDefinition, RubricBasedEvaluatorDefinition :ivar type: The type of evaluator definition. Required. Known values are: "prompt", "code", - "prompt_and_code", "service", "openai_graders", and "rubrics". + "prompt_and_code", "service", "openai_graders", and "rubric". :vartype type: str or ~azure.ai.projects.models.EvaluatorDefinitionType :ivar init_parameters: The JSON schema (Draft 2020-12) for the evaluator's input parameters. This includes parameters like type, properties, required. @@ -2825,7 +3076,7 @@ class EvaluatorDefinition(_Model): __mapping__: dict[str, _Model] = {} type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) """The type of evaluator definition. Required. Known values are: \"prompt\", \"code\", - \"prompt_and_code\", \"service\", \"openai_graders\", and \"rubrics\".""" + \"prompt_and_code\", \"service\", \"openai_graders\", and \"rubric\".""" init_parameters: Optional[dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The JSON schema (Draft 2020-12) for the evaluator's input parameters. This includes parameters like type, properties, required.""" @@ -2986,6 +3237,10 @@ class CodeInterpreterTool(Tool, discriminator="code_interpreter"): :vartype name: str :ivar description: Optional user-defined description for this tool or configuration. :vartype description: str + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] :ivar container: The code interpreter container. Can be a container ID or an object that specifies uploaded file IDs to make available to your code, along with an optional ``memory_limit`` setting. If not provided, the service assumes auto. Is either a str type or a @@ -2999,6 +3254,12 @@ class CodeInterpreterTool(Tool, discriminator="code_interpreter"): """Optional user-defined name for this tool or configuration.""" description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Optional user-defined description for this tool or configuration.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" container: Optional[Union[str, "_models.AutoCodeInterpreterToolParam"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) @@ -3013,6 +3274,7 @@ def __init__( *, name: Optional[str] = None, description: Optional[str] = None, + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, container: Optional[Union[str, "_models.AutoCodeInterpreterToolParam"]] = None, ) -> None: ... @@ -3739,6 +4001,42 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class CreateAsyncResponse(_Model): + """CreateAsyncResponse. + + :ivar location: URL to poll for operation status. + :vartype location: str + :ivar operation_result: URL to the operation result, or null if the operation is still in + progress. + :vartype operation_result: str + """ + + location: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """URL to poll for operation status.""" + operation_result: Optional[str] = rest_field( + name="operationResult", visibility=["read", "create", "update", "delete", "query"] + ) + """URL to the operation result, or null if the operation is still in progress.""" + + @overload + def __init__( + self, + *, + location: Optional[str] = None, + operation_result: 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 Trigger(_Model): """Base model for Trigger of the schedule. @@ -4138,6 +4436,10 @@ class DataGenerationJobInputs(_Model): Required. Known values are: "supervised_finetuning", "reinforcement_finetuning", and "evaluation". :vartype scenario: str or ~azure.ai.projects.models.DataGenerationJobScenario + :ivar output_options: Optional caller-supplied metadata for the job's output. See individual + fields for whether they apply to file outputs (fine-tuning scenarios), dataset outputs + (evaluation scenario), or both. + :vartype output_options: ~azure.ai.projects.models.DataGenerationJobOutputOptions """ name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -4153,6 +4455,11 @@ class DataGenerationJobInputs(_Model): ) """The scenario of the data generation job. Either for fine-tuning or evaluation. Required. Known values are: \"supervised_finetuning\", \"reinforcement_finetuning\", and \"evaluation\".""" + output_options: Optional["_models.DataGenerationJobOutputOptions"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Optional caller-supplied metadata for the job's output. See individual fields for whether they + apply to file outputs (fine-tuning scenarios), dataset outputs (evaluation scenario), or both.""" @overload def __init__( @@ -4162,6 +4469,7 @@ def __init__( sources: list["_models.DataGenerationJobSource"], options: "_models.DataGenerationJobOptions", scenario: Union[str, "_models.DataGenerationJobScenario"], + output_options: Optional["_models.DataGenerationJobOutputOptions"] = None, ) -> None: ... @overload @@ -4261,6 +4569,50 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class DataGenerationJobOutputOptions(_Model): + """Output options for data generation job. + + :ivar name: Name to assign to the output. Used as the filename for Azure OpenAI file outputs + (fine-tuning scenarios) and as the dataset name for dataset outputs (evaluation scenario). + :vartype name: str + :ivar description: Description to assign to the output. Applies only to dataset outputs + (evaluation scenario); ignored for Azure OpenAI file outputs. + :vartype description: str + :ivar tags: Tags to assign to the output. Applies only to dataset outputs (evaluation + scenario); ignored for Azure OpenAI file outputs. + :vartype tags: dict[str, str] + """ + + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Name to assign to the output. Used as the filename for Azure OpenAI file outputs (fine-tuning + scenarios) and as the dataset name for dataset outputs (evaluation scenario).""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description to assign to the output. Applies only to dataset outputs (evaluation scenario); + ignored for Azure OpenAI file outputs.""" + tags: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Tags to assign to the output. Applies only to dataset outputs (evaluation scenario); ignored + for Azure OpenAI file outputs.""" + + @overload + def __init__( + self, + *, + name: Optional[str] = None, + description: Optional[str] = None, + tags: Optional[dict[str, 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 DataGenerationJobResult(_Model): """Result produced by a successful data generation job. @@ -4388,15 +4740,13 @@ class DatasetDataGenerationJobOutput(DataGenerationJobOutput, discriminator="dat :vartype type: str or ~azure.ai.projects.models.DATASET :ivar id: The id of the output dataset created. :vartype id: str - :ivar name: The name of the output dataset and can be optionally set during job creation time. + :ivar name: The name of the output dataset. :vartype name: str :ivar version: The version of the output dataset. :vartype version: str - :ivar description: Description of the output dataset and can be optionally set during job - creation time. + :ivar description: Description of the output dataset. :vartype description: str - :ivar tags: Tag dictionary of the output dataset and can be optionally set during job creation - time. + :ivar tags: Tag dictionary of the output dataset. :vartype tags: dict[str, str] """ @@ -4404,22 +4754,18 @@ class DatasetDataGenerationJobOutput(DataGenerationJobOutput, discriminator="dat """Dataset output. Required. The generated data is a Dataset.""" id: Optional[str] = rest_field(visibility=["read"]) """The id of the output dataset created.""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the output dataset and can be optionally set during job creation time.""" + name: Optional[str] = rest_field(visibility=["read"]) + """The name of the output dataset.""" version: Optional[str] = rest_field(visibility=["read"]) """The version of the output dataset.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Description of the output dataset and can be optionally set during job creation time.""" - tags: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Tag dictionary of the output dataset and can be optionally set during job creation time.""" + description: Optional[str] = rest_field(visibility=["read"]) + """Description of the output dataset.""" + tags: Optional[dict[str, str]] = rest_field(visibility=["read"]) + """Tag dictionary of the output dataset.""" @overload def __init__( self, - *, - name: Optional[str] = None, - description: Optional[str] = None, - tags: Optional[dict[str, str]] = None, ) -> None: ... @overload @@ -4527,6 +4873,102 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.type = EvaluatorGenerationJobSourceType.DATASET # type: ignore +class DatasetItem(_Model): + """A single evaluation task with input query, expected output, and evaluation criteria. + + :ivar name: Unique-within-the-dataset identifier for this task. Required. + :vartype name: str + :ivar query: The user query / input for the task. Required. + :vartype query: str + :ivar ground_truth: Optional ground truth used by reference-based evaluators. + :vartype ground_truth: str + :ivar criteria: Per-task evaluation criteria. Defaults to the job-level evaluators if unset. + :vartype criteria: list[~azure.ai.projects.models.EvaluationCriterion] + :ivar eval_results: Pre-computed evaluation results in AOAI-compatible format. When provided + together with ``response_items``, the baseline run-and-evaluate phase is skipped. + :vartype eval_results: list[~azure.ai.projects.models.EvalRunOutputItemResult] + :ivar response_items: Pre-computed agent response output items. Captures the full trajectory + (function calls, tool outputs, messages) from a prior agent run. + :vartype response_items: list[dict[str, any]] + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Unique-within-the-dataset identifier for this task. Required.""" + query: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The user query / input for the task. Required.""" + ground_truth: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Optional ground truth used by reference-based evaluators.""" + criteria: Optional[list["_models.EvaluationCriterion"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-task evaluation criteria. Defaults to the job-level evaluators if unset.""" + eval_results: Optional[list["_models.EvalRunOutputItemResult"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Pre-computed evaluation results in AOAI-compatible format. When provided together with + ``response_items``, the baseline run-and-evaluate phase is skipped.""" + response_items: Optional[list[dict[str, Any]]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Pre-computed agent response output items. Captures the full trajectory (function calls, tool + outputs, messages) from a prior agent run.""" + + @overload + def __init__( + self, + *, + name: str, + query: str, + ground_truth: Optional[str] = None, + criteria: Optional[list["_models.EvaluationCriterion"]] = None, + eval_results: Optional[list["_models.EvalRunOutputItemResult"]] = None, + response_items: Optional[list[dict[str, Any]]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DatasetRef(_Model): + """Reference to a registered dataset in the Foundry Dataset Service. + + :ivar name: Dataset name. Required. + :vartype name: str + :ivar version: Dataset version. If not specified, the latest version is used. + :vartype version: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Dataset name. Required.""" + version: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Dataset version. If not specified, the latest version is used.""" + + @overload + def __init__( + self, + *, + name: str, + version: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + class DatasetReference(_Model): """Reference to a versioned Foundry Dataset. @@ -4719,31 +5161,71 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class DeleteMemoryStoreResult(_Model): - """DeleteMemoryStoreResult. +class DeleteMemoryResponse(_Model): + """Response for deleting a memory item from a memory store. - :ivar object: The object type. Always 'memory_store.deleted'. Required. MEMORY_STORE_DELETED. - :vartype object: str or ~azure.ai.projects.models.MEMORY_STORE_DELETED - :ivar name: The name of the memory store. Required. - :vartype name: str - :ivar deleted: Whether the memory store was successfully deleted. Required. + :ivar object: The object type. Always 'memory_store.item.deleted'. Required. MEMORY_DELETED. + :vartype object: str or ~azure.ai.projects.models.MEMORY_DELETED + :ivar memory_id: The unique ID of the deleted memory item. Required. + :vartype memory_id: str + :ivar deleted: Whether the memory item was successfully deleted. Required. :vartype deleted: bool """ - object: Literal[MemoryStoreObjectType.MEMORY_STORE_DELETED] = rest_field( + object: Literal[MemoryStoreObjectType.MEMORY_DELETED] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) - """The object type. Always 'memory_store.deleted'. Required. MEMORY_STORE_DELETED.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the memory store. Required.""" + """The object type. Always 'memory_store.item.deleted'. Required. MEMORY_DELETED.""" + memory_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The unique ID of the deleted memory item. Required.""" deleted: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Whether the memory store was successfully deleted. Required.""" + """Whether the memory item was successfully deleted. Required.""" @overload def __init__( self, *, - object: Literal[MemoryStoreObjectType.MEMORY_STORE_DELETED], + object: Literal[MemoryStoreObjectType.MEMORY_DELETED], + memory_id: str, + deleted: bool, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DeleteMemoryStoreResult(_Model): + """DeleteMemoryStoreResult. + + :ivar object: The object type. Always 'memory_store.deleted'. Required. MEMORY_STORE_DELETED. + :vartype object: str or ~azure.ai.projects.models.MEMORY_STORE_DELETED + :ivar name: The name of the memory store. Required. + :vartype name: str + :ivar deleted: Whether the memory store was successfully deleted. Required. + :vartype deleted: bool + """ + + object: Literal[MemoryStoreObjectType.MEMORY_STORE_DELETED] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The object type. Always 'memory_store.deleted'. Required. MEMORY_STORE_DELETED.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the memory store. Required.""" + deleted: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Whether the memory store was successfully deleted. Required.""" + + @overload + def __init__( + self, + *, + object: Literal[MemoryStoreObjectType.MEMORY_STORE_DELETED], name: str, deleted: bool, ) -> None: ... @@ -4828,6 +5310,104 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class Dimension(_Model): + """A single dimension — one independent, measurable quality dimension within a rubric evaluator's + scoring blueprint. + + :ivar id: Stable identifier for this dimension (snake_case, e.g., ``correct_resolution``). + Required. Provided by the user when manually creating a rubric evaluator or during + human-in-the-loop review of a generated set; the generation pipeline produces an initial value + the user can edit. Editable when saving new versions. Required. + :vartype id: str + :ivar description: What this dimension measures (e.g., 'Correctly identifies the user's + reservation intent and pursues the appropriate workflow'). Required. + :vartype description: str + :ivar weight: Relative weight of this dimension (1-10). The generation pipeline assigns exactly + one dimension weight 8-10; all others use 1-6. User edits are not constrained by this + heuristic. Required. + :vartype weight: int + :ivar always_applicable: When true, the LLM judge always scores this dimension regardless of + relevance (skips applicability assessment). The service-generated general quality/policy + dimension has this set to true and is non-editable. Users may set this on their own custom + dimensions. + :vartype always_applicable: bool + """ + + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Stable identifier for this dimension (snake_case, e.g., ``correct_resolution``). Required. + Provided by the user when manually creating a rubric evaluator or during human-in-the-loop + review of a generated set; the generation pipeline produces an initial value the user can edit. + Editable when saving new versions. Required.""" + description: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """What this dimension measures (e.g., 'Correctly identifies the user's reservation intent and + pursues the appropriate workflow'). Required.""" + weight: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Relative weight of this dimension (1-10). The generation pipeline assigns exactly one dimension + weight 8-10; all others use 1-6. User edits are not constrained by this heuristic. Required.""" + always_applicable: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """When true, the LLM judge always scores this dimension regardless of relevance (skips + applicability assessment). The service-generated general quality/policy dimension has this set + to true and is non-editable. Users may set this on their own custom dimensions.""" + + @overload + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + description: str, + weight: int, + always_applicable: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class DispatchRoutineResponse(_Model): + """Identifiers returned after a routine dispatch is queued. + + :ivar dispatch_id: The dispatch identifier created for the routine dispatch. + :vartype dispatch_id: str + :ivar action_correlation_id: A downstream action correlation identifier, when available. + :vartype action_correlation_id: str + :ivar task_id: A workspace task identifier created for the dispatch, when available. + :vartype task_id: str + """ + + dispatch_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The dispatch identifier created for the routine dispatch.""" + action_correlation_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A downstream action correlation identifier, when available.""" + task_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A workspace task identifier created for the dispatch, when available.""" + + @overload + def __init__( + self, + *, + dispatch_id: Optional[str] = None, + action_correlation_id: Optional[str] = None, + task_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + class EmbeddingConfiguration(_Model): """Embedding configuration class. @@ -4868,14 +5448,24 @@ class EntraAuthorizationScheme(AgentEndpointAuthorizationScheme, discriminator=" :ivar type: Required. ENTRA. :vartype type: str or ~azure.ai.projects.models.ENTRA + :ivar isolation_key_source: The source from which the per-user isolation key is derived for + requests authorized via this scheme. Defaults to Entra-based isolation when omitted. + :vartype isolation_key_source: ~azure.ai.projects.models.IsolationKeySource """ type: Literal[AgentEndpointAuthorizationSchemeType.ENTRA] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """Required. ENTRA.""" + isolation_key_source: Optional["_models.IsolationKeySource"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The source from which the per-user isolation key is derived for requests authorized via this + scheme. Defaults to Entra-based isolation when omitted.""" @overload def __init__( self, + *, + isolation_key_source: Optional["_models.IsolationKeySource"] = None, ) -> None: ... @overload @@ -4917,6 +5507,65 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.type = CredentialType.ENTRA_ID # type: ignore +class IsolationKeySource(_Model): + """IsolationKeySource. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + EntraIsolationKeySource, HeaderIsolationKeySource + + :ivar kind: Required. Known values are: "Entra" and "Header". + :vartype kind: str or ~azure.ai.projects.models.IsolationKeySourceKind + """ + + __mapping__: dict[str, _Model] = {} + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """Required. Known values are: \"Entra\" and \"Header\".""" + + @overload + def __init__( + self, + *, + kind: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class EntraIsolationKeySource(IsolationKeySource, discriminator="Entra"): + """EntraIsolationKeySource. + + :ivar kind: Required. ENTRA. + :vartype kind: str or ~azure.ai.projects.models.ENTRA + """ + + kind: Literal[IsolationKeySourceKind.ENTRA] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required. ENTRA.""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = IsolationKeySourceKind.ENTRA # type: ignore + + class EvalResult(_Model): """Result of the evaluation. @@ -4960,6 +5609,93 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class EvalRunOutputItemResult(_Model): + """EvalRunOutputItemResult. + + :ivar name: The name of the grader. Required. + :vartype name: str + :ivar type: The grader type (for example, "string-check-grader"). + :vartype type: str + :ivar score: The numeric score produced by the grader. Required. + :vartype score: int + :ivar passed: Whether the grader considered the output a pass. Required. + :vartype passed: bool + :ivar sample: Optional sample or intermediate data produced by the grader. + :vartype sample: dict[str, any] + :ivar status: The evaluation status for this result item. Values: "completed", "errored", + "skipped". Null if not provided by evaluator. When status is skipped, passed/score can be + ignored. Known values are: "completed", "errored", and "skipped". + :vartype status: str or ~azure.ai.projects.models.EvalRunOutputItemResultStatus + :ivar metric: The name of the metric (e.g., "fluency", "f1_score"). + :vartype metric: str + :ivar label: The label associated with the test criteria metric (e.g., "pass", "fail", "good", + "bad"). + :vartype label: str + :ivar threshold: The threshold used to determine pass/fail for this test criteria, if it is + numerical. + :vartype threshold: float + :ivar reason: The reason for the test criteria metric. + :vartype reason: str + :ivar properties: Additional details about the test criteria metric. + :vartype properties: dict[str, str] + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the grader. Required.""" + type: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The grader type (for example, \"string-check-grader\").""" + score: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The numeric score produced by the grader. Required.""" + passed: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Whether the grader considered the output a pass. Required.""" + sample: Optional[dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Optional sample or intermediate data produced by the grader.""" + status: Optional[Union[str, "_models.EvalRunOutputItemResultStatus"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The evaluation status for this result item. Values: \"completed\", \"errored\", \"skipped\". + Null if not provided by evaluator. When status is skipped, passed/score can be ignored. Known + values are: \"completed\", \"errored\", and \"skipped\".""" + metric: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the metric (e.g., \"fluency\", \"f1_score\").""" + label: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The label associated with the test criteria metric (e.g., \"pass\", \"fail\", \"good\", + \"bad\").""" + threshold: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The threshold used to determine pass/fail for this test criteria, if it is numerical.""" + reason: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The reason for the test criteria metric.""" + properties: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional details about the test criteria metric.""" + + @overload + def __init__( + self, + *, + name: str, + score: int, + passed: bool, + type: Optional[str] = None, + sample: Optional[dict[str, Any]] = None, + status: Optional[Union[str, "_models.EvalRunOutputItemResultStatus"]] = None, + metric: Optional[str] = None, + label: Optional[str] = None, + threshold: Optional[float] = None, + reason: Optional[str] = None, + properties: Optional[dict[str, 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 EvalRunResultCompareItem(_Model): """Metric comparison for a treatment against the baseline. @@ -5200,6 +5936,39 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.type = InsightType.EVALUATION_COMPARISON # type: ignore +class EvaluationCriterion(_Model): + """LLM-as-judge evaluation criterion applied to a single task. + + :ivar name: Criterion name (referenced in evaluation result rows). Required. + :vartype name: str + :ivar instruction: Natural-language instruction passed to the judge LLM. Required. + :vartype instruction: str + """ + + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Criterion name (referenced in evaluation result rows). Required.""" + instruction: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Natural-language instruction passed to the judge LLM. Required.""" + + @overload + def __init__( + self, + *, + name: str, + instruction: 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 InsightSample(_Model): """A sample from the analysis. @@ -5612,6 +6381,36 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class EvaluatorCredentialRequest(_Model): + """Request body for getting evaluator credentials. + + :ivar blob_uri: The blob URI for the evaluator storage. Example: + ``https://account.blob.core.windows.net:443/container``. Required. + :vartype blob_uri: str + """ + + blob_uri: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The blob URI for the evaluator storage. Example: + ``https://account.blob.core.windows.net:443/container``. Required.""" + + @overload + def __init__( + self, + *, + blob_uri: 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 EvaluatorGenerationArtifacts(_Model): """Service-managed provenance artifacts produced by an evaluator generation job. Present only on EvaluatorVersion resources created via the generation pipeline. The combined-JSONL Foundry @@ -5664,58 +6463,73 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: class EvaluatorGenerationInputs(_Model): """Caller-supplied inputs for an evaluator generation job. - :ivar name: Display name for this generation job. Required. - :vartype name: str :ivar sources: Source materials for generation — agent descriptions, prompts, traces, or datasets. Each entry is an ``EvaluatorGenerationJobSource`` variant discriminated by ``type``. Required. :vartype sources: list[~azure.ai.projects.models.EvaluatorGenerationJobSource] - :ivar category: Category determines the rubric generation focus: 'quality' (default) produces - quality-focused rubric criteria, 'safety' produces policy-derived safety rubric criteria. Both - use the same rubric structure. Singular because quality and safety generation are mutually - exclusive pipelines — the output EvaluatorVersion.categories is an array (e.g., ['agents', - 'quality']). Known values are: "quality", "safety", and "agents". - :vartype category: str or ~azure.ai.projects.models.EvaluatorCategory :ivar model: The LLM model to use for rubric generation (e.g., 'gpt-4o'). Required — users must provide their own model rather than relying on service-owned capacity. Required. :vartype model: str - :ivar evaluator_name: The evaluator name to create or update. If an evaluator with this name - already exists, the service retrieves the latest version's criteria as context for improvement. - Required. + :ivar evaluator_name: The evaluator name (immutable identifier). 1-256 characters; allowed + characters are ASCII letters, digits, underscore (``_``), period (``.``), tilde (``~``), and + hyphen (``-``). The prefix ``builtin.`` is reserved for system-managed evaluators and is + rejected by the service. If an evaluator with this name already exists in the project (and is + rubric-subtype), the service creates a new version under the same name and uses the prior + version's ``dimensions`` as context for incremental improvement (foundation of the post-//build + adaptive loop). Old versions remain queryable via ``get_version(name, version)``. If the + existing evaluator is not a rubric-subtype evaluator (built-in, prompt-based, code-based), the + request is rejected with ``400 Bad Request``. Required. :vartype evaluator_name: str + :ivar evaluator_display_name: Optional human-friendly display name for the resulting evaluator. + Surfaced as ``EvaluatorVersion.display_name`` on the persisted evaluator. When omitted, the + service uses ``evaluator_name`` as the display name. The ``evaluator_`` prefix disambiguates + this from the immutable ``evaluator_name`` identifier. + :vartype evaluator_display_name: str + :ivar evaluator_description: Optional human-friendly description for the resulting evaluator. + Surfaced as ``EvaluatorVersion.description`` on the persisted evaluator. Typically collected + from the UI alongside ``evaluator_display_name``. The ``evaluator_`` prefix disambiguates this + from any other description fields on related models. + :vartype evaluator_description: str """ - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Display name for this generation job. Required.""" sources: list["_models.EvaluatorGenerationJobSource"] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) """Source materials for generation — agent descriptions, prompts, traces, or datasets. Each entry is an ``EvaluatorGenerationJobSource`` variant discriminated by ``type``. Required.""" - category: Optional[Union[str, "_models.EvaluatorCategory"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Category determines the rubric generation focus: 'quality' (default) produces quality-focused - rubric criteria, 'safety' produces policy-derived safety rubric criteria. Both use the same - rubric structure. Singular because quality and safety generation are mutually exclusive - pipelines — the output EvaluatorVersion.categories is an array (e.g., ['agents', 'quality']). - Known values are: \"quality\", \"safety\", and \"agents\".""" model: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The LLM model to use for rubric generation (e.g., 'gpt-4o'). Required — users must provide their own model rather than relying on service-owned capacity. Required.""" evaluator_name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The evaluator name to create or update. If an evaluator with this name already exists, the - service retrieves the latest version's criteria as context for improvement. Required.""" + """The evaluator name (immutable identifier). 1-256 characters; allowed characters are ASCII + letters, digits, underscore (``_``), period (``.``), tilde (``~``), and hyphen (``-``). The + prefix ``builtin.`` is reserved for system-managed evaluators and is rejected by the service. + If an evaluator with this name already exists in the project (and is rubric-subtype), the + service creates a new version under the same name and uses the prior version's ``dimensions`` + as context for incremental improvement (foundation of the post-//build adaptive loop). Old + versions remain queryable via ``get_version(name, version)``. If the existing evaluator is not + a rubric-subtype evaluator (built-in, prompt-based, code-based), the request is rejected with + ``400 Bad Request``. Required.""" + evaluator_display_name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Optional human-friendly display name for the resulting evaluator. Surfaced as + ``EvaluatorVersion.display_name`` on the persisted evaluator. When omitted, the service uses + ``evaluator_name`` as the display name. The ``evaluator_`` prefix disambiguates this from the + immutable ``evaluator_name`` identifier.""" + evaluator_description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Optional human-friendly description for the resulting evaluator. Surfaced as + ``EvaluatorVersion.description`` on the persisted evaluator. Typically collected from the UI + alongside ``evaluator_display_name``. The ``evaluator_`` prefix disambiguates this from any + other description fields on related models.""" @overload def __init__( self, *, - name: str, sources: list["_models.EvaluatorGenerationJobSource"], model: str, evaluator_name: str, - category: Optional[Union[str, "_models.EvaluatorCategory"]] = None, + evaluator_display_name: Optional[str] = None, + evaluator_description: Optional[str] = None, ) -> None: ... @overload @@ -5986,19 +6800,67 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class FabricDataAgentToolParameters(_Model): - """The fabric data agent tool parameters. +class ExternalAgentDefinition(AgentDefinition, discriminator="external"): + """The external agent definition. Represents a third-party agent hosted outside Foundry (for + example, on GCP or AWS). Registration is metadata-only: Foundry records the agent definition to + light up observability experiences (traces, evaluations) over customer-emitted OpenTelemetry + data. - :ivar project_connections: The project connections attached to this tool. There can be a - maximum of 1 connection resource attached to the tool. - :vartype project_connections: list[~azure.ai.projects.models.ToolProjectConnection] + :ivar rai_config: Configuration for Responsible AI (RAI) content filtering and safety features. + :vartype rai_config: ~azure.ai.projects.models.RaiConfig + :ivar kind: Required. EXTERNAL. + :vartype kind: str or ~azure.ai.projects.models.EXTERNAL + :ivar otel_agent_id: The OpenTelemetry agent identifier used to attribute customer-emitted + spans to this Foundry agent. Spans must include the attribute ``gen_ai.agent.id = + `` to appear under this registration. Defaults to the top-level agent name when + omitted. Provide an explicit value only for migration scenarios where the running external + agent already emits a stable id that differs from the Foundry agent name. The resolved value is + always echoed on read. + :vartype otel_agent_id: str """ - project_connections: Optional[list["_models.ToolProjectConnection"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The project connections attached to this tool. There can be a maximum of 1 connection resource - attached to the tool.""" + kind: Literal[AgentKind.EXTERNAL] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required. EXTERNAL.""" + otel_agent_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The OpenTelemetry agent identifier used to attribute customer-emitted spans to this Foundry + agent. Spans must include the attribute ``gen_ai.agent.id = `` to appear under + this registration. Defaults to the top-level agent name when omitted. Provide an explicit value + only for migration scenarios where the running external agent already emits a stable id that + differs from the Foundry agent name. The resolved value is always echoed on read.""" + + @overload + def __init__( + self, + *, + rai_config: Optional["_models.RaiConfig"] = None, + otel_agent_id: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = AgentKind.EXTERNAL # type: ignore + + +class FabricDataAgentToolParameters(_Model): + """The fabric data agent tool parameters. + + :ivar project_connections: The project connections attached to this tool. There can be a + maximum of 1 connection resource attached to the tool. + :vartype project_connections: list[~azure.ai.projects.models.ToolProjectConnection] + """ + + project_connections: Optional[list["_models.ToolProjectConnection"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The project connections attached to this tool. There can be a maximum of 1 connection resource + attached to the tool.""" @overload def __init__( @@ -6037,6 +6899,10 @@ class FabricIQPreviewTool(Tool, discriminator="fabric_iq_preview"): :vartype name: str :ivar description: Optional user-defined description for this tool or configuration. :vartype description: str + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] """ type: Literal[ToolType.FABRIC_IQ_PREVIEW] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore @@ -6057,6 +6923,12 @@ class FabricIQPreviewTool(Tool, discriminator="fabric_iq_preview"): """Optional user-defined name for this tool or configuration.""" description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Optional user-defined description for this tool or configuration.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" @overload def __init__( @@ -6068,6 +6940,7 @@ def __init__( require_approval: Optional[Union["_models.MCPToolRequireApproval", str]] = None, name: Optional[str] = None, description: Optional[str] = None, + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, ) -> None: ... @overload @@ -6280,6 +7153,10 @@ class FileSearchTool(Tool, discriminator="file_search"): :vartype name: str :ivar description: Optional user-defined description for this tool or configuration. :vartype description: str + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] """ type: Literal[ToolType.FILE_SEARCH] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore @@ -6298,6 +7175,12 @@ class FileSearchTool(Tool, discriminator="file_search"): """Optional user-defined name for this tool or configuration.""" description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Optional user-defined description for this tool or configuration.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" @overload def __init__( @@ -6309,6 +7192,7 @@ def __init__( filters: Optional["_types.Filters"] = None, name: Optional[str] = None, description: Optional[str] = None, + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, ) -> None: ... @overload @@ -6449,6 +7333,42 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.type = DatasetType.URI_FOLDER # type: ignore +class FoundryModelWarning(_Model): + """A warning associated with a model. + + :ivar code: The warning code. Known values are: "RuntimeDependentArtifact" and + "UnclassifiedArtifact". + :vartype code: str or ~azure.ai.projects.models.FoundryModelWarningCode + :ivar message: The warning message. + :vartype message: str + """ + + code: Optional[Union[str, "_models.FoundryModelWarningCode"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The warning code. Known values are: \"RuntimeDependentArtifact\" and \"UnclassifiedArtifact\".""" + message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The warning message.""" + + @overload + def __init__( + self, + *, + code: Optional[Union[str, "_models.FoundryModelWarningCode"]] = None, + message: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + class FunctionShellToolParam(Tool, discriminator="shell"): """Shell tool. @@ -6460,6 +7380,10 @@ class FunctionShellToolParam(Tool, discriminator="shell"): :vartype name: str :ivar description: Optional user-defined description for this tool or configuration. :vartype description: str + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] """ type: Literal[ToolType.SHELL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore @@ -6471,6 +7395,12 @@ class FunctionShellToolParam(Tool, discriminator="shell"): """Optional user-defined name for this tool or configuration.""" description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Optional user-defined description for this tool or configuration.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" @overload def __init__( @@ -6479,6 +7409,7 @@ def __init__( environment: Optional["_models.FunctionShellToolParamEnvironment"] = None, name: Optional[str] = None, description: Optional[str] = None, + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, ) -> None: ... @overload @@ -6613,6 +7544,115 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.type = ToolType.FUNCTION # type: ignore +class RoutineTrigger(_Model): + """Base model for a routine trigger. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + GitHubIssueOpenedRoutineTrigger, ScheduleRoutineTrigger, TimerRoutineTrigger + + :ivar type: The trigger type. Required. Known values are: "github_issue_opened", "schedule", + and "timer". + :vartype type: str or ~azure.ai.projects.models.RoutineTriggerType + """ + + __mapping__: dict[str, _Model] = {} + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """The trigger type. Required. Known values are: \"github_issue_opened\", \"schedule\", and + \"timer\".""" + + @overload + def __init__( + self, + *, + type: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class GitHubIssueOpenedRoutineTrigger(RoutineTrigger, discriminator="github_issue_opened"): + """A GitHub issue-opened routine trigger. + + :ivar type: The trigger type. Required. A GitHub issue-opened trigger. + :vartype type: str or ~azure.ai.projects.models.GITHUB_ISSUE_OPENED + :ivar connection_id: The workspace connection identifier that resolves the GitHub configuration + for the trigger. Required. + :vartype connection_id: str + :ivar assignee: The GitHub assignee or organization filter that scopes which issues can fire + the trigger. Required. + :vartype assignee: str + :ivar repository: The GitHub repository filter that scopes which issues can fire the trigger. + Required. + :vartype repository: str + """ + + type: Literal[RoutineTriggerType.GITHUB_ISSUE_OPENED] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The trigger type. Required. A GitHub issue-opened trigger.""" + connection_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The workspace connection identifier that resolves the GitHub configuration for the trigger. + Required.""" + assignee: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The GitHub assignee or organization filter that scopes which issues can fire the trigger. + Required.""" + repository: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The GitHub repository filter that scopes which issues can fire the trigger. Required.""" + + @overload + def __init__( + self, + *, + connection_id: str, + assignee: str, + repository: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = RoutineTriggerType.GITHUB_ISSUE_OPENED # type: ignore + + +class HeaderIsolationKeySource(IsolationKeySource, discriminator="Header"): + """HeaderIsolationKeySource. + + :ivar kind: Required. HEADER. + :vartype kind: str or ~azure.ai.projects.models.HEADER + """ + + kind: Literal[IsolationKeySourceKind.HEADER] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required. HEADER.""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = IsolationKeySourceKind.HEADER # type: ignore + + class TelemetryEndpointAuth(_Model): """Authentication configuration for a telemetry endpoint. @@ -6933,6 +7973,10 @@ class ImageGenTool(Tool, discriminator="image_generation"): :vartype name: str :ivar description: Optional user-defined description for this tool or configuration. :vartype description: str + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] """ type: Literal[ToolType.IMAGE_GENERATION] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore @@ -6992,6 +8036,12 @@ class ImageGenTool(Tool, discriminator="image_generation"): """Optional user-defined name for this tool or configuration.""" description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Optional user-defined description for this tool or configuration.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" @overload def __init__( @@ -7012,6 +8062,7 @@ def __init__( action: Optional[Union[str, "_models.ImageGenAction"]] = None, name: Optional[str] = None, description: Optional[str] = None, + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, ) -> None: ... @overload @@ -7421,30 +8472,27 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class LocalShellToolParam(Tool, discriminator="local_shell"): - """Local shell tool. +class RoutineDispatchPayload(_Model): + """Base model for a manual dispatch payload. - :ivar type: The type of the local shell tool. Always ``local_shell``. Required. LOCAL_SHELL. - :vartype type: str or ~azure.ai.projects.models.LOCAL_SHELL - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + InvokeAgentInvocationsApiDispatchPayload, InvokeAgentResponsesApiDispatchPayload + + :ivar type: The manual dispatch payload type. Required. Known values are: + "invoke_agent_responses_api" and "invoke_agent_invocations_api". + :vartype type: str or ~azure.ai.projects.models.RoutineDispatchPayloadType """ - type: Literal[ToolType.LOCAL_SHELL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the local shell tool. Always ``local_shell``. Required. LOCAL_SHELL.""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" + __mapping__: dict[str, _Model] = {} + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """The manual dispatch payload type. Required. Known values are: \"invoke_agent_responses_api\" + and \"invoke_agent_invocations_api\".""" @overload def __init__( self, *, - name: Optional[str] = None, - description: Optional[str] = None, + type: str, ) -> None: ... @overload @@ -7456,34 +8504,29 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = ToolType.LOCAL_SHELL # type: ignore -class LocalSkillParam(_Model): - """LocalSkillParam. +class InvokeAgentInvocationsApiDispatchPayload(RoutineDispatchPayload, discriminator="invoke_agent_invocations_api"): + """A manual payload used to test an invocations API routine dispatch. - :ivar name: The name of the skill. Required. - :vartype name: str - :ivar description: The description of the skill. Required. - :vartype description: str - :ivar path: The path to the directory containing the skill. Required. - :vartype path: str + :ivar type: The manual dispatch payload type. Required. A manual payload for an invocations API + routine dispatch. + :vartype type: str or ~azure.ai.projects.models.INVOKE_AGENT_INVOCATIONS_API + :ivar input: The raw input sent to the downstream invocations target. + :vartype input: str """ - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the skill. Required.""" - description: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The description of the skill. Required.""" - path: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The path to the directory containing the skill. Required.""" + type: Literal[RoutineDispatchPayloadType.INVOKE_AGENT_INVOCATIONS_API] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The manual dispatch payload type. Required. A manual payload for an invocations API routine + dispatch.""" + input: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The raw input sent to the downstream invocations target.""" @overload def __init__( self, *, - name: str, - description: str, - path: str, + input: Optional[str] = None, ) -> None: ... @overload @@ -7495,27 +8538,30 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) + self.type = RoutineDispatchPayloadType.INVOKE_AGENT_INVOCATIONS_API # type: ignore -class ManagedAgentIdentityBlueprintReference(AgentBlueprintReference, discriminator="ManagedAgentIdentityBlueprint"): - """ManagedAgentIdentityBlueprintReference. +class RoutineAction(_Model): + """Base model for a routine action. - :ivar type: Required. MANAGED_AGENT_IDENTITY_BLUEPRINT. - :vartype type: str or ~azure.ai.projects.models.MANAGED_AGENT_IDENTITY_BLUEPRINT - :ivar blueprint_id: The ID of the managed blueprint. Required. - :vartype blueprint_id: str + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + InvokeAgentInvocationsApiRoutineAction, InvokeAgentResponsesApiRoutineAction + + :ivar type: The action type. Required. Known values are: "invoke_agent_responses_api" and + "invoke_agent_invocations_api". + :vartype type: str or ~azure.ai.projects.models.RoutineActionType """ - type: Literal[AgentBlueprintReferenceType.MANAGED_AGENT_IDENTITY_BLUEPRINT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. MANAGED_AGENT_IDENTITY_BLUEPRINT.""" - blueprint_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the managed blueprint. Required.""" + __mapping__: dict[str, _Model] = {} + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """The action type. Required. Known values are: \"invoke_agent_responses_api\" and + \"invoke_agent_invocations_api\".""" @overload def __init__( self, *, - blueprint_id: str, + type: str, ) -> None: ... @overload @@ -7527,40 +8573,35 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = AgentBlueprintReferenceType.MANAGED_AGENT_IDENTITY_BLUEPRINT # type: ignore -class ManagedAzureAISearchIndex(Index, discriminator="ManagedAzureSearch"): - """Managed Azure AI Search Index Definition. +class InvokeAgentInvocationsApiRoutineAction(RoutineAction, discriminator="invoke_agent_invocations_api"): + """Dispatches a routine through the raw invocations API. - :ivar id: Asset ID, a unique identifier for the asset. - :vartype id: str - :ivar name: The name of the resource. Required. - :vartype name: str - :ivar version: The version of the resource. Required. - :vartype version: str - :ivar description: The asset description text. - :vartype description: str - :ivar tags: Tag dictionary. Tags can be added, removed, and updated. - :vartype tags: dict[str, str] - :ivar type: Type of index. Required. Managed Azure Search. - :vartype type: str or ~azure.ai.projects.models.MANAGED_AZURE_SEARCH - :ivar vector_store_id: Vector store id of managed index. Required. - :vartype vector_store_id: str + :ivar type: The action type. Required. Dispatches through the raw invocations API. + :vartype type: str or ~azure.ai.projects.models.INVOKE_AGENT_INVOCATIONS_API + :ivar agent_endpoint_id: The endpoint-scoped agent identifier for invocations API dispatch. + Required. + :vartype agent_endpoint_id: str + :ivar session_id: An optional existing hosted-agent session identifier to continue during the + downstream dispatch. + :vartype session_id: str """ - type: Literal[IndexType.MANAGED_AZURE_SEARCH] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Type of index. Required. Managed Azure Search.""" - vector_store_id: str = rest_field(name="vectorStoreId", visibility=["create"]) - """Vector store id of managed index. Required.""" + type: Literal[RoutineActionType.INVOKE_AGENT_INVOCATIONS_API] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The action type. Required. Dispatches through the raw invocations API.""" + agent_endpoint_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The endpoint-scoped agent identifier for invocations API dispatch. Required.""" + session_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """An optional existing hosted-agent session identifier to continue during the downstream + dispatch.""" @overload def __init__( self, *, - vector_store_id: str, - description: Optional[str] = None, - tags: Optional[dict[str, str]] = None, + agent_endpoint_id: str, + session_id: Optional[str] = None, ) -> None: ... @overload @@ -7572,132 +8613,30 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = IndexType.MANAGED_AZURE_SEARCH # type: ignore + self.type = RoutineActionType.INVOKE_AGENT_INVOCATIONS_API # type: ignore -class MCPTool(Tool, discriminator="mcp"): - """MCP tool. +class InvokeAgentResponsesApiDispatchPayload(RoutineDispatchPayload, discriminator="invoke_agent_responses_api"): + """A manual payload used to test a responses API routine dispatch. - :ivar type: The type of the MCP tool. Always ``mcp``. Required. MCP. - :vartype type: str or ~azure.ai.projects.models.MCP - :ivar server_label: A label for this MCP server, used to identify it in tool calls. Required. - :vartype server_label: str - :ivar server_url: The URL for the MCP server. One of ``server_url`` or ``connector_id`` must be - provided. - :vartype server_url: str - :ivar connector_id: Identifier for service connectors, like those available in ChatGPT. One of - ``server_url`` or ``connector_id`` must be provided. Learn more about service connectors `here - `_. Currently supported ``connector_id`` values are: + :ivar type: The manual dispatch payload type. Required. A manual payload for a responses API + routine dispatch. + :vartype type: str or ~azure.ai.projects.models.INVOKE_AGENT_RESPONSES_API + :ivar input: The user input sent to the downstream responses target. + :vartype input: str + """ - * Dropbox: `connector_dropbox` - * Gmail: `connector_gmail` - * Google Calendar: `connector_googlecalendar` - * Google Drive: `connector_googledrive` - * Microsoft Teams: `connector_microsoftteams` - * Outlook Calendar: `connector_outlookcalendar` - * Outlook Email: `connector_outlookemail` - * SharePoint: `connector_sharepoint`. Is one of the following types: - Literal["connector_dropbox"], Literal["connector_gmail"], Literal["connector_googlecalendar"], - Literal["connector_googledrive"], Literal["connector_microsoftteams"], - Literal["connector_outlookcalendar"], Literal["connector_outlookemail"], - Literal["connector_sharepoint"] - :vartype connector_id: str or str or str or str or str or str or str or str - :ivar authorization: An OAuth access token that can be used with a remote MCP server, either - with a custom MCP server URL or a service connector. Your application must handle the OAuth - authorization flow and provide the token here. - :vartype authorization: str - :ivar server_description: Optional description of the MCP server, used to provide more context. - :vartype server_description: str - :ivar headers: - :vartype headers: dict[str, str] - :ivar allowed_tools: Is either a [str] type or a MCPToolFilter type. - :vartype allowed_tools: list[str] or ~azure.ai.projects.models.MCPToolFilter - :ivar require_approval: Is one of the following types: MCPToolRequireApproval, - Literal["always"], Literal["never"] - :vartype require_approval: ~azure.ai.projects.models.MCPToolRequireApproval or str or str - :ivar project_connection_id: The connection ID in the project for the MCP server. The - connection stores authentication and other connection details needed to connect to the MCP - server. - :vartype project_connection_id: str - """ - - type: Literal[ToolType.MCP] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the MCP tool. Always ``mcp``. Required. MCP.""" - server_label: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A label for this MCP server, used to identify it in tool calls. Required.""" - server_url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The URL for the MCP server. One of ``server_url`` or ``connector_id`` must be provided.""" - connector_id: Optional[ - Literal[ - "connector_dropbox", - "connector_gmail", - "connector_googlecalendar", - "connector_googledrive", - "connector_microsoftteams", - "connector_outlookcalendar", - "connector_outlookemail", - "connector_sharepoint", - ] - ] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Identifier for service connectors, like those available in ChatGPT. One of ``server_url`` or - ``connector_id`` must be provided. Learn more about service connectors `here - `_. Currently supported ``connector_id`` values are: - - * Dropbox: `connector_dropbox` - * Gmail: `connector_gmail` - * Google Calendar: `connector_googlecalendar` - * Google Drive: `connector_googledrive` - * Microsoft Teams: `connector_microsoftteams` - * Outlook Calendar: `connector_outlookcalendar` - * Outlook Email: `connector_outlookemail` - * SharePoint: `connector_sharepoint`. Is one of the following types: - Literal[\"connector_dropbox\"], Literal[\"connector_gmail\"], - Literal[\"connector_googlecalendar\"], Literal[\"connector_googledrive\"], - Literal[\"connector_microsoftteams\"], Literal[\"connector_outlookcalendar\"], - Literal[\"connector_outlookemail\"], Literal[\"connector_sharepoint\"]""" - authorization: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """An OAuth access token that can be used with a remote MCP server, either with a custom MCP - server URL or a service connector. Your application must handle the OAuth authorization flow - and provide the token here.""" - server_description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional description of the MCP server, used to provide more context.""" - headers: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - allowed_tools: Optional[Union[list[str], "_models.MCPToolFilter"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Is either a [str] type or a MCPToolFilter type.""" - require_approval: Optional[Union["_models.MCPToolRequireApproval", Literal["always"], Literal["never"]]] = ( - rest_field(visibility=["read", "create", "update", "delete", "query"]) - ) - """Is one of the following types: MCPToolRequireApproval, Literal[\"always\"], Literal[\"never\"]""" - project_connection_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The connection ID in the project for the MCP server. The connection stores authentication and - other connection details needed to connect to the MCP server.""" + type: Literal[RoutineDispatchPayloadType.INVOKE_AGENT_RESPONSES_API] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The manual dispatch payload type. Required. A manual payload for a responses API routine + dispatch.""" + input: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The user input sent to the downstream responses target.""" @overload def __init__( self, *, - server_label: str, - server_url: Optional[str] = None, - connector_id: Optional[ - Literal[ - "connector_dropbox", - "connector_gmail", - "connector_googlecalendar", - "connector_googledrive", - "connector_microsoftteams", - "connector_outlookcalendar", - "connector_outlookemail", - "connector_sharepoint", - ] - ] = None, - authorization: Optional[str] = None, - server_description: Optional[str] = None, - headers: Optional[dict[str, str]] = None, - allowed_tools: Optional[Union[list[str], "_models.MCPToolFilter"]] = None, - require_approval: Optional[Union["_models.MCPToolRequireApproval", Literal["always"], Literal["never"]]] = None, - project_connection_id: Optional[str] = None, + input: Optional[str] = None, ) -> None: ... @overload @@ -7709,35 +8648,40 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = ToolType.MCP # type: ignore + self.type = RoutineDispatchPayloadType.INVOKE_AGENT_RESPONSES_API # type: ignore -class MCPToolFilter(_Model): - """MCP tool filter. +class InvokeAgentResponsesApiRoutineAction(RoutineAction, discriminator="invoke_agent_responses_api"): + """Dispatches a routine through the responses API. Exactly one of agent_name or agent_endpoint_id + must be provided. - :ivar tool_names: MCP allowed tools. - :vartype tool_names: list[str] - :ivar read_only: Indicates whether or not a tool modifies data or is read-only. If an MCP - server is `annotated with `readOnlyHint` - `_, - it will match this filter. - :vartype read_only: bool + :ivar type: The action type. Required. Dispatches through the responses API. + :vartype type: str or ~azure.ai.projects.models.INVOKE_AGENT_RESPONSES_API + :ivar agent_name: The project-scoped agent name for responses API dispatch. + :vartype agent_name: str + :ivar agent_endpoint_id: The endpoint-scoped agent identifier for responses API dispatch. + :vartype agent_endpoint_id: str + :ivar conversation_id: An optional existing conversation identifier to continue during the + downstream dispatch. + :vartype conversation_id: str """ - tool_names: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """MCP allowed tools.""" - read_only: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Indicates whether or not a tool modifies data or is read-only. If an MCP server is `annotated - with `readOnlyHint` - `_, - it will match this filter.""" + type: Literal[RoutineActionType.INVOKE_AGENT_RESPONSES_API] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The action type. Required. Dispatches through the responses API.""" + agent_name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The project-scoped agent name for responses API dispatch.""" + agent_endpoint_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The endpoint-scoped agent identifier for responses API dispatch.""" + conversation_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """An optional existing conversation identifier to continue during the downstream dispatch.""" @overload def __init__( self, *, - tool_names: Optional[list[str]] = None, - read_only: Optional[bool] = None, + agent_name: Optional[str] = None, + agent_endpoint_id: Optional[str] = None, + conversation_id: Optional[str] = None, ) -> None: ... @overload @@ -7749,26 +8693,44 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) + self.type = RoutineActionType.INVOKE_AGENT_RESPONSES_API # type: ignore -class MCPToolRequireApproval(_Model): - """MCPToolRequireApproval. +class LocalShellToolParam(Tool, discriminator="local_shell"): + """Local shell tool. - :ivar always: - :vartype always: ~azure.ai.projects.models.MCPToolFilter - :ivar never: - :vartype never: ~azure.ai.projects.models.MCPToolFilter + :ivar type: The type of the local shell tool. Always ``local_shell``. Required. LOCAL_SHELL. + :vartype type: str or ~azure.ai.projects.models.LOCAL_SHELL + :ivar name: Optional user-defined name for this tool or configuration. + :vartype name: str + :ivar description: Optional user-defined description for this tool or configuration. + :vartype description: str + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] """ - always: Optional["_models.MCPToolFilter"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - never: Optional["_models.MCPToolFilter"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + type: Literal[ToolType.LOCAL_SHELL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The type of the local shell tool. Always ``local_shell``. Required. LOCAL_SHELL.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Optional user-defined name for this tool or configuration.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Optional user-defined description for this tool or configuration.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" @overload def __init__( self, *, - always: Optional["_models.MCPToolFilter"] = None, - never: Optional["_models.MCPToolFilter"] = None, + name: Optional[str] = None, + description: Optional[str] = None, + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, ) -> None: ... @overload @@ -7780,32 +8742,34 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) + self.type = ToolType.LOCAL_SHELL # type: ignore -class MemoryOperation(_Model): - """Represents a single memory operation (create, update, or delete) performed on a memory item. +class LocalSkillParam(_Model): + """LocalSkillParam. - :ivar kind: The type of memory operation being performed. Required. Known values are: "create", - "update", and "delete". - :vartype kind: str or ~azure.ai.projects.models.MemoryOperationKind - :ivar memory_item: The memory item to create, update, or delete. Required. - :vartype memory_item: ~azure.ai.projects.models.MemoryItem + :ivar name: The name of the skill. Required. + :vartype name: str + :ivar description: The description of the skill. Required. + :vartype description: str + :ivar path: The path to the directory containing the skill. Required. + :vartype path: str """ - kind: Union[str, "_models.MemoryOperationKind"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The type of memory operation being performed. Required. Known values are: \"create\", - \"update\", and \"delete\".""" - memory_item: "_models.MemoryItem" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The memory item to create, update, or delete. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the skill. Required.""" + description: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The description of the skill. Required.""" + path: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The path to the directory containing the skill. Required.""" @overload def __init__( self, *, - kind: Union[str, "_models.MemoryOperationKind"], - memory_item: "_models.MemoryItem", + name: str, + description: str, + path: str, ) -> None: ... @overload @@ -7819,21 +8783,41 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class MemorySearchItem(_Model): - """A retrieved memory item from memory search. +class LoraConfig(_Model): + """Adapter-specific metadata for LoRA models. Drives serving engine configuration at deployment + time. - :ivar memory_item: Retrieved memory item. Required. - :vartype memory_item: ~azure.ai.projects.models.MemoryItem + :ivar rank: LoRA rank (r). Positive integer. Common values: 8, 16, 32, 64. + :vartype rank: int + :ivar alpha: LoRA scaling factor (α). Positive integer; typically 2× the rank. + :vartype alpha: int + :ivar target_modules: Model layers modified by the adapter (e.g., q_proj, v_proj). + Auto-detected from adapter_config.json if omitted. + :vartype target_modules: list[str] + :ivar dropout: Dropout rate used during training. Informational — not used at serving time. + :vartype dropout: float """ - memory_item: "_models.MemoryItem" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Retrieved memory item. Required.""" + rank: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """LoRA rank (r). Positive integer. Common values: 8, 16, 32, 64.""" + alpha: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """LoRA scaling factor (α). Positive integer; typically 2× the rank.""" + target_modules: Optional[list[str]] = rest_field( + name="targetModules", visibility=["read", "create", "update", "delete", "query"] + ) + """Model layers modified by the adapter (e.g., q_proj, v_proj). Auto-detected from + adapter_config.json if omitted.""" + dropout: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Dropout rate used during training. Informational — not used at serving time.""" @overload def __init__( self, *, - memory_item: "_models.MemoryItem", + rank: Optional[int] = None, + alpha: Optional[int] = None, + target_modules: Optional[list[str]] = None, + dropout: Optional[float] = None, ) -> None: ... @overload @@ -7847,21 +8831,25 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class MemorySearchOptions(_Model): - """Memory search options. +class ManagedAgentIdentityBlueprintReference(AgentBlueprintReference, discriminator="ManagedAgentIdentityBlueprint"): + """ManagedAgentIdentityBlueprintReference. - :ivar max_memories: Maximum number of memory items to return. - :vartype max_memories: int + :ivar type: Required. MANAGED_AGENT_IDENTITY_BLUEPRINT. + :vartype type: str or ~azure.ai.projects.models.MANAGED_AGENT_IDENTITY_BLUEPRINT + :ivar blueprint_id: The ID of the managed blueprint. Required. + :vartype blueprint_id: str """ - max_memories: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Maximum number of memory items to return.""" + type: Literal[AgentBlueprintReferenceType.MANAGED_AGENT_IDENTITY_BLUEPRINT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required. MANAGED_AGENT_IDENTITY_BLUEPRINT.""" + blueprint_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The ID of the managed blueprint. Required.""" @overload def __init__( self, *, - max_memories: Optional[int] = None, + blueprint_id: str, ) -> None: ... @overload @@ -7873,60 +8861,40 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) + self.type = AgentBlueprintReferenceType.MANAGED_AGENT_IDENTITY_BLUEPRINT # type: ignore -class MemorySearchPreviewTool(Tool, discriminator="memory_search_preview"): - """A tool for integrating memories into the agent. +class ManagedAzureAISearchIndex(Index, discriminator="ManagedAzureSearch"): + """Managed Azure AI Search Index Definition. - :ivar type: The type of the tool. Always ``memory_search_preview``. Required. - MEMORY_SEARCH_PREVIEW. - :vartype type: str or ~azure.ai.projects.models.MEMORY_SEARCH_PREVIEW - :ivar name: Optional user-defined name for this tool or configuration. + :ivar id: Asset ID, a unique identifier for the asset. + :vartype id: str + :ivar name: The name of the resource. Required. :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. + :ivar version: The version of the resource. Required. + :vartype version: str + :ivar description: The asset description text. :vartype description: str - :ivar memory_store_name: The name of the memory store to use. Required. - :vartype memory_store_name: str - :ivar scope: The namespace used to group and isolate memories, such as a user ID. Limits which - memories can be retrieved or updated. Use special variable ``{{$userId}}`` to scope memories to - the current signed-in user. Required. - :vartype scope: str - :ivar search_options: Options for searching the memory store. - :vartype search_options: ~azure.ai.projects.models.MemorySearchOptions - :ivar update_delay: Time to wait before updating memories after inactivity (seconds). Default - 300. - :vartype update_delay: int + :ivar tags: Tag dictionary. Tags can be added, removed, and updated. + :vartype tags: dict[str, str] + :ivar type: Type of index. Required. Managed Azure Search. + :vartype type: str or ~azure.ai.projects.models.MANAGED_AZURE_SEARCH + :ivar vector_store_id: Vector store id of managed index. Required. + :vartype vector_store_id: str """ - type: Literal[ToolType.MEMORY_SEARCH_PREVIEW] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the tool. Always ``memory_search_preview``. Required. MEMORY_SEARCH_PREVIEW.""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - memory_store_name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the memory store to use. Required.""" - scope: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The namespace used to group and isolate memories, such as a user ID. Limits which memories can - be retrieved or updated. Use special variable ``{{$userId}}`` to scope memories to the current - signed-in user. Required.""" - search_options: Optional["_models.MemorySearchOptions"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Options for searching the memory store.""" - update_delay: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Time to wait before updating memories after inactivity (seconds). Default 300.""" + type: Literal[IndexType.MANAGED_AZURE_SEARCH] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Type of index. Required. Managed Azure Search.""" + vector_store_id: str = rest_field(name="vectorStoreId", visibility=["create"]) + """Vector store id of managed index. Required.""" @overload def __init__( self, *, - memory_store_name: str, - scope: str, - name: Optional[str] = None, + vector_store_id: str, description: Optional[str] = None, - search_options: Optional["_models.MemorySearchOptions"] = None, - update_delay: Optional[int] = None, + tags: Optional[dict[str, str]] = None, ) -> None: ... @overload @@ -7938,28 +8906,1010 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = ToolType.MEMORY_SEARCH_PREVIEW # type: ignore - + self.type = IndexType.MANAGED_AZURE_SEARCH # type: ignore -class MemoryStoreDefinition(_Model): - """Base definition for memory store configurations. - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - MemoryStoreDefaultDefinition +class MCPTool(Tool, discriminator="mcp"): + """MCP tool. - :ivar kind: The kind of the memory store. Required. "default" + :ivar type: The type of the MCP tool. Always ``mcp``. Required. MCP. + :vartype type: str or ~azure.ai.projects.models.MCP + :ivar server_label: A label for this MCP server, used to identify it in tool calls. Required. + :vartype server_label: str + :ivar server_url: The URL for the MCP server. One of ``server_url`` or ``connector_id`` must be + provided. + :vartype server_url: str + :ivar connector_id: Identifier for service connectors, like those available in ChatGPT. One of + ``server_url`` or ``connector_id`` must be provided. Learn more about service connectors `here + `_. Currently supported ``connector_id`` values are: + + * Dropbox: `connector_dropbox` + * Gmail: `connector_gmail` + * Google Calendar: `connector_googlecalendar` + * Google Drive: `connector_googledrive` + * Microsoft Teams: `connector_microsoftteams` + * Outlook Calendar: `connector_outlookcalendar` + * Outlook Email: `connector_outlookemail` + * SharePoint: `connector_sharepoint`. Is one of the following types: + Literal["connector_dropbox"], Literal["connector_gmail"], Literal["connector_googlecalendar"], + Literal["connector_googledrive"], Literal["connector_microsoftteams"], + Literal["connector_outlookcalendar"], Literal["connector_outlookemail"], + Literal["connector_sharepoint"] + :vartype connector_id: str or str or str or str or str or str or str or str + :ivar authorization: An OAuth access token that can be used with a remote MCP server, either + with a custom MCP server URL or a service connector. Your application must handle the OAuth + authorization flow and provide the token here. + :vartype authorization: str + :ivar server_description: Optional description of the MCP server, used to provide more context. + :vartype server_description: str + :ivar headers: + :vartype headers: dict[str, str] + :ivar allowed_tools: Is either a [str] type or a MCPToolFilter type. + :vartype allowed_tools: list[str] or ~azure.ai.projects.models.MCPToolFilter + :ivar require_approval: Is one of the following types: MCPToolRequireApproval, + Literal["always"], Literal["never"] + :vartype require_approval: ~azure.ai.projects.models.MCPToolRequireApproval or str or str + :ivar project_connection_id: The connection ID in the project for the MCP server. The + connection stores authentication and other connection details needed to connect to the MCP + server. + :vartype project_connection_id: str + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] + """ + + type: Literal[ToolType.MCP] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The type of the MCP tool. Always ``mcp``. Required. MCP.""" + server_label: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A label for this MCP server, used to identify it in tool calls. Required.""" + server_url: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The URL for the MCP server. One of ``server_url`` or ``connector_id`` must be provided.""" + connector_id: Optional[ + Literal[ + "connector_dropbox", + "connector_gmail", + "connector_googlecalendar", + "connector_googledrive", + "connector_microsoftteams", + "connector_outlookcalendar", + "connector_outlookemail", + "connector_sharepoint", + ] + ] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Identifier for service connectors, like those available in ChatGPT. One of ``server_url`` or + ``connector_id`` must be provided. Learn more about service connectors `here + `_. Currently supported ``connector_id`` values are: + + * Dropbox: `connector_dropbox` + * Gmail: `connector_gmail` + * Google Calendar: `connector_googlecalendar` + * Google Drive: `connector_googledrive` + * Microsoft Teams: `connector_microsoftteams` + * Outlook Calendar: `connector_outlookcalendar` + * Outlook Email: `connector_outlookemail` + * SharePoint: `connector_sharepoint`. Is one of the following types: + Literal[\"connector_dropbox\"], Literal[\"connector_gmail\"], + Literal[\"connector_googlecalendar\"], Literal[\"connector_googledrive\"], + Literal[\"connector_microsoftteams\"], Literal[\"connector_outlookcalendar\"], + Literal[\"connector_outlookemail\"], Literal[\"connector_sharepoint\"]""" + authorization: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """An OAuth access token that can be used with a remote MCP server, either with a custom MCP + server URL or a service connector. Your application must handle the OAuth authorization flow + and provide the token here.""" + server_description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Optional description of the MCP server, used to provide more context.""" + headers: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + allowed_tools: Optional[Union[list[str], "_models.MCPToolFilter"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Is either a [str] type or a MCPToolFilter type.""" + require_approval: Optional[Union["_models.MCPToolRequireApproval", Literal["always"], Literal["never"]]] = ( + rest_field(visibility=["read", "create", "update", "delete", "query"]) + ) + """Is one of the following types: MCPToolRequireApproval, Literal[\"always\"], Literal[\"never\"]""" + project_connection_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The connection ID in the project for the MCP server. The connection stores authentication and + other connection details needed to connect to the MCP server.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" + + @overload + def __init__( + self, + *, + server_label: str, + server_url: Optional[str] = None, + connector_id: Optional[ + Literal[ + "connector_dropbox", + "connector_gmail", + "connector_googlecalendar", + "connector_googledrive", + "connector_microsoftteams", + "connector_outlookcalendar", + "connector_outlookemail", + "connector_sharepoint", + ] + ] = None, + authorization: Optional[str] = None, + server_description: Optional[str] = None, + headers: Optional[dict[str, str]] = None, + allowed_tools: Optional[Union[list[str], "_models.MCPToolFilter"]] = None, + require_approval: Optional[Union["_models.MCPToolRequireApproval", Literal["always"], Literal["never"]]] = None, + project_connection_id: Optional[str] = None, + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = ToolType.MCP # type: ignore + + +class MCPToolFilter(_Model): + """MCP tool filter. + + :ivar tool_names: MCP allowed tools. + :vartype tool_names: list[str] + :ivar read_only: Indicates whether or not a tool modifies data or is read-only. If an MCP + server is `annotated with `readOnlyHint` + `_, + it will match this filter. + :vartype read_only: bool + """ + + tool_names: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """MCP allowed tools.""" + read_only: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Indicates whether or not a tool modifies data or is read-only. If an MCP server is `annotated + with `readOnlyHint` + `_, + it will match this filter.""" + + @overload + def __init__( + self, + *, + tool_names: Optional[list[str]] = None, + read_only: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MCPToolRequireApproval(_Model): + """MCPToolRequireApproval. + + :ivar always: + :vartype always: ~azure.ai.projects.models.MCPToolFilter + :ivar never: + :vartype never: ~azure.ai.projects.models.MCPToolFilter + """ + + always: Optional["_models.MCPToolFilter"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + never: Optional["_models.MCPToolFilter"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + + @overload + def __init__( + self, + *, + always: Optional["_models.MCPToolFilter"] = None, + never: Optional["_models.MCPToolFilter"] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MemoryOperation(_Model): + """Represents a single memory operation (create, update, or delete) performed on a memory item. + + :ivar kind: The type of memory operation being performed. Required. Known values are: "create", + "update", and "delete". + :vartype kind: str or ~azure.ai.projects.models.MemoryOperationKind + :ivar memory_item: The memory item to create, update, or delete. Required. + :vartype memory_item: ~azure.ai.projects.models.MemoryItem + """ + + kind: Union[str, "_models.MemoryOperationKind"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The type of memory operation being performed. Required. Known values are: \"create\", + \"update\", and \"delete\".""" + memory_item: "_models.MemoryItem" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The memory item to create, update, or delete. Required.""" + + @overload + def __init__( + self, + *, + kind: Union[str, "_models.MemoryOperationKind"], + memory_item: "_models.MemoryItem", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MemorySearchItem(_Model): + """A retrieved memory item from memory search. + + :ivar memory_item: Retrieved memory item. Required. + :vartype memory_item: ~azure.ai.projects.models.MemoryItem + """ + + memory_item: "_models.MemoryItem" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Retrieved memory item. Required.""" + + @overload + def __init__( + self, + *, + memory_item: "_models.MemoryItem", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MemorySearchOptions(_Model): + """Memory search options. + + :ivar max_memories: Maximum number of memory items to return. + :vartype max_memories: int + """ + + max_memories: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Maximum number of memory items to return.""" + + @overload + def __init__( + self, + *, + max_memories: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MemorySearchPreviewTool(Tool, discriminator="memory_search_preview"): + """A tool for integrating memories into the agent. + + :ivar type: The type of the tool. Always ``memory_search_preview``. Required. + MEMORY_SEARCH_PREVIEW. + :vartype type: str or ~azure.ai.projects.models.MEMORY_SEARCH_PREVIEW + :ivar name: Optional user-defined name for this tool or configuration. + :vartype name: str + :ivar description: Optional user-defined description for this tool or configuration. + :vartype description: str + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] + :ivar memory_store_name: The name of the memory store to use. Required. + :vartype memory_store_name: str + :ivar scope: The namespace used to group and isolate memories, such as a user ID. Limits which + memories can be retrieved or updated. Use special variable ``{{$userId}}`` to scope memories to + the current signed-in user. Required. + :vartype scope: str + :ivar search_options: Options for searching the memory store. + :vartype search_options: ~azure.ai.projects.models.MemorySearchOptions + :ivar update_delay: Time to wait before updating memories after inactivity (seconds). Default + 300. + :vartype update_delay: int + """ + + type: Literal[ToolType.MEMORY_SEARCH_PREVIEW] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The type of the tool. Always ``memory_search_preview``. Required. MEMORY_SEARCH_PREVIEW.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Optional user-defined name for this tool or configuration.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Optional user-defined description for this tool or configuration.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" + memory_store_name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the memory store to use. Required.""" + scope: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The namespace used to group and isolate memories, such as a user ID. Limits which memories can + be retrieved or updated. Use special variable ``{{$userId}}`` to scope memories to the current + signed-in user. Required.""" + search_options: Optional["_models.MemorySearchOptions"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Options for searching the memory store.""" + update_delay: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Time to wait before updating memories after inactivity (seconds). Default 300.""" + + @overload + def __init__( + self, + *, + memory_store_name: str, + scope: str, + name: Optional[str] = None, + description: Optional[str] = None, + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, + search_options: Optional["_models.MemorySearchOptions"] = None, + update_delay: Optional[int] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = ToolType.MEMORY_SEARCH_PREVIEW # type: ignore + + +class MemoryStoreDefinition(_Model): + """Base definition for memory store configurations. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + MemoryStoreDefaultDefinition + + :ivar kind: The kind of the memory store. Required. "default" :vartype kind: str or ~azure.ai.projects.models.MemoryStoreKind """ - __mapping__: dict[str, _Model] = {} - kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) - """The kind of the memory store. Required. \"default\"""" + __mapping__: dict[str, _Model] = {} + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) + """The kind of the memory store. Required. \"default\"""" + + @overload + def __init__( + self, + *, + kind: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MemoryStoreDefaultDefinition(MemoryStoreDefinition, discriminator="default"): + """Default memory store implementation. + + :ivar kind: The kind of the memory store. Required. The default memory store implementation. + :vartype kind: str or ~azure.ai.projects.models.DEFAULT + :ivar chat_model: The name or identifier of the chat completion model deployment used for + memory processing. Required. + :vartype chat_model: str + :ivar embedding_model: The name or identifier of the embedding model deployment used for memory + processing. Required. + :vartype embedding_model: str + :ivar options: Default memory store options. + :vartype options: ~azure.ai.projects.models.MemoryStoreDefaultOptions + """ + + kind: Literal[MemoryStoreKind.DEFAULT] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The kind of the memory store. Required. The default memory store implementation.""" + chat_model: str = rest_field(visibility=["read", "create"]) + """The name or identifier of the chat completion model deployment used for memory processing. + Required.""" + embedding_model: str = rest_field(visibility=["read", "create"]) + """The name or identifier of the embedding model deployment used for memory processing. Required.""" + options: Optional["_models.MemoryStoreDefaultOptions"] = rest_field(visibility=["read", "create"]) + """Default memory store options.""" + + @overload + def __init__( + self, + *, + chat_model: str, + embedding_model: str, + options: Optional["_models.MemoryStoreDefaultOptions"] = 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.kind = MemoryStoreKind.DEFAULT # type: ignore + + +class MemoryStoreDefaultOptions(_Model): + """Default memory store configurations. + + :ivar user_profile_enabled: Whether to enable user profile extraction and storage. Default is + true. Required. + :vartype user_profile_enabled: bool + :ivar user_profile_details: Specific categories or types of user profile information to extract + and store. + :vartype user_profile_details: str + :ivar chat_summary_enabled: Whether to enable chat summary extraction and storage. Default is + true. Required. + :vartype chat_summary_enabled: bool + :ivar procedural_memory_enabled: Whether to enable procedural memory extraction and storage. + Default is true. + :vartype procedural_memory_enabled: bool + :ivar default_ttl_seconds: The default time-to-live for memories in seconds. A value of 0 + indicates that memories do not expire. + :vartype default_ttl_seconds: int + """ + + user_profile_enabled: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Whether to enable user profile extraction and storage. Default is true. Required.""" + user_profile_details: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Specific categories or types of user profile information to extract and store.""" + chat_summary_enabled: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Whether to enable chat summary extraction and storage. Default is true. Required.""" + procedural_memory_enabled: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Whether to enable procedural memory extraction and storage. Default is true.""" + default_ttl_seconds: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The default time-to-live for memories in seconds. A value of 0 indicates that memories do not + expire.""" + + @overload + def __init__( + self, + *, + user_profile_enabled: bool, + chat_summary_enabled: bool, + user_profile_details: Optional[str] = None, + procedural_memory_enabled: Optional[bool] = None, + default_ttl_seconds: 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 MemoryStoreDeleteScopeResult(_Model): + """Response for deleting memories from a scope. + + :ivar object: The object type. Always 'memory_store.scope.deleted'. Required. + MEMORY_STORE_SCOPE_DELETED. + :vartype object: str or ~azure.ai.projects.models.MEMORY_STORE_SCOPE_DELETED + :ivar name: The name of the memory store. Required. + :vartype name: str + :ivar scope: The scope from which memories were deleted. Required. + :vartype scope: str + :ivar deleted: Whether the deletion operation was successful. Required. + :vartype deleted: bool + """ + + object: Literal[MemoryStoreObjectType.MEMORY_STORE_SCOPE_DELETED] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The object type. Always 'memory_store.scope.deleted'. Required. MEMORY_STORE_SCOPE_DELETED.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the memory store. Required.""" + scope: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The scope from which memories were deleted. Required.""" + deleted: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Whether the deletion operation was successful. Required.""" + + @overload + def __init__( + self, + *, + object: Literal[MemoryStoreObjectType.MEMORY_STORE_SCOPE_DELETED], + name: str, + scope: str, + deleted: bool, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MemoryStoreDetails(_Model): + """A memory store that can store and retrieve user memories. + + :ivar object: The object type, which is always 'memory_store'. Required. MEMORY_STORE. + :vartype object: str or ~azure.ai.projects.models.MEMORY_STORE + :ivar id: The unique identifier of the memory store. Required. + :vartype id: str + :ivar created_at: The Unix timestamp (seconds) when the memory store was created. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: The Unix timestamp (seconds) when the memory store was last updated. + Required. + :vartype updated_at: ~datetime.datetime + :ivar name: The name of the memory store. Required. + :vartype name: str + :ivar description: A human-readable description of the memory store. + :vartype description: str + :ivar metadata: Arbitrary key-value metadata to associate with the memory store. + :vartype metadata: dict[str, str] + :ivar definition: The definition of the memory store. Required. + :vartype definition: ~azure.ai.projects.models.MemoryStoreDefinition + """ + + object: Literal[MemoryStoreObjectType.MEMORY_STORE] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The object type, which is always 'memory_store'. Required. MEMORY_STORE.""" + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The unique identifier of the memory store. Required.""" + created_at: datetime.datetime = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" + ) + """The Unix timestamp (seconds) when the memory store was created. Required.""" + updated_at: datetime.datetime = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" + ) + """The Unix timestamp (seconds) when the memory store was last updated. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the memory store. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A human-readable description of the memory store.""" + metadata: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Arbitrary key-value metadata to associate with the memory store.""" + definition: "_models.MemoryStoreDefinition" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The definition of the memory store. Required.""" + + @overload + def __init__( + self, + *, + object: Literal[MemoryStoreObjectType.MEMORY_STORE], + id: str, # pylint: disable=redefined-builtin + created_at: datetime.datetime, + updated_at: datetime.datetime, + name: str, + definition: "_models.MemoryStoreDefinition", + description: Optional[str] = None, + metadata: Optional[dict[str, 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 MemoryStoreOperationUsage(_Model): + """Usage statistics of a memory store operation. + + :ivar embedding_tokens: The number of embedding tokens. Required. + :vartype embedding_tokens: int + :ivar input_tokens: The number of input tokens. Required. + :vartype input_tokens: int + :ivar input_tokens_details: A detailed breakdown of the input tokens. Required. + :vartype input_tokens_details: ~azure.ai.projects.models.ResponseUsageInputTokensDetails + :ivar output_tokens: The number of output tokens. Required. + :vartype output_tokens: int + :ivar output_tokens_details: A detailed breakdown of the output tokens. Required. + :vartype output_tokens_details: ~azure.ai.projects.models.ResponseUsageOutputTokensDetails + :ivar total_tokens: The total number of tokens used. Required. + :vartype total_tokens: int + """ + + embedding_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The number of embedding tokens. Required.""" + input_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The number of input tokens. Required.""" + input_tokens_details: "_models.ResponseUsageInputTokensDetails" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A detailed breakdown of the input tokens. Required.""" + output_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The number of output tokens. Required.""" + output_tokens_details: "_models.ResponseUsageOutputTokensDetails" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A detailed breakdown of the output tokens. Required.""" + total_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The total number of tokens used. Required.""" + + @overload + def __init__( + self, + *, + embedding_tokens: int, + input_tokens: int, + input_tokens_details: "_models.ResponseUsageInputTokensDetails", + output_tokens: int, + output_tokens_details: "_models.ResponseUsageOutputTokensDetails", + total_tokens: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class MemoryStoreSearchResult(_Model): + """Memory search response. + + :ivar search_id: The unique ID of this search request. Use this value as previous_search_id in + subsequent requests to perform incremental searches. Required. + :vartype search_id: str + :ivar memories: Related memory items found during the search operation. Required. + :vartype memories: list[~azure.ai.projects.models.MemorySearchItem] + :ivar usage: Usage statistics associated with the memory search operation. Required. + :vartype usage: ~azure.ai.projects.models.MemoryStoreOperationUsage + """ + + search_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The unique ID of this search request. Use this value as previous_search_id in subsequent + requests to perform incremental searches. Required.""" + memories: list["_models.MemorySearchItem"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Related memory items found during the search operation. Required.""" + usage: "_models.MemoryStoreOperationUsage" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Usage statistics associated with the memory search operation. Required.""" + + @overload + def __init__( + self, + *, + search_id: str, + memories: list["_models.MemorySearchItem"], + usage: "_models.MemoryStoreOperationUsage", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param 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 MemoryStoreUpdateCompletedResult(_Model): + """Memory update result. + + :ivar memory_operations: A list of individual memory operations that were performed during the + update. Required. + :vartype memory_operations: list[~azure.ai.projects.models.MemoryOperation] + :ivar usage: Usage statistics associated with the memory update operation. Required. + :vartype usage: ~azure.ai.projects.models.MemoryStoreOperationUsage + """ + + memory_operations: list["_models.MemoryOperation"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """A list of individual memory operations that were performed during the update. Required.""" + usage: "_models.MemoryStoreOperationUsage" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Usage statistics associated with the memory update operation. Required.""" + + @overload + def __init__( + self, + *, + memory_operations: list["_models.MemoryOperation"], + usage: "_models.MemoryStoreOperationUsage", + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param 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 MemoryStoreUpdateResult(_Model): + """Provides the status of a memory store update operation. + + :ivar update_id: The unique ID of this update request. Use this value as previous_update_id in + subsequent requests to perform incremental updates. Required. + :vartype update_id: str + :ivar status: The status of the memory update operation. One of "queued", "in_progress", + "completed", "failed", or "superseded". Required. Known values are: "queued", "in_progress", + "completed", "failed", and "superseded". + :vartype status: str or ~azure.ai.projects.models.MemoryStoreUpdateStatus + :ivar superseded_by: The update_id the operation was superseded by when status is "superseded". + :vartype superseded_by: str + :ivar result: The result of memory store update operation when status is "completed". + :vartype result: ~azure.ai.projects.models.MemoryStoreUpdateCompletedResult + :ivar error: Error object that describes the error when status is "failed". + :vartype error: ~azure.ai.projects.models.ApiError + """ + + update_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The unique ID of this update request. Use this value as previous_update_id in subsequent + requests to perform incremental updates. Required.""" + status: Union[str, "_models.MemoryStoreUpdateStatus"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The status of the memory update operation. One of \"queued\", \"in_progress\", \"completed\", + \"failed\", or \"superseded\". Required. Known values are: \"queued\", \"in_progress\", + \"completed\", \"failed\", and \"superseded\".""" + superseded_by: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The update_id the operation was superseded by when status is \"superseded\".""" + result: Optional["_models.MemoryStoreUpdateCompletedResult"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The result of memory store update operation when status is \"completed\".""" + error: Optional["_models.ApiError"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Error object that describes the error when status is \"failed\".""" + + @overload + def __init__( + self, + *, + update_id: str, + status: Union[str, "_models.MemoryStoreUpdateStatus"], + superseded_by: Optional[str] = None, + result: Optional["_models.MemoryStoreUpdateCompletedResult"] = None, + error: Optional["_models.ApiError"] = 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 MicrosoftFabricPreviewTool(Tool, discriminator="fabric_dataagent_preview"): + """The input definition information for a Microsoft Fabric tool as used to configure an agent. + + :ivar type: The object type, which is always 'fabric_dataagent_preview'. Required. + FABRIC_DATAAGENT_PREVIEW. + :vartype type: str or ~azure.ai.projects.models.FABRIC_DATAAGENT_PREVIEW + :ivar name: Optional user-defined name for this tool or configuration. + :vartype name: str + :ivar description: Optional user-defined description for this tool or configuration. + :vartype description: str + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] + :ivar fabric_dataagent_preview: The fabric data agent tool parameters. Required. + :vartype fabric_dataagent_preview: ~azure.ai.projects.models.FabricDataAgentToolParameters + """ + + type: Literal[ToolType.FABRIC_DATAAGENT_PREVIEW] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The object type, which is always 'fabric_dataagent_preview'. Required. + FABRIC_DATAAGENT_PREVIEW.""" + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Optional user-defined name for this tool or configuration.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Optional user-defined description for this tool or configuration.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" + fabric_dataagent_preview: "_models.FabricDataAgentToolParameters" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The fabric data agent tool parameters. Required.""" + + @overload + def __init__( + self, + *, + fabric_dataagent_preview: "_models.FabricDataAgentToolParameters", + name: Optional[str] = None, + description: Optional[str] = None, + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = ToolType.FABRIC_DATAAGENT_PREVIEW # type: ignore + + +class ModelCredentialRequest(_Model): + """Request to fetch credentials for a model asset. + + :ivar blob_uri: Blob URI of the model asset to fetch credentials for. Required. + :vartype blob_uri: str + """ + + blob_uri: str = rest_field(name="blobUri", visibility=["read", "create", "update", "delete", "query"]) + """Blob URI of the model asset to fetch credentials for. Required.""" + + @overload + def __init__( + self, + *, + blob_uri: 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 ModelDeployment(Deployment, discriminator="ModelDeployment"): + """Model Deployment Definition. + + :ivar name: Name of the deployment. Required. + :vartype name: str + :ivar type: The type of the deployment. Required. Model deployment. + :vartype type: str or ~azure.ai.projects.models.MODEL_DEPLOYMENT + :ivar model_name: Publisher-specific name of the deployed model. Required. + :vartype model_name: str + :ivar model_version: Publisher-specific version of the deployed model. Required. + :vartype model_version: str + :ivar model_publisher: Name of the deployed model's publisher. Required. + :vartype model_publisher: str + :ivar capabilities: Capabilities of deployed model. Required. + :vartype capabilities: dict[str, str] + :ivar sku: Sku of the model deployment. Required. + :vartype sku: ~azure.ai.projects.models.ModelDeploymentSku + :ivar connection_name: Name of the connection the deployment comes from. + :vartype connection_name: str + """ + + type: Literal[DeploymentType.MODEL_DEPLOYMENT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The type of the deployment. Required. Model deployment.""" + model_name: str = rest_field(name="modelName", visibility=["read"]) + """Publisher-specific name of the deployed model. Required.""" + model_version: str = rest_field(name="modelVersion", visibility=["read"]) + """Publisher-specific version of the deployed model. Required.""" + model_publisher: str = rest_field(name="modelPublisher", visibility=["read"]) + """Name of the deployed model's publisher. Required.""" + capabilities: dict[str, str] = rest_field(visibility=["read"]) + """Capabilities of deployed model. Required.""" + sku: "_models.ModelDeploymentSku" = rest_field(visibility=["read"]) + """Sku of the model deployment. Required.""" + connection_name: Optional[str] = rest_field(name="connectionName", visibility=["read"]) + """Name of the connection the deployment comes from.""" + + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = DeploymentType.MODEL_DEPLOYMENT # type: ignore + + +class ModelDeploymentSku(_Model): + """Sku information. + + :ivar capacity: Sku capacity. Required. + :vartype capacity: int + :ivar family: Sku family. Required. + :vartype family: str + :ivar name: Sku name. Required. + :vartype name: str + :ivar size: Sku size. Required. + :vartype size: str + :ivar tier: Sku tier. Required. + :vartype tier: str + """ + + capacity: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Sku capacity. Required.""" + family: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Sku family. Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Sku name. Required.""" + size: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Sku size. Required.""" + tier: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Sku tier. Required.""" @overload def __init__( self, *, - kind: str, + capacity: int, + family: str, + name: str, + size: str, + tier: str, ) -> None: ... @overload @@ -7973,38 +9923,40 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class MemoryStoreDefaultDefinition(MemoryStoreDefinition, discriminator="default"): - """Default memory store implementation. +class ModelPendingUploadRequest(_Model): + """Represents a request for a pending upload of a model version. - :ivar kind: The kind of the memory store. Required. The default memory store implementation. - :vartype kind: str or ~azure.ai.projects.models.DEFAULT - :ivar chat_model: The name or identifier of the chat completion model deployment used for - memory processing. Required. - :vartype chat_model: str - :ivar embedding_model: The name or identifier of the embedding model deployment used for memory - processing. Required. - :vartype embedding_model: str - :ivar options: Default memory store options. - :vartype options: ~azure.ai.projects.models.MemoryStoreDefaultOptions + :ivar pending_upload_id: If PendingUploadId is not provided, a random GUID will be used. + :vartype pending_upload_id: str + :ivar connection_name: Azure Storage Account connection name to use for generating temporary + SAS token. + :vartype connection_name: str + :ivar pending_upload_type: The type of pending upload. Only TemporaryBlobReference is supported + for models. Required. Temporary blob reference. + :vartype pending_upload_type: str or ~azure.ai.projects.models.TEMPORARY_BLOB_REFERENCE """ - kind: Literal[MemoryStoreKind.DEFAULT] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The kind of the memory store. Required. The default memory store implementation.""" - chat_model: str = rest_field(visibility=["read", "create"]) - """The name or identifier of the chat completion model deployment used for memory processing. - Required.""" - embedding_model: str = rest_field(visibility=["read", "create"]) - """The name or identifier of the embedding model deployment used for memory processing. Required.""" - options: Optional["_models.MemoryStoreDefaultOptions"] = rest_field(visibility=["read", "create"]) - """Default memory store options.""" + pending_upload_id: Optional[str] = rest_field( + name="pendingUploadId", visibility=["read", "create", "update", "delete", "query"] + ) + """If PendingUploadId is not provided, a random GUID will be used.""" + connection_name: Optional[str] = rest_field( + name="connectionName", visibility=["read", "create", "update", "delete", "query"] + ) + """Azure Storage Account connection name to use for generating temporary SAS token.""" + pending_upload_type: Literal[PendingUploadType.TEMPORARY_BLOB_REFERENCE] = rest_field( + name="pendingUploadType", visibility=["read", "create", "update", "delete", "query"] + ) + """The type of pending upload. Only TemporaryBlobReference is supported for models. Required. + Temporary blob reference.""" @overload def __init__( self, *, - chat_model: str, - embedding_model: str, - options: Optional["_models.MemoryStoreDefaultOptions"] = None, + pending_upload_type: Literal[PendingUploadType.TEMPORARY_BLOB_REFERENCE], + pending_upload_id: Optional[str] = None, + connection_name: Optional[str] = None, ) -> None: ... @overload @@ -8016,37 +9968,47 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.kind = MemoryStoreKind.DEFAULT # type: ignore -class MemoryStoreDefaultOptions(_Model): - """Default memory store configurations. +class ModelPendingUploadResponse(_Model): + """Represents the response for a model pending upload request. - :ivar user_profile_enabled: Whether to enable user profile extraction and storage. Default is - true. Required. - :vartype user_profile_enabled: bool - :ivar user_profile_details: Specific categories or types of user profile information to extract - and store. - :vartype user_profile_details: str - :ivar chat_summary_enabled: Whether to enable chat summary extraction and storage. Default is - true. Required. - :vartype chat_summary_enabled: bool + :ivar blob_reference: Container-level read, write, list SAS. Required. + :vartype blob_reference: ~azure.ai.projects.models.BlobReference + :ivar pending_upload_id: ID for this upload request. Required. + :vartype pending_upload_id: str + :ivar version: Version of asset to be created if user did not specify version when initially + creating upload. + :vartype version: str + :ivar pending_upload_type: The type of pending upload. Only TemporaryBlobReference is supported + for models. Required. Temporary blob reference. + :vartype pending_upload_type: str or ~azure.ai.projects.models.TEMPORARY_BLOB_REFERENCE """ - user_profile_enabled: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Whether to enable user profile extraction and storage. Default is true. Required.""" - user_profile_details: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Specific categories or types of user profile information to extract and store.""" - chat_summary_enabled: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Whether to enable chat summary extraction and storage. Default is true. Required.""" + blob_reference: "_models.BlobReference" = rest_field( + name="blobReference", visibility=["read", "create", "update", "delete", "query"] + ) + """Container-level read, write, list SAS. Required.""" + pending_upload_id: str = rest_field( + name="pendingUploadId", visibility=["read", "create", "update", "delete", "query"] + ) + """ID for this upload request. Required.""" + version: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Version of asset to be created if user did not specify version when initially creating upload.""" + pending_upload_type: Literal[PendingUploadType.TEMPORARY_BLOB_REFERENCE] = rest_field( + name="pendingUploadType", visibility=["read", "create", "update", "delete", "query"] + ) + """The type of pending upload. Only TemporaryBlobReference is supported for models. Required. + Temporary blob reference.""" @overload def __init__( self, *, - user_profile_enabled: bool, - chat_summary_enabled: bool, - user_profile_details: Optional[str] = None, + blob_reference: "_models.BlobReference", + pending_upload_id: str, + pending_upload_type: Literal[PendingUploadType.TEMPORARY_BLOB_REFERENCE], + version: Optional[str] = None, ) -> None: ... @overload @@ -8060,39 +10022,73 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class MemoryStoreDeleteScopeResult(_Model): - """Response for deleting memories from a scope. +class ModelSamplingParams(_Model): + """Represents a set of parameters used to control the sampling behavior of a language model during + text generation. - :ivar object: The object type. Always 'memory_store.scope.deleted'. Required. - MEMORY_STORE_SCOPE_DELETED. - :vartype object: str or ~azure.ai.projects.models.MEMORY_STORE_SCOPE_DELETED - :ivar name: The name of the memory store. Required. - :vartype name: str - :ivar scope: The scope from which memories were deleted. Required. - :vartype scope: str - :ivar deleted: Whether the deletion operation was successful. Required. - :vartype deleted: bool + :ivar temperature: The temperature parameter for sampling. Defaults to 1.0. + :vartype temperature: float + :ivar top_p: The top-p parameter for nucleus sampling. Defaults to 1.0. + :vartype top_p: float + :ivar seed: The random seed for reproducibility. Defaults to 42. + :vartype seed: int + :ivar max_completion_tokens: The maximum number of tokens allowed in the completion. + :vartype max_completion_tokens: int """ - object: Literal[MemoryStoreObjectType.MEMORY_STORE_SCOPE_DELETED] = rest_field( - visibility=["read", "create", "update", "delete", "query"] + temperature: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The temperature parameter for sampling. Defaults to 1.0.""" + top_p: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The top-p parameter for nucleus sampling. Defaults to 1.0.""" + seed: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The random seed for reproducibility. Defaults to 42.""" + max_completion_tokens: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The maximum number of tokens allowed in the completion.""" + + @overload + def __init__( + self, + *, + temperature: Optional[float] = None, + top_p: Optional[float] = None, + seed: Optional[int] = None, + max_completion_tokens: 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 ModelSourceData(_Model): + """Source information for the model. + + :ivar source_type: The source type of the model. Known values are: "LocalUpload" and + "TrainingJob". + :vartype source_type: str or ~azure.ai.projects.models.FoundryModelSourceType + :ivar job_id: The job ID that produced this model. + :vartype job_id: str + """ + + source_type: Optional[Union[str, "_models.FoundryModelSourceType"]] = rest_field( + name="sourceType", visibility=["read", "create", "update", "delete", "query"] ) - """The object type. Always 'memory_store.scope.deleted'. Required. MEMORY_STORE_SCOPE_DELETED.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the memory store. Required.""" - scope: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The scope from which memories were deleted. Required.""" - deleted: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Whether the deletion operation was successful. Required.""" + """The source type of the model. Known values are: \"LocalUpload\" and \"TrainingJob\".""" + job_id: Optional[str] = rest_field(name="jobId", visibility=["read", "create", "update", "delete", "query"]) + """The job ID that produced this model.""" @overload def __init__( self, *, - object: Literal[MemoryStoreObjectType.MEMORY_STORE_SCOPE_DELETED], - name: str, - scope: str, - deleted: bool, + source_type: Optional[Union[str, "_models.FoundryModelSourceType"]] = None, + job_id: Optional[str] = None, ) -> None: ... @overload @@ -8106,63 +10102,82 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class MemoryStoreDetails(_Model): - """A memory store that can store and retrieve user memories. +class ModelVersion(_Model): + """Model Version Definition. - :ivar object: The object type, which is always 'memory_store'. Required. MEMORY_STORE. - :vartype object: str or ~azure.ai.projects.models.MEMORY_STORE - :ivar id: The unique identifier of the memory store. Required. + :ivar system_data: System related metadata. + :vartype system_data: ~azure.ai.projects.models.SystemDataV3 + :ivar blob_uri: URI of the model artifact in blob storage. Required. + :vartype blob_uri: str + :ivar weight_type: The weight type of the model. Known values are: "FullWeight", "LoRA", and + "DraftModel". + :vartype weight_type: str or ~azure.ai.projects.models.FoundryModelWeightType + :ivar base_model: Base model asset ID. + :vartype base_model: str + :ivar source: The source of the model. + :vartype source: ~azure.ai.projects.models.ModelSourceData + :ivar lora_config: Adapter-specific configuration. Required when weight_type is lora; ignored + otherwise. May be auto-populated from adapter_config.json when present in the uploaded files — + user-provided values take precedence over auto-detected values. + :vartype lora_config: ~azure.ai.projects.models.LoraConfig + :ivar artifact_profile: The artifact profile of the model. + :vartype artifact_profile: ~azure.ai.projects.models.ArtifactProfile + :ivar warnings: Service-computed advisory warnings derived from the artifact profile. + :vartype warnings: list[~azure.ai.projects.models.FoundryModelWarning] + :ivar id: Asset ID, a unique identifier for the asset. :vartype id: str - :ivar created_at: The Unix timestamp (seconds) when the memory store was created. Required. - :vartype created_at: ~datetime.datetime - :ivar updated_at: The Unix timestamp (seconds) when the memory store was last updated. - Required. - :vartype updated_at: ~datetime.datetime - :ivar name: The name of the memory store. Required. + :ivar name: The name of the resource. Required. :vartype name: str - :ivar description: A human-readable description of the memory store. - :vartype description: str - :ivar metadata: Arbitrary key-value metadata to associate with the memory store. - :vartype metadata: dict[str, str] - :ivar definition: The definition of the memory store. Required. - :vartype definition: ~azure.ai.projects.models.MemoryStoreDefinition + :ivar version: The version of the resource. Required. + :vartype version: str + :ivar description: The asset description text. + :vartype description: str + :ivar tags: Tag dictionary. Tags can be added, removed, and updated. + :vartype tags: dict[str, str] """ - object: Literal[MemoryStoreObjectType.MEMORY_STORE] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The object type, which is always 'memory_store'. Required. MEMORY_STORE.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique identifier of the memory store. Required.""" - created_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp (seconds) when the memory store was created. Required.""" - updated_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp (seconds) when the memory store was last updated. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the memory store. Required.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A human-readable description of the memory store.""" - metadata: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Arbitrary key-value metadata to associate with the memory store.""" - definition: "_models.MemoryStoreDefinition" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The definition of the memory store. Required.""" + system_data: Optional["_models.SystemDataV3"] = rest_field(name="systemData", visibility=["read"]) + """System related metadata.""" + blob_uri: str = rest_field(name="blobUri", visibility=["read", "create", "update", "delete", "query"]) + """URI of the model artifact in blob storage. Required.""" + weight_type: Optional[Union[str, "_models.FoundryModelWeightType"]] = rest_field( + name="weightType", visibility=["read", "create", "update", "delete", "query"] + ) + """The weight type of the model. Known values are: \"FullWeight\", \"LoRA\", and \"DraftModel\".""" + base_model: Optional[str] = rest_field(name="baseModel", visibility=["read", "create"]) + """Base model asset ID.""" + source: Optional["_models.ModelSourceData"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The source of the model.""" + lora_config: Optional["_models.LoraConfig"] = rest_field(name="loraConfig", visibility=["read", "create"]) + """Adapter-specific configuration. Required when weight_type is lora; ignored otherwise. May be + auto-populated from adapter_config.json when present in the uploaded files — user-provided + values take precedence over auto-detected values.""" + artifact_profile: Optional["_models.ArtifactProfile"] = rest_field(name="artifactProfile", visibility=["read"]) + """The artifact profile of the model.""" + warnings: Optional[list["_models.FoundryModelWarning"]] = rest_field(visibility=["read"]) + """Service-computed advisory warnings derived from the artifact profile.""" + id: Optional[str] = rest_field(visibility=["read"]) + """Asset ID, a unique identifier for the asset.""" + name: str = rest_field(visibility=["read"]) + """The name of the resource. Required.""" + version: str = rest_field(visibility=["read"]) + """The version of the resource. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update"]) + """The asset description text.""" + tags: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update"]) + """Tag dictionary. Tags can be added, removed, and updated.""" @overload def __init__( self, *, - object: Literal[MemoryStoreObjectType.MEMORY_STORE], - id: str, # pylint: disable=redefined-builtin - created_at: datetime.datetime, - updated_at: datetime.datetime, - name: str, - definition: "_models.MemoryStoreDefinition", + blob_uri: str, + weight_type: Optional[Union[str, "_models.FoundryModelWeightType"]] = None, + base_model: Optional[str] = None, + source: Optional["_models.ModelSourceData"] = None, + lora_config: Optional["_models.LoraConfig"] = None, description: Optional[str] = None, - metadata: Optional[dict[str, str]] = None, + tags: Optional[dict[str, str]] = None, ) -> None: ... @overload @@ -8176,50 +10191,27 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class MemoryStoreOperationUsage(_Model): - """Usage statistics of a memory store operation. +class MonthlyRecurrenceSchedule(RecurrenceSchedule, discriminator="Monthly"): + """Monthly recurrence schedule. - :ivar embedding_tokens: The number of embedding tokens. Required. - :vartype embedding_tokens: int - :ivar input_tokens: The number of input tokens. Required. - :vartype input_tokens: int - :ivar input_tokens_details: A detailed breakdown of the input tokens. Required. - :vartype input_tokens_details: ~azure.ai.projects.models.ResponseUsageInputTokensDetails - :ivar output_tokens: The number of output tokens. Required. - :vartype output_tokens: int - :ivar output_tokens_details: A detailed breakdown of the output tokens. Required. - :vartype output_tokens_details: ~azure.ai.projects.models.ResponseUsageOutputTokensDetails - :ivar total_tokens: The total number of tokens used. Required. - :vartype total_tokens: int + :ivar type: Monthly recurrence type. Required. Monthly recurrence pattern. + :vartype type: str or ~azure.ai.projects.models.MONTHLY + :ivar days_of_month: Days of the month for the recurrence schedule. Required. + :vartype days_of_month: list[int] """ - embedding_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The number of embedding tokens. Required.""" - input_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The number of input tokens. Required.""" - input_tokens_details: "_models.ResponseUsageInputTokensDetails" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """A detailed breakdown of the input tokens. Required.""" - output_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The number of output tokens. Required.""" - output_tokens_details: "_models.ResponseUsageOutputTokensDetails" = rest_field( - visibility=["read", "create", "update", "delete", "query"] + type: Literal[RecurrenceType.MONTHLY] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Monthly recurrence type. Required. Monthly recurrence pattern.""" + days_of_month: list[int] = rest_field( + name="daysOfMonth", visibility=["read", "create", "update", "delete", "query"] ) - """A detailed breakdown of the output tokens. Required.""" - total_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The total number of tokens used. Required.""" + """Days of the month for the recurrence schedule. Required.""" @overload def __init__( self, *, - embedding_tokens: int, - input_tokens: int, - input_tokens_details: "_models.ResponseUsageInputTokensDetails", - output_tokens: int, - output_tokens_details: "_models.ResponseUsageOutputTokensDetails", - total_tokens: int, + days_of_month: list[int], ) -> None: ... @overload @@ -8231,35 +10223,22 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) + self.type = RecurrenceType.MONTHLY # type: ignore -class MemoryStoreSearchResult(_Model): - """Memory search response. +class NoAuthenticationCredentials(BaseCredentials, discriminator="None"): + """Credentials that do not require authentication. - :ivar search_id: The unique ID of this search request. Use this value as previous_search_id in - subsequent requests to perform incremental searches. Required. - :vartype search_id: str - :ivar memories: Related memory items found during the search operation. Required. - :vartype memories: list[~azure.ai.projects.models.MemorySearchItem] - :ivar usage: Usage statistics associated with the memory search operation. Required. - :vartype usage: ~azure.ai.projects.models.MemoryStoreOperationUsage + :ivar type: The credential type. Required. No credential. + :vartype type: str or ~azure.ai.projects.models.NONE """ - search_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of this search request. Use this value as previous_search_id in subsequent - requests to perform incremental searches. Required.""" - memories: list["_models.MemorySearchItem"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Related memory items found during the search operation. Required.""" - usage: "_models.MemoryStoreOperationUsage" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Usage statistics associated with the memory search operation. Required.""" + type: Literal[CredentialType.NONE] = rest_discriminator(name="type", visibility=["read"]) # type: ignore + """The credential type. Required. No credential.""" @overload def __init__( self, - *, - search_id: str, - memories: list["_models.MemorySearchItem"], - usage: "_models.MemoryStoreOperationUsage", ) -> None: ... @overload @@ -8271,31 +10250,35 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) + self.type = CredentialType.NONE # type: ignore -class MemoryStoreUpdateCompletedResult(_Model): - """Memory update result. +class OneTimeTrigger(Trigger, discriminator="OneTime"): + """One-time trigger. - :ivar memory_operations: A list of individual memory operations that were performed during the - update. Required. - :vartype memory_operations: list[~azure.ai.projects.models.MemoryOperation] - :ivar usage: Usage statistics associated with the memory update operation. Required. - :vartype usage: ~azure.ai.projects.models.MemoryStoreOperationUsage + :ivar type: Required. One-time trigger. + :vartype type: str or ~azure.ai.projects.models.ONE_TIME + :ivar trigger_at: Date and time for the one-time trigger in ISO 8601 format. Required. + :vartype trigger_at: ~datetime.datetime + :ivar time_zone: Time zone for the one-time trigger. + :vartype time_zone: str """ - memory_operations: list["_models.MemoryOperation"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] + type: Literal[TriggerType.ONE_TIME] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required. One-time trigger.""" + trigger_at: datetime.datetime = rest_field( + name="triggerAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" ) - """A list of individual memory operations that were performed during the update. Required.""" - usage: "_models.MemoryStoreOperationUsage" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Usage statistics associated with the memory update operation. Required.""" + """Date and time for the one-time trigger in ISO 8601 format. Required.""" + time_zone: Optional[str] = rest_field(name="timeZone", visibility=["read", "create", "update", "delete", "query"]) + """Time zone for the one-time trigger.""" @overload def __init__( self, *, - memory_operations: list["_models.MemoryOperation"], - usage: "_models.MemoryStoreOperationUsage", + trigger_at: datetime.datetime, + time_zone: Optional[str] = None, ) -> None: ... @overload @@ -8307,53 +10290,30 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) + self.type = TriggerType.ONE_TIME # type: ignore -class MemoryStoreUpdateResult(_Model): - """Provides the status of a memory store update operation. +class OpenApiAuthDetails(_Model): + """authentication details for OpenApiFunctionDefinition. - :ivar update_id: The unique ID of this update request. Use this value as previous_update_id in - subsequent requests to perform incremental updates. Required. - :vartype update_id: str - :ivar status: The status of the memory update operation. One of "queued", "in_progress", - "completed", "failed", or "superseded". Required. Known values are: "queued", "in_progress", - "completed", "failed", and "superseded". - :vartype status: str or ~azure.ai.projects.models.MemoryStoreUpdateStatus - :ivar superseded_by: The update_id the operation was superseded by when status is "superseded". - :vartype superseded_by: str - :ivar result: The result of memory store update operation when status is "completed". - :vartype result: ~azure.ai.projects.models.MemoryStoreUpdateCompletedResult - :ivar error: Error object that describes the error when status is "failed". - :vartype error: ~azure.ai.projects.models.ApiError + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + OpenApiAnonymousAuthDetails, OpenApiManagedAuthDetails, OpenApiProjectConnectionAuthDetails + + :ivar type: The type of authentication, must be anonymous/project_connection/managed_identity. + Required. Known values are: "anonymous", "project_connection", and "managed_identity". + :vartype type: str or ~azure.ai.projects.models.OpenApiAuthType """ - update_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique ID of this update request. Use this value as previous_update_id in subsequent - requests to perform incremental updates. Required.""" - status: Union[str, "_models.MemoryStoreUpdateStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the memory update operation. One of \"queued\", \"in_progress\", \"completed\", - \"failed\", or \"superseded\". Required. Known values are: \"queued\", \"in_progress\", - \"completed\", \"failed\", and \"superseded\".""" - superseded_by: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The update_id the operation was superseded by when status is \"superseded\".""" - result: Optional["_models.MemoryStoreUpdateCompletedResult"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The result of memory store update operation when status is \"completed\".""" - error: Optional["_models.ApiError"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Error object that describes the error when status is \"failed\".""" + __mapping__: dict[str, _Model] = {} + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """The type of authentication, must be anonymous/project_connection/managed_identity. Required. + Known values are: \"anonymous\", \"project_connection\", and \"managed_identity\".""" @overload def __init__( self, *, - update_id: str, - status: Union[str, "_models.MemoryStoreUpdateStatus"], - superseded_by: Optional[str] = None, - result: Optional["_models.MemoryStoreUpdateCompletedResult"] = None, - error: Optional["_models.ApiError"] = None, + type: str, ) -> None: ... @overload @@ -8367,39 +10327,19 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class MicrosoftFabricPreviewTool(Tool, discriminator="fabric_dataagent_preview"): - """The input definition information for a Microsoft Fabric tool as used to configure an agent. +class OpenApiAnonymousAuthDetails(OpenApiAuthDetails, discriminator="anonymous"): + """Security details for OpenApi anonymous authentication. - :ivar type: The object type, which is always 'fabric_dataagent_preview'. Required. - FABRIC_DATAAGENT_PREVIEW. - :vartype type: str or ~azure.ai.projects.models.FABRIC_DATAAGENT_PREVIEW - :ivar name: Optional user-defined name for this tool or configuration. - :vartype name: str - :ivar description: Optional user-defined description for this tool or configuration. - :vartype description: str - :ivar fabric_dataagent_preview: The fabric data agent tool parameters. Required. - :vartype fabric_dataagent_preview: ~azure.ai.projects.models.FabricDataAgentToolParameters + :ivar type: The object type, which is always 'anonymous'. Required. ANONYMOUS. + :vartype type: str or ~azure.ai.projects.models.ANONYMOUS """ - type: Literal[ToolType.FABRIC_DATAAGENT_PREVIEW] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'fabric_dataagent_preview'. Required. - FABRIC_DATAAGENT_PREVIEW.""" - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined name for this tool or configuration.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Optional user-defined description for this tool or configuration.""" - fabric_dataagent_preview: "_models.FabricDataAgentToolParameters" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The fabric data agent tool parameters. Required.""" + type: Literal[OpenApiAuthType.ANONYMOUS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The object type, which is always 'anonymous'. Required. ANONYMOUS.""" @overload def __init__( self, - *, - fabric_dataagent_preview: "_models.FabricDataAgentToolParameters", - name: Optional[str] = None, - description: Optional[str] = None, ) -> None: ... @overload @@ -8411,48 +10351,50 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = ToolType.FABRIC_DATAAGENT_PREVIEW # type: ignore + self.type = OpenApiAuthType.ANONYMOUS # type: ignore -class ModelDeployment(Deployment, discriminator="ModelDeployment"): - """Model Deployment Definition. +class OpenApiFunctionDefinition(_Model): + """The input definition information for an openapi function. - :ivar name: Name of the deployment. Required. + :ivar name: The name of the function to be called. Required. :vartype name: str - :ivar type: The type of the deployment. Required. Model deployment. - :vartype type: str or ~azure.ai.projects.models.MODEL_DEPLOYMENT - :ivar model_name: Publisher-specific name of the deployed model. Required. - :vartype model_name: str - :ivar model_version: Publisher-specific version of the deployed model. Required. - :vartype model_version: str - :ivar model_publisher: Name of the deployed model's publisher. Required. - :vartype model_publisher: str - :ivar capabilities: Capabilities of deployed model. Required. - :vartype capabilities: dict[str, str] - :ivar sku: Sku of the model deployment. Required. - :vartype sku: ~azure.ai.projects.models.ModelDeploymentSku - :ivar connection_name: Name of the connection the deployment comes from. - :vartype connection_name: str + :ivar description: A description of what the function does, used by the model to choose when + and how to call the function. + :vartype description: str + :ivar spec: The openapi function shape, described as a JSON Schema object. Required. + :vartype spec: dict[str, any] + :ivar auth: Open API authentication details. Required. + :vartype auth: ~azure.ai.projects.models.OpenApiAuthDetails + :ivar default_params: List of OpenAPI spec parameters that will use user-provided defaults. + :vartype default_params: list[str] + :ivar functions: List of function definitions used by OpenApi tool. + :vartype functions: list[~azure.ai.projects.models.OpenApiFunctionDefinitionFunction] """ - type: Literal[DeploymentType.MODEL_DEPLOYMENT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the deployment. Required. Model deployment.""" - model_name: str = rest_field(name="modelName", visibility=["read"]) - """Publisher-specific name of the deployed model. Required.""" - model_version: str = rest_field(name="modelVersion", visibility=["read"]) - """Publisher-specific version of the deployed model. Required.""" - model_publisher: str = rest_field(name="modelPublisher", visibility=["read"]) - """Name of the deployed model's publisher. Required.""" - capabilities: dict[str, str] = rest_field(visibility=["read"]) - """Capabilities of deployed model. Required.""" - sku: "_models.ModelDeploymentSku" = rest_field(visibility=["read"]) - """Sku of the model deployment. Required.""" - connection_name: Optional[str] = rest_field(name="connectionName", visibility=["read"]) - """Name of the connection the deployment comes from.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The name of the function to be called. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A description of what the function does, used by the model to choose when and how to call the + function.""" + spec: dict[str, Any] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The openapi function shape, described as a JSON Schema object. Required.""" + auth: "_models.OpenApiAuthDetails" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Open API authentication details. Required.""" + default_params: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """List of OpenAPI spec parameters that will use user-provided defaults.""" + functions: Optional[list["_models.OpenApiFunctionDefinitionFunction"]] = rest_field(visibility=["read"]) + """List of function definitions used by OpenApi tool.""" @overload def __init__( self, + *, + name: str, + spec: dict[str, Any], + auth: "_models.OpenApiAuthDetails", + description: Optional[str] = None, + default_params: Optional[list[str]] = None, ) -> None: ... @overload @@ -8464,44 +10406,36 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = DeploymentType.MODEL_DEPLOYMENT # type: ignore -class ModelDeploymentSku(_Model): - """Sku information. +class OpenApiFunctionDefinitionFunction(_Model): + """OpenApiFunctionDefinitionFunction. - :ivar capacity: Sku capacity. Required. - :vartype capacity: int - :ivar family: Sku family. Required. - :vartype family: str - :ivar name: Sku name. Required. + :ivar name: The name of the function to be called. Required. :vartype name: str - :ivar size: Sku size. Required. - :vartype size: str - :ivar tier: Sku tier. Required. - :vartype tier: str + :ivar description: A description of what the function does, used by the model to choose when + and how to call the function. + :vartype description: str + :ivar parameters: The parameters the functions accepts, described as a JSON Schema object. + Required. + :vartype parameters: dict[str, any] """ - capacity: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Sku capacity. Required.""" - family: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Sku family. Required.""" name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Sku name. Required.""" - size: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Sku size. Required.""" - tier: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Sku tier. Required.""" + """The name of the function to be called. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A description of what the function does, used by the model to choose when and how to call the + function.""" + parameters: dict[str, Any] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The parameters the functions accepts, described as a JSON Schema object. Required.""" @overload def __init__( self, *, - capacity: int, - family: str, name: str, - size: str, - tier: str, + parameters: dict[str, Any], + description: Optional[str] = None, ) -> None: ... @overload @@ -8515,37 +10449,27 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ModelSamplingParams(_Model): - """Represents a set of parameters used to control the sampling behavior of a language model during - text generation. +class OpenApiManagedAuthDetails(OpenApiAuthDetails, discriminator="managed_identity"): + """Security details for OpenApi managed_identity authentication. - :ivar temperature: The temperature parameter for sampling. Defaults to 1.0. - :vartype temperature: float - :ivar top_p: The top-p parameter for nucleus sampling. Defaults to 1.0. - :vartype top_p: float - :ivar seed: The random seed for reproducibility. Defaults to 42. - :vartype seed: int - :ivar max_completion_tokens: The maximum number of tokens allowed in the completion. - :vartype max_completion_tokens: int + :ivar type: The object type, which is always 'managed_identity'. Required. MANAGED_IDENTITY. + :vartype type: str or ~azure.ai.projects.models.MANAGED_IDENTITY + :ivar security_scheme: Connection auth security details. Required. + :vartype security_scheme: ~azure.ai.projects.models.OpenApiManagedSecurityScheme """ - temperature: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The temperature parameter for sampling. Defaults to 1.0.""" - top_p: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The top-p parameter for nucleus sampling. Defaults to 1.0.""" - seed: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The random seed for reproducibility. Defaults to 42.""" - max_completion_tokens: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The maximum number of tokens allowed in the completion.""" + type: Literal[OpenApiAuthType.MANAGED_IDENTITY] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The object type, which is always 'managed_identity'. Required. MANAGED_IDENTITY.""" + security_scheme: "_models.OpenApiManagedSecurityScheme" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Connection auth security details. Required.""" @overload def __init__( self, *, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - seed: Optional[int] = None, - max_completion_tokens: Optional[int] = None, + security_scheme: "_models.OpenApiManagedSecurityScheme", ) -> None: ... @overload @@ -8557,29 +10481,24 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) + self.type = OpenApiAuthType.MANAGED_IDENTITY # type: ignore -class MonthlyRecurrenceSchedule(RecurrenceSchedule, discriminator="Monthly"): - """Monthly recurrence schedule. +class OpenApiManagedSecurityScheme(_Model): + """Security scheme for OpenApi managed_identity authentication. - :ivar type: Monthly recurrence type. Required. Monthly recurrence pattern. - :vartype type: str or ~azure.ai.projects.models.MONTHLY - :ivar days_of_month: Days of the month for the recurrence schedule. Required. - :vartype days_of_month: list[int] + :ivar audience: Authentication scope for managed_identity auth type. Required. + :vartype audience: str """ - type: Literal[RecurrenceType.MONTHLY] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Monthly recurrence type. Required. Monthly recurrence pattern.""" - days_of_month: list[int] = rest_field( - name="daysOfMonth", visibility=["read", "create", "update", "delete", "query"] - ) - """Days of the month for the recurrence schedule. Required.""" + audience: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Authentication scope for managed_identity auth type. Required.""" @overload def __init__( self, *, - days_of_month: list[int], + audience: str, ) -> None: ... @overload @@ -8591,22 +10510,30 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = RecurrenceType.MONTHLY # type: ignore -class NoAuthenticationCredentials(BaseCredentials, discriminator="None"): - """Credentials that do not require authentication. +class OpenApiProjectConnectionAuthDetails(OpenApiAuthDetails, discriminator="project_connection"): + """Security details for OpenApi project connection authentication. - :ivar type: The credential type. Required. No credential. - :vartype type: str or ~azure.ai.projects.models.NONE + :ivar type: The object type, which is always 'project_connection'. Required. + PROJECT_CONNECTION. + :vartype type: str or ~azure.ai.projects.models.PROJECT_CONNECTION + :ivar security_scheme: Project connection auth security details. Required. + :vartype security_scheme: ~azure.ai.projects.models.OpenApiProjectConnectionSecurityScheme """ - type: Literal[CredentialType.NONE] = rest_discriminator(name="type", visibility=["read"]) # type: ignore - """The credential type. Required. No credential.""" + type: Literal[OpenApiAuthType.PROJECT_CONNECTION] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The object type, which is always 'project_connection'. Required. PROJECT_CONNECTION.""" + security_scheme: "_models.OpenApiProjectConnectionSecurityScheme" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Project connection auth security details. Required.""" @overload def __init__( self, + *, + security_scheme: "_models.OpenApiProjectConnectionSecurityScheme", ) -> None: ... @overload @@ -8618,35 +10545,24 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = CredentialType.NONE # type: ignore + self.type = OpenApiAuthType.PROJECT_CONNECTION # type: ignore -class OneTimeTrigger(Trigger, discriminator="OneTime"): - """One-time trigger. +class OpenApiProjectConnectionSecurityScheme(_Model): + """Security scheme for OpenApi managed_identity authentication. - :ivar type: Required. One-time trigger. - :vartype type: str or ~azure.ai.projects.models.ONE_TIME - :ivar trigger_at: Date and time for the one-time trigger in ISO 8601 format. Required. - :vartype trigger_at: ~datetime.datetime - :ivar time_zone: Time zone for the one-time trigger. - :vartype time_zone: str + :ivar project_connection_id: Project connection id for Project Connection auth type. Required. + :vartype project_connection_id: str """ - type: Literal[TriggerType.ONE_TIME] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. One-time trigger.""" - trigger_at: datetime.datetime = rest_field( - name="triggerAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" - ) - """Date and time for the one-time trigger in ISO 8601 format. Required.""" - time_zone: Optional[str] = rest_field(name="timeZone", visibility=["read", "create", "update", "delete", "query"]) - """Time zone for the one-time trigger.""" + project_connection_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Project connection id for Project Connection auth type. Required.""" @overload def __init__( self, *, - trigger_at: datetime.datetime, - time_zone: Optional[str] = None, + project_connection_id: str, ) -> None: ... @overload @@ -8658,30 +10574,40 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = TriggerType.ONE_TIME # type: ignore - -class OpenApiAuthDetails(_Model): - """authentication details for OpenApiFunctionDefinition. - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - OpenApiAnonymousAuthDetails, OpenApiManagedAuthDetails, OpenApiProjectConnectionAuthDetails +class OpenApiTool(Tool, discriminator="openapi"): + """The input definition information for an OpenAPI tool as used to configure an agent. - :ivar type: The type of authentication, must be anonymous/project_connection/managed_identity. - Required. Known values are: "anonymous", "project_connection", and "managed_identity". - :vartype type: str or ~azure.ai.projects.models.OpenApiAuthType + :ivar type: The object type, which is always 'openapi'. Required. OPENAPI. + :vartype type: str or ~azure.ai.projects.models.OPENAPI + :ivar openapi: The openapi function definition. Required. + :vartype openapi: ~azure.ai.projects.models.OpenApiFunctionDefinition + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] """ - __mapping__: dict[str, _Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The type of authentication, must be anonymous/project_connection/managed_identity. Required. - Known values are: \"anonymous\", \"project_connection\", and \"managed_identity\".""" + type: Literal[ToolType.OPENAPI] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The object type, which is always 'openapi'. Required. OPENAPI.""" + openapi: "_models.OpenApiFunctionDefinition" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The openapi function definition. Required.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" @overload def __init__( self, *, - type: str, + openapi: "_models.OpenApiFunctionDefinition", + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, ) -> None: ... @overload @@ -8693,21 +10619,52 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) + self.type = ToolType.OPENAPI # type: ignore -class OpenApiAnonymousAuthDetails(OpenApiAuthDetails, discriminator="anonymous"): - """Security details for OpenApi anonymous authentication. +class OptimizationAgentDefinition(_Model): + """The agent definition being optimized. Identifies the Foundry agent and optional configuration + overrides. - :ivar type: The object type, which is always 'anonymous'. Required. ANONYMOUS. - :vartype type: str or ~azure.ai.projects.models.ANONYMOUS + :ivar agent_name: Registered Foundry agent name. Required — bare-model mode is not supported. + Required. + :vartype agent_name: str + :ivar agent_version: Pinned agent version. Defaults to latest if omitted. + :vartype agent_version: str + :ivar model: Model deployment name (e.g., 'gpt-4o'). Optional when agent_name is set — the + agent definition provides the model. + :vartype model: str + :ivar system_prompt: System prompt / instructions override. When set, used as the baseline + instructions for the agent. + :vartype system_prompt: str + :ivar skills: Optional named skills the optimizer may tune. Tool descriptions and parameters. + :vartype skills: list[~azure.ai.projects.models.OptimizationAgentSkill] """ - type: Literal[OpenApiAuthType.ANONYMOUS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'anonymous'. Required. ANONYMOUS.""" + agent_name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Registered Foundry agent name. Required — bare-model mode is not supported. Required.""" + agent_version: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Pinned agent version. Defaults to latest if omitted.""" + model: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Model deployment name (e.g., 'gpt-4o'). Optional when agent_name is set — the agent definition + provides the model.""" + system_prompt: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """System prompt / instructions override. When set, used as the baseline instructions for the + agent.""" + skills: Optional[list["_models.OptimizationAgentSkill"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Optional named skills the optimizer may tune. Tool descriptions and parameters.""" @overload def __init__( self, + *, + agent_name: str, + agent_version: Optional[str] = None, + model: Optional[str] = None, + system_prompt: Optional[str] = None, + skills: Optional[list["_models.OptimizationAgentSkill"]] = None, ) -> None: ... @overload @@ -8719,50 +10676,28 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = OpenApiAuthType.ANONYMOUS # type: ignore -class OpenApiFunctionDefinition(_Model): - """The input definition information for an openapi function. +class OptimizationAgentSkill(_Model): + """A named skill on the agent that the optimizer may tune. - :ivar name: The name of the function to be called. Required. + :ivar name: Skill name (matches the tool name on the agent). Required. :vartype name: str - :ivar description: A description of what the function does, used by the model to choose when - and how to call the function. + :ivar description: Free-form description used as the seed when tuning skill descriptions. :vartype description: str - :ivar spec: The openapi function shape, described as a JSON Schema object. Required. - :vartype spec: dict[str, any] - :ivar auth: Open API authentication details. Required. - :vartype auth: ~azure.ai.projects.models.OpenApiAuthDetails - :ivar default_params: List of OpenAPI spec parameters that will use user-provided defaults. - :vartype default_params: list[str] - :ivar functions: List of function definitions used by OpenApi tool. - :vartype functions: list[~azure.ai.projects.models.OpenApiFunctionDefinitionFunction] """ name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the function to be called. Required.""" + """Skill name (matches the tool name on the agent). Required.""" description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A description of what the function does, used by the model to choose when and how to call the - function.""" - spec: dict[str, Any] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The openapi function shape, described as a JSON Schema object. Required.""" - auth: "_models.OpenApiAuthDetails" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Open API authentication details. Required.""" - default_params: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """List of OpenAPI spec parameters that will use user-provided defaults.""" - functions: Optional[list["_models.OpenApiFunctionDefinitionFunction"]] = rest_field(visibility=["read"]) - """List of function definitions used by OpenApi tool.""" + """Free-form description used as the seed when tuning skill descriptions.""" @overload def __init__( self, *, name: str, - spec: dict[str, Any], - auth: "_models.OpenApiAuthDetails", description: Optional[str] = None, - default_params: Optional[list[str]] = None, ) -> None: ... @overload @@ -8776,34 +10711,108 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class OpenApiFunctionDefinitionFunction(_Model): - """OpenApiFunctionDefinitionFunction. +class OptimizationCandidate(_Model): + """Aggregated evaluation result for a single candidate agent configuration across all tasks. - :ivar name: The name of the function to be called. Required. + :ivar candidate_id: Server-assigned candidate identifier. Use with ``GET /candidates/{id}`` + sub-endpoints. + :vartype candidate_id: str + :ivar name: Display name of the candidate (e.g., 'baseline', 'instruction-v2'). Required. :vartype name: str - :ivar description: A description of what the function does, used by the model to choose when - and how to call the function. - :vartype description: str - :ivar parameters: The parameters the functions accepts, described as a JSON Schema object. + :ivar config: The agent configuration that produced this candidate. Required. + :vartype config: ~azure.ai.projects.models.OptimizationAgentDefinition + :ivar mutations: What was mutated from the baseline (e.g., {instructions: 'new prompt'}). Required. - :vartype parameters: dict[str, any] + :vartype mutations: dict[str, any] + :ivar rationale: Strategy rationale — why this candidate was generated. Required. + :vartype rationale: str + :ivar avg_score: Average composite score across all tasks. Required. + :vartype avg_score: float + :ivar avg_tokens: Average token usage across all tasks. Required. + :vartype avg_tokens: float + :ivar pass_rate: Fraction of tasks that met the pass threshold. Required. + :vartype pass_rate: float + :ivar task_scores: Individual task-level scores. Required. + :vartype task_scores: list[~azure.ai.projects.models.OptimizationTaskResult] + :ivar is_pareto_optimal: Whether this candidate is on the Pareto frontier (score vs cost). + Required. + :vartype is_pareto_optimal: bool + :ivar sample_avg_score: Average score from sampled evaluation (null if full dataset was used). + :vartype sample_avg_score: float + :ivar sample_size: Number of tasks in the sample (null if full dataset was used). + :vartype sample_size: int + :ivar evaluation_type: 'sample' if scored on a subset, 'full' if re-evaluated on the full + dataset. + :vartype evaluation_type: str + :ivar strategy: Identifies the strategy that produced this candidate. Known values are: + "instruction", "model", and "skill". + :vartype strategy: str or ~azure.ai.projects.models.OptimizationStrategy + :ivar eval_id: Foundry evaluation identifier used to score this candidate. + :vartype eval_id: str + :ivar eval_run_id: Foundry evaluation run identifier for this candidate's scoring run. + :vartype eval_run_id: str """ + candidate_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Server-assigned candidate identifier. Use with ``GET /candidates/{id}`` sub-endpoints.""" name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the function to be called. Required.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A description of what the function does, used by the model to choose when and how to call the - function.""" - parameters: dict[str, Any] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The parameters the functions accepts, described as a JSON Schema object. Required.""" + """Display name of the candidate (e.g., 'baseline', 'instruction-v2'). Required.""" + config: "_models.OptimizationAgentDefinition" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The agent configuration that produced this candidate. Required.""" + mutations: dict[str, Any] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """What was mutated from the baseline (e.g., {instructions: 'new prompt'}). Required.""" + rationale: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Strategy rationale — why this candidate was generated. Required.""" + avg_score: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Average composite score across all tasks. Required.""" + avg_tokens: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Average token usage across all tasks. Required.""" + pass_rate: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Fraction of tasks that met the pass threshold. Required.""" + task_scores: list["_models.OptimizationTaskResult"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Individual task-level scores. Required.""" + is_pareto_optimal: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Whether this candidate is on the Pareto frontier (score vs cost). Required.""" + sample_avg_score: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Average score from sampled evaluation (null if full dataset was used).""" + sample_size: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Number of tasks in the sample (null if full dataset was used).""" + evaluation_type: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """'sample' if scored on a subset, 'full' if re-evaluated on the full dataset.""" + strategy: Optional[Union[str, "_models.OptimizationStrategy"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Identifies the strategy that produced this candidate. Known values are: \"instruction\", + \"model\", and \"skill\".""" + eval_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Foundry evaluation identifier used to score this candidate.""" + eval_run_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Foundry evaluation run identifier for this candidate's scoring run.""" @overload def __init__( self, *, name: str, - parameters: dict[str, Any], - description: Optional[str] = None, + config: "_models.OptimizationAgentDefinition", + mutations: dict[str, Any], + rationale: str, + avg_score: float, + avg_tokens: float, + pass_rate: float, + task_scores: list["_models.OptimizationTaskResult"], + is_pareto_optimal: bool, + candidate_id: Optional[str] = None, + sample_avg_score: Optional[float] = None, + sample_size: Optional[int] = None, + evaluation_type: Optional[str] = None, + strategy: Optional[Union[str, "_models.OptimizationStrategy"]] = None, + eval_id: Optional[str] = None, + eval_run_id: Optional[str] = None, ) -> None: ... @overload @@ -8817,27 +10826,55 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class OpenApiManagedAuthDetails(OpenApiAuthDetails, discriminator="managed_identity"): - """Security details for OpenApi managed_identity authentication. +class OptimizationJob(_Model): + """Agent optimization job resource — a long-running job that optimizes an agent's configuration + (instructions, model, skills) to maximize evaluation scores. On success, the result contains + scored candidates. - :ivar type: The object type, which is always 'managed_identity'. Required. MANAGED_IDENTITY. - :vartype type: str or ~azure.ai.projects.models.MANAGED_IDENTITY - :ivar security_scheme: Connection auth security details. Required. - :vartype security_scheme: ~azure.ai.projects.models.OpenApiManagedSecurityScheme + :ivar id: Server-assigned unique identifier. Required. + :vartype id: str + :ivar inputs: Caller-supplied inputs. + :vartype inputs: ~azure.ai.projects.models.OptimizationJobInputs + :ivar result: Result produced on success. + :vartype result: ~azure.ai.projects.models.OptimizationJobResult + :ivar status: Current lifecycle status. Required. Known values are: "queued", "in_progress", + "succeeded", "failed", and "cancelled". + :vartype status: str or ~azure.ai.projects.models.JobStatus + :ivar error: Error details — populated only on failure. + :vartype error: ~azure.ai.projects.models.ApiError + :ivar created_at: The timestamp when the job was created, represented in Unix time. Required. + :vartype created_at: ~datetime.datetime + :ivar updated_at: The timestamp when the job was last updated, represented in Unix time. + :vartype updated_at: ~datetime.datetime + :ivar progress: Progress while in flight. Absent in terminal states. + :vartype progress: ~azure.ai.projects.models.OptimizationJobProgress """ - type: Literal[OpenApiAuthType.MANAGED_IDENTITY] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'managed_identity'. Required. MANAGED_IDENTITY.""" - security_scheme: "_models.OpenApiManagedSecurityScheme" = rest_field( + id: str = rest_field(visibility=["read"]) + """Server-assigned unique identifier. Required.""" + inputs: Optional["_models.OptimizationJobInputs"] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) - """Connection auth security details. Required.""" + """Caller-supplied inputs.""" + result: Optional["_models.OptimizationJobResult"] = rest_field(visibility=["read"]) + """Result produced on success.""" + status: Union[str, "_models.JobStatus"] = rest_field(visibility=["read"]) + """Current lifecycle status. Required. Known values are: \"queued\", \"in_progress\", + \"succeeded\", \"failed\", and \"cancelled\".""" + error: Optional["_models.ApiError"] = rest_field(visibility=["read"]) + """Error details — populated only on failure.""" + created_at: datetime.datetime = rest_field(visibility=["read"], format="unix-timestamp") + """The timestamp when the job was created, represented in Unix time. Required.""" + updated_at: Optional[datetime.datetime] = rest_field(visibility=["read"], format="unix-timestamp") + """The timestamp when the job was last updated, represented in Unix time.""" + progress: Optional["_models.OptimizationJobProgress"] = rest_field(visibility=["read"]) + """Progress while in flight. Absent in terminal states.""" @overload def __init__( self, *, - security_scheme: "_models.OpenApiManagedSecurityScheme", + inputs: Optional["_models.OptimizationJobInputs"] = None, ) -> None: ... @overload @@ -8849,24 +10886,70 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = OpenApiAuthType.MANAGED_IDENTITY # type: ignore -class OpenApiManagedSecurityScheme(_Model): - """Security scheme for OpenApi managed_identity authentication. +class OptimizationJobInputs(_Model): + """Caller-supplied inputs for an optimization job. - :ivar audience: Authentication scope for managed_identity auth type. Required. - :vartype audience: str + :ivar agent: The agent (and pinned version) being optimized. Required. + :vartype agent: ~azure.ai.projects.models.OptimizationAgentDefinition + :ivar dataset: Inline evaluation dataset. Mutually exclusive with ``train_dataset_reference``. + :vartype dataset: list[~azure.ai.projects.models.DatasetItem] + :ivar train_dataset_reference: Reference to a registered training dataset. Mutually exclusive + with ``dataset``. + :vartype train_dataset_reference: ~azure.ai.projects.models.DatasetRef + :ivar validation_dataset_reference: Optional held-out validation dataset for measuring + generalization of the final candidate. + :vartype validation_dataset_reference: ~azure.ai.projects.models.DatasetRef + :ivar evaluators: Job-level evaluators (referenced by ``name``). Per-task ``criteria`` may + override. Default: ['task_adherence']. + :vartype evaluators: list[str] + :ivar criteria: Job-level evaluation criteria. Applied to all tasks unless overridden by + per-task ``criteria``. + :vartype criteria: list[~azure.ai.projects.models.EvaluationCriterion] + :ivar options: Tuning knobs and run-mode. + :vartype options: ~azure.ai.projects.models.OptimizationOptions """ - audience: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Authentication scope for managed_identity auth type. Required.""" + agent: "_models.OptimizationAgentDefinition" = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The agent (and pinned version) being optimized. Required.""" + dataset: Optional[list["_models.DatasetItem"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Inline evaluation dataset. Mutually exclusive with ``train_dataset_reference``.""" + train_dataset_reference: Optional["_models.DatasetRef"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Reference to a registered training dataset. Mutually exclusive with ``dataset``.""" + validation_dataset_reference: Optional["_models.DatasetRef"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Optional held-out validation dataset for measuring generalization of the final candidate.""" + evaluators: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Job-level evaluators (referenced by ``name``). Per-task ``criteria`` may override. Default: + ['task_adherence'].""" + criteria: Optional[list["_models.EvaluationCriterion"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Job-level evaluation criteria. Applied to all tasks unless overridden by per-task ``criteria``.""" + options: Optional["_models.OptimizationOptions"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Tuning knobs and run-mode.""" @overload def __init__( self, *, - audience: str, + agent: "_models.OptimizationAgentDefinition", + dataset: Optional[list["_models.DatasetItem"]] = None, + train_dataset_reference: Optional["_models.DatasetRef"] = None, + validation_dataset_reference: Optional["_models.DatasetRef"] = None, + evaluators: Optional[list[str]] = None, + criteria: Optional[list["_models.EvaluationCriterion"]] = None, + options: Optional["_models.OptimizationOptions"] = None, ) -> None: ... @overload @@ -8880,28 +10963,50 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class OpenApiProjectConnectionAuthDetails(OpenApiAuthDetails, discriminator="project_connection"): - """Security details for OpenApi project connection authentication. +class OptimizationJobProgress(_Model): + """In-flight progress; only populated while status is ``queued`` or ``in_progress``. - :ivar type: The object type, which is always 'project_connection'. Required. - PROJECT_CONNECTION. - :vartype type: str or ~azure.ai.projects.models.PROJECT_CONNECTION - :ivar security_scheme: Project connection auth security details. Required. - :vartype security_scheme: ~azure.ai.projects.models.OpenApiProjectConnectionSecurityScheme + :ivar current_strategy: Strategy currently being explored. Required. Known values are: + "instruction", "model", and "skill". + :vartype current_strategy: str or ~azure.ai.projects.models.OptimizationStrategy + :ivar current_iteration: 1-based current iteration index. Required. + :vartype current_iteration: int + :ivar tasks_completed: Tasks evaluated so far this iteration. Required. + :vartype tasks_completed: int + :ivar tasks_total: Total tasks scheduled this iteration. Required. + :vartype tasks_total: int + :ivar best_score: Best score observed so far across all candidates. Required. + :vartype best_score: float + :ivar elapsed_seconds: Wall-clock time elapsed since the job began executing. Required. + :vartype elapsed_seconds: float """ - type: Literal[OpenApiAuthType.PROJECT_CONNECTION] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'project_connection'. Required. PROJECT_CONNECTION.""" - security_scheme: "_models.OpenApiProjectConnectionSecurityScheme" = rest_field( + current_strategy: Union[str, "_models.OptimizationStrategy"] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) - """Project connection auth security details. Required.""" + """Strategy currently being explored. Required. Known values are: \"instruction\", \"model\", and + \"skill\".""" + current_iteration: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """1-based current iteration index. Required.""" + tasks_completed: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Tasks evaluated so far this iteration. Required.""" + tasks_total: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Total tasks scheduled this iteration. Required.""" + best_score: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Best score observed so far across all candidates. Required.""" + elapsed_seconds: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Wall-clock time elapsed since the job began executing. Required.""" @overload def __init__( self, *, - security_scheme: "_models.OpenApiProjectConnectionSecurityScheme", + current_strategy: Union[str, "_models.OptimizationStrategy"], + current_iteration: int, + tasks_completed: int, + tasks_total: int, + best_score: float, + elapsed_seconds: float, ) -> None: ... @overload @@ -8913,24 +11018,80 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = OpenApiAuthType.PROJECT_CONNECTION # type: ignore -class OpenApiProjectConnectionSecurityScheme(_Model): - """Security scheme for OpenApi managed_identity authentication. +class OptimizationJobResult(_Model): + """Terminal-state result body. Populated when ``status`` is ``succeeded`` or ``failed``. - :ivar project_connection_id: Project connection id for Project Connection auth type. Required. - :vartype project_connection_id: str + :ivar baseline: Evaluation scores for the original (un-optimized) agent configuration. + :vartype baseline: ~azure.ai.projects.models.OptimizationCandidate + :ivar best: The highest-scoring candidate found during optimization. + :vartype best: ~azure.ai.projects.models.OptimizationCandidate + :ivar candidates: All evaluated candidates including baseline. + :vartype candidates: list[~azure.ai.projects.models.OptimizationCandidate] + :ivar pareto_frontier: Candidates on the Pareto frontier (maximize score, minimize cost). + :vartype pareto_frontier: list[~azure.ai.projects.models.OptimizationCandidate] + :ivar validation_score: Score of the best candidate on the held-out validation dataset. Null + when no validation dataset was provided. + :vartype validation_score: ~azure.ai.projects.models.OptimizationCandidate + :ivar options: The options used for this optimization run. + :vartype options: ~azure.ai.projects.models.OptimizationOptions + :ivar sample_size: Number of tasks sampled during optimization iterations (null if sampling was + not used). + :vartype sample_size: int + :ivar warnings: Non-fatal warnings from the optimization run (e.g., strategy failures that were + skipped). + :vartype warnings: list[str] + :ivar all_strategies_failed: True when all optimization strategies failed — only the baseline + was evaluated. + :vartype all_strategies_failed: bool """ - project_connection_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Project connection id for Project Connection auth type. Required.""" + baseline: Optional["_models.OptimizationCandidate"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Evaluation scores for the original (un-optimized) agent configuration.""" + best: Optional["_models.OptimizationCandidate"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The highest-scoring candidate found during optimization.""" + candidates: Optional[list["_models.OptimizationCandidate"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """All evaluated candidates including baseline.""" + pareto_frontier: Optional[list["_models.OptimizationCandidate"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Candidates on the Pareto frontier (maximize score, minimize cost).""" + validation_score: Optional["_models.OptimizationCandidate"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Score of the best candidate on the held-out validation dataset. Null when no validation dataset + was provided.""" + options: Optional["_models.OptimizationOptions"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The options used for this optimization run.""" + sample_size: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Number of tasks sampled during optimization iterations (null if sampling was not used).""" + warnings: Optional[list[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Non-fatal warnings from the optimization run (e.g., strategy failures that were skipped).""" + all_strategies_failed: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """True when all optimization strategies failed — only the baseline was evaluated.""" @overload def __init__( self, *, - project_connection_id: str, + baseline: Optional["_models.OptimizationCandidate"] = None, + best: Optional["_models.OptimizationCandidate"] = None, + candidates: Optional[list["_models.OptimizationCandidate"]] = None, + pareto_frontier: Optional[list["_models.OptimizationCandidate"]] = None, + validation_score: Optional["_models.OptimizationCandidate"] = None, + options: Optional["_models.OptimizationOptions"] = None, + sample_size: Optional[int] = None, + warnings: Optional[list[str]] = None, + all_strategies_failed: Optional[bool] = None, ) -> None: ... @overload @@ -8944,27 +11105,173 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class OpenApiTool(Tool, discriminator="openapi"): - """The input definition information for an OpenAPI tool as used to configure an agent. - - :ivar type: The object type, which is always 'openapi'. Required. OPENAPI. - :vartype type: str or ~azure.ai.projects.models.OPENAPI - :ivar openapi: The openapi function definition. Required. - :vartype openapi: ~azure.ai.projects.models.OpenApiFunctionDefinition - """ +class OptimizationOptions(_Model): + """Tuning knobs and run-mode for an optimization job. - type: Literal[ToolType.OPENAPI] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'openapi'. Required. OPENAPI.""" - openapi: "_models.OpenApiFunctionDefinition" = rest_field( + :ivar strategies: Strategies to apply this run. Default: ['instruction']. + :vartype strategies: list[str or ~azure.ai.projects.models.OptimizationStrategy] + :ivar budget: Total candidate generation budget (number of candidates explored). Default: 10. + :vartype budget: int + :ivar max_iterations: Maximum optimization iterations per strategy. Default: 5. + :vartype max_iterations: int + :ivar tasks_per_iteration: Tasks sampled per iteration (mutation step input). Default: + service-decided (auto-computed). + :vartype tasks_per_iteration: int + :ivar max_reflection_tasks: Maximum tasks fed into the reflective-mutation LLM per iteration. + Default: 5. + :vartype max_reflection_tasks: int + :ivar min_improvement: Minimum score improvement between iterations to continue (plateau + detection). Default: 0.005. + :vartype min_improvement: float + :ivar pass_threshold: Composite score threshold for a task to be considered passing. Default: + 0.5. + :vartype pass_threshold: float + :ivar improvement_threshold: Target average score at which optimization stops early (quality + ceiling). Default: 0.95. + :vartype improvement_threshold: float + :ivar mode: Run mode. "optimize" + :vartype mode: str or ~azure.ai.projects.models.OptimizationMode + :ivar eval_model: Foundry deployment name to use as the LLM-as-judge evaluation model. + Required. + :vartype eval_model: str + :ivar reflection_model: Optional model deployment for strategy reflection (instruction + rewriting, skill generation). Falls back to ``eval_model`` if unset. + :vartype reflection_model: str + :ivar task_timeout_seconds: Per-task timeout for agent execution. Default: 300 seconds (5 + minutes). + :vartype task_timeout_seconds: int + :ivar keep_versions: If true, retain temporary candidate-evaluation agent versions for + inspection. Default: false. + :vartype keep_versions: bool + """ + + strategies: Optional[list[Union[str, "_models.OptimizationStrategy"]]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) - """The openapi function definition. Required.""" + """Strategies to apply this run. Default: ['instruction'].""" + budget: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Total candidate generation budget (number of candidates explored). Default: 10.""" + max_iterations: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Maximum optimization iterations per strategy. Default: 5.""" + tasks_per_iteration: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Tasks sampled per iteration (mutation step input). Default: service-decided (auto-computed).""" + max_reflection_tasks: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Maximum tasks fed into the reflective-mutation LLM per iteration. Default: 5.""" + min_improvement: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Minimum score improvement between iterations to continue (plateau detection). Default: 0.005.""" + pass_threshold: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Composite score threshold for a task to be considered passing. Default: 0.5.""" + improvement_threshold: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Target average score at which optimization stops early (quality ceiling). Default: 0.95.""" + mode: Optional[Union[str, "_models.OptimizationMode"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Run mode. \"optimize\"""" + eval_model: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Foundry deployment name to use as the LLM-as-judge evaluation model. Required.""" + reflection_model: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Optional model deployment for strategy reflection (instruction rewriting, skill generation). + Falls back to ``eval_model`` if unset.""" + task_timeout_seconds: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Per-task timeout for agent execution. Default: 300 seconds (5 minutes).""" + keep_versions: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """If true, retain temporary candidate-evaluation agent versions for inspection. Default: false.""" @overload def __init__( self, *, - openapi: "_models.OpenApiFunctionDefinition", + strategies: Optional[list[Union[str, "_models.OptimizationStrategy"]]] = None, + budget: Optional[int] = None, + max_iterations: Optional[int] = None, + tasks_per_iteration: Optional[int] = None, + max_reflection_tasks: Optional[int] = None, + min_improvement: Optional[float] = None, + pass_threshold: Optional[float] = None, + improvement_threshold: Optional[float] = None, + mode: Optional[Union[str, "_models.OptimizationMode"]] = None, + eval_model: Optional[str] = None, + reflection_model: Optional[str] = None, + task_timeout_seconds: Optional[int] = None, + keep_versions: Optional[bool] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class OptimizationTaskResult(_Model): + """Per-task evaluation result for a single candidate. + + :ivar task_name: Task name (from the dataset). Required. + :vartype task_name: str + :ivar query: The user query / input for the task. + :vartype query: str + :ivar scores: Per-evaluator scores keyed by evaluator name. Required. + :vartype scores: dict[str, float] + :ivar composite_score: Composite score combining all evaluator scores. Required. + :vartype composite_score: float + :ivar tokens: Total tokens consumed during the agent run for this task. Required. + :vartype tokens: int + :ivar duration_seconds: Wall-clock seconds for this task's agent execution. Required. + :vartype duration_seconds: float + :ivar passed: Whether the task met the pass threshold. Required. + :vartype passed: bool + :ivar error_message: Error message if the task failed during execution. + :vartype error_message: str + :ivar rationales: Per-evaluator reasoning keyed by evaluator name. + :vartype rationales: dict[str, str] + :ivar response: Raw agent response text. + :vartype response: str + :ivar run_id: Identifier of the agent run that produced this result. + :vartype run_id: str + """ + + task_name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Task name (from the dataset). Required.""" + query: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The user query / input for the task.""" + scores: dict[str, float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Per-evaluator scores keyed by evaluator name. Required.""" + composite_score: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Composite score combining all evaluator scores. Required.""" + tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Total tokens consumed during the agent run for this task. Required.""" + duration_seconds: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Wall-clock seconds for this task's agent execution. Required.""" + passed: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Whether the task met the pass threshold. Required.""" + error_message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Error message if the task failed during execution.""" + rationales: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Per-evaluator reasoning keyed by evaluator name.""" + response: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Raw agent response text.""" + run_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Identifier of the agent run that produced this result.""" + + @overload + def __init__( + self, + *, + task_name: str, + scores: dict[str, float], + composite_score: float, + tokens: int, + duration_seconds: float, + passed: bool, + query: Optional[str] = None, + error_message: Optional[str] = None, + rationales: Optional[dict[str, str]] = None, + response: Optional[str] = None, + run_id: Optional[str] = None, ) -> None: ... @overload @@ -8976,7 +11283,6 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = ToolType.OPENAPI # type: ignore class TelemetryEndpoint(_Model): @@ -9085,8 +11391,8 @@ class PendingUploadRequest(_Model): :ivar connection_name: Azure Storage Account connection name to use for generating temporary SAS token. :vartype connection_name: str - :ivar pending_upload_type: BlobReference is the only supported type. Required. Blob Reference - is the only supported type. + :ivar pending_upload_type: The type of pending upload. Required. Deprecated: the service never + read this value and silently ignored it. Use TemporaryBlobReference instead. :vartype pending_upload_type: str or ~azure.ai.projects.models.BLOB_REFERENCE """ @@ -9101,7 +11407,8 @@ class PendingUploadRequest(_Model): pending_upload_type: Literal[PendingUploadType.BLOB_REFERENCE] = rest_field( name="pendingUploadType", visibility=["read", "create", "update", "delete", "query"] ) - """BlobReference is the only supported type. Required. Blob Reference is the only supported type.""" + """The type of pending upload. Required. Deprecated: the service never read this value and + silently ignored it. Use TemporaryBlobReference instead.""" @overload def __init__( @@ -9133,8 +11440,8 @@ class PendingUploadResult(_Model): :ivar version: Version of asset to be created if user did not specify version when initially creating upload. :vartype version: str - :ivar pending_upload_type: BlobReference is the only supported type. Required. Blob Reference - is the only supported type. + :ivar pending_upload_type: The type of pending upload. Required. Deprecated: the service never + read this value and silently ignored it. Use TemporaryBlobReference instead. :vartype pending_upload_type: str or ~azure.ai.projects.models.BLOB_REFERENCE """ @@ -9151,7 +11458,8 @@ class PendingUploadResult(_Model): pending_upload_type: Literal[PendingUploadType.BLOB_REFERENCE] = rest_field( name="pendingUploadType", visibility=["read", "create", "update", "delete", "query"] ) - """BlobReference is the only supported type. Required. Blob Reference is the only supported type.""" + """The type of pending upload. Required. Deprecated: the service never read this value and + silently ignored it. Use TemporaryBlobReference instead.""" @overload def __init__( @@ -9174,6 +11482,48 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class ProceduralMemoryItem(MemoryItem, discriminator="procedural"): + """A memory item containing a procedure extracted from conversations. + + :ivar memory_id: The unique ID of the memory item. Required. + :vartype memory_id: str + :ivar updated_at: The last update time of the memory item. Required. + :vartype updated_at: ~datetime.datetime + :ivar scope: The namespace that logically groups and isolates memories, such as a user ID. + Required. + :vartype scope: str + :ivar content: The content of the memory. Required. + :vartype content: str + :ivar kind: The kind of the memory item. Required. Routine procedures extracted from + conversations. + :vartype kind: str or ~azure.ai.projects.models.PROCEDURAL + """ + + kind: Literal[MemoryItemKind.PROCEDURAL] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The kind of the memory item. Required. Routine procedures extracted from conversations.""" + + @overload + def __init__( + self, + *, + memory_id: str, + updated_at: datetime.datetime, + scope: str, + content: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.kind = MemoryItemKind.PROCEDURAL # type: ignore + + class PromptAgentDefinition(AgentDefinition, discriminator="prompt"): """The prompt agent definition. @@ -9442,7 +11792,7 @@ class ProtocolVersionRecord(_Model): """A record mapping for a single protocol and its version. :ivar protocol: The protocol type. Required. Known values are: "activity_protocol", - "responses", and "invocations". + "responses", "mcp", and "invocations". :vartype protocol: str or ~azure.ai.projects.models.AgentProtocol :ivar version: The version string for the protocol, e.g. 'v0.1.1'. Required. :vartype version: str @@ -9451,8 +11801,8 @@ class ProtocolVersionRecord(_Model): protocol: Union[str, "_models.AgentProtocol"] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) - """The protocol type. Required. Known values are: \"activity_protocol\", \"responses\", and - \"invocations\".""" + """The protocol type. Required. Known values are: \"activity_protocol\", \"responses\", \"mcp\", + and \"invocations\".""" version: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The version string for the protocol, e.g. 'v0.1.1'. Required.""" @@ -9683,7 +12033,7 @@ class RedTeam(_Model): :ivar status: Status of the red-team. It is set by service and is read-only. :vartype status: str :ivar target: Target configuration for the red-team run. Required. - :vartype target: ~azure.ai.projects.models.TargetConfig + :vartype target: ~azure.ai.projects.models.RedTeamTargetConfig """ name: str = rest_field(name="id", visibility=["read"]) @@ -9718,22 +12068,78 @@ class RedTeam(_Model): removed.""" status: Optional[str] = rest_field(visibility=["read"]) """Status of the red-team. It is set by service and is read-only.""" - target: "_models.TargetConfig" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + target: "_models.RedTeamTargetConfig" = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Target configuration for the red-team run. Required.""" @overload def __init__( self, *, - target: "_models.TargetConfig", - display_name: Optional[str] = None, - num_turns: Optional[int] = None, - attack_strategies: Optional[list[Union[str, "_models.AttackStrategy"]]] = None, - simulation_only: Optional[bool] = None, - risk_categories: Optional[list[Union[str, "_models.RiskCategory"]]] = None, - application_scenario: Optional[str] = None, - tags: Optional[dict[str, str]] = None, - properties: Optional[dict[str, str]] = None, + target: "_models.RedTeamTargetConfig", + display_name: Optional[str] = None, + num_turns: Optional[int] = None, + attack_strategies: Optional[list[Union[str, "_models.AttackStrategy"]]] = None, + simulation_only: Optional[bool] = None, + risk_categories: Optional[list[Union[str, "_models.RiskCategory"]]] = None, + application_scenario: Optional[str] = None, + tags: Optional[dict[str, str]] = None, + properties: Optional[dict[str, 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 ResponseUsageInputTokensDetails(_Model): + """ResponseUsageInputTokensDetails. + + :ivar cached_tokens: Required. + :vartype cached_tokens: int + """ + + cached_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + + @overload + def __init__( + self, + *, + cached_tokens: int, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + + +class ResponseUsageOutputTokensDetails(_Model): + """ResponseUsageOutputTokensDetails. + + :ivar reasoning_tokens: Required. + :vartype reasoning_tokens: int + """ + + reasoning_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Required.""" + + @overload + def __init__( + self, + *, + reasoning_tokens: int, ) -> None: ... @overload @@ -9747,21 +12153,57 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ResponseUsageInputTokensDetails(_Model): - """ResponseUsageInputTokensDetails. +class Routine(_Model): + """A routine definition returned by the service. - :ivar cached_tokens: Required. - :vartype cached_tokens: int + :ivar name: The routine name. Required. + :vartype name: str + :ivar description: A human-readable description of the routine. + :vartype description: str + :ivar enabled: Whether the routine is enabled. Required. + :vartype enabled: bool + :ivar triggers: The triggers configured for the routine. Required. + :vartype triggers: dict[str, ~azure.ai.projects.models.RoutineTrigger] + :ivar action: The action executed when the routine fires. Required. + :vartype action: ~azure.ai.projects.models.RoutineAction + :ivar created_at: The time when the routine was created. + :vartype created_at: ~datetime.datetime + :ivar updated_at: The time when the routine was last updated. + :vartype updated_at: ~datetime.datetime """ - cached_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The routine name. Required.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A human-readable description of the routine.""" + enabled: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Whether the routine is enabled. Required.""" + triggers: dict[str, "_models.RoutineTrigger"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The triggers configured for the routine. Required.""" + action: "_models.RoutineAction" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The action executed when the routine fires. Required.""" + created_at: Optional[datetime.datetime] = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" + ) + """The time when the routine was created.""" + updated_at: Optional[datetime.datetime] = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" + ) + """The time when the routine was last updated.""" @overload def __init__( self, *, - cached_tokens: int, + name: str, + enabled: bool, + triggers: dict[str, "_models.RoutineTrigger"], + action: "_models.RoutineAction", + description: Optional[str] = None, + created_at: Optional[datetime.datetime] = None, + updated_at: Optional[datetime.datetime] = None, ) -> None: ... @overload @@ -9775,21 +12217,121 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ResponseUsageOutputTokensDetails(_Model): - """ResponseUsageOutputTokensDetails. +class RoutineRun(_Model): + """A single routine run returned from the run history API. - :ivar reasoning_tokens: Required. - :vartype reasoning_tokens: int + :ivar id: The MLflow run identifier for the routine attempt. Required. + :vartype id: str + :ivar status: The underlying MLflow run status. Required. + :vartype status: str + :ivar phase: The AgentExtensions lifecycle phase for the routine attempt. Known values are: + "queued", "dispatching", "completed", and "failed". + :vartype phase: str or ~azure.ai.projects.models.RoutineRunPhase + :ivar trigger_type: The trigger type that produced the routine attempt. Required. Known values + are: "github_issue_opened", "schedule", and "timer". + :vartype trigger_type: str or ~azure.ai.projects.models.RoutineTriggerType + :ivar attempt_source: The source path that created the routine attempt. Known values are: + "event_fire", "manual_dispatch", "queued_dispatch", "schedule_delivery", and "timer_delivery". + :vartype attempt_source: str or ~azure.ai.projects.models.RoutineAttemptSource + :ivar action_type: The action type dispatched for the routine attempt. Known values are: + "invoke_agent_responses_api" and "invoke_agent_invocations_api". + :vartype action_type: str or ~azure.ai.projects.models.RoutineActionType + :ivar triggered_at: The logical trigger time recorded for the routine attempt. + :vartype triggered_at: ~datetime.datetime + :ivar started_at: The time when the underlying run started. Required. + :vartype started_at: ~datetime.datetime + :ivar ended_at: The time when the underlying run reached a terminal state. + :vartype ended_at: ~datetime.datetime + :ivar dispatch_id: The dispatch identifier associated with the routine attempt. + :vartype dispatch_id: str + :ivar action_correlation_id: The downstream action correlation identifier, when available. + :vartype action_correlation_id: str + :ivar response_id: The downstream response or invocation identifier, when available. + :vartype response_id: str + :ivar task_id: The workspace task identifier linked to the routine attempt, when available. + :vartype task_id: str + :ivar error_type: The fully qualified error type captured for a failed attempt, when available. + :vartype error_type: str + :ivar error_message: The truncated failure message captured for a failed attempt, when + available. + :vartype error_message: str + :ivar diagnostics: Diagnostic data captured for the routine attempt. + :vartype diagnostics: ~azure.ai.projects.models.RoutineRunDiagnostics """ - reasoning_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Required.""" + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The MLflow run identifier for the routine attempt. Required.""" + status: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The underlying MLflow run status. Required.""" + phase: Optional[Union[str, "_models.RoutineRunPhase"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The AgentExtensions lifecycle phase for the routine attempt. Known values are: \"queued\", + \"dispatching\", \"completed\", and \"failed\".""" + trigger_type: Union[str, "_models.RoutineTriggerType"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The trigger type that produced the routine attempt. Required. Known values are: + \"github_issue_opened\", \"schedule\", and \"timer\".""" + attempt_source: Optional[Union[str, "_models.RoutineAttemptSource"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The source path that created the routine attempt. Known values are: \"event_fire\", + \"manual_dispatch\", \"queued_dispatch\", \"schedule_delivery\", and \"timer_delivery\".""" + action_type: Optional[Union[str, "_models.RoutineActionType"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """The action type dispatched for the routine attempt. Known values are: + \"invoke_agent_responses_api\" and \"invoke_agent_invocations_api\".""" + triggered_at: Optional[datetime.datetime] = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" + ) + """The logical trigger time recorded for the routine attempt.""" + started_at: datetime.datetime = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" + ) + """The time when the underlying run started. Required.""" + ended_at: Optional[datetime.datetime] = rest_field( + visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" + ) + """The time when the underlying run reached a terminal state.""" + dispatch_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The dispatch identifier associated with the routine attempt.""" + action_correlation_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The downstream action correlation identifier, when available.""" + response_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The downstream response or invocation identifier, when available.""" + task_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The workspace task identifier linked to the routine attempt, when available.""" + error_type: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The fully qualified error type captured for a failed attempt, when available.""" + error_message: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The truncated failure message captured for a failed attempt, when available.""" + diagnostics: Optional["_models.RoutineRunDiagnostics"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Diagnostic data captured for the routine attempt.""" @overload def __init__( self, *, - reasoning_tokens: int, + id: str, # pylint: disable=redefined-builtin + status: str, + trigger_type: Union[str, "_models.RoutineTriggerType"], + started_at: datetime.datetime, + phase: Optional[Union[str, "_models.RoutineRunPhase"]] = None, + attempt_source: Optional[Union[str, "_models.RoutineAttemptSource"]] = None, + action_type: Optional[Union[str, "_models.RoutineActionType"]] = None, + triggered_at: Optional[datetime.datetime] = None, + ended_at: Optional[datetime.datetime] = None, + dispatch_id: Optional[str] = None, + action_correlation_id: Optional[str] = None, + response_id: Optional[str] = None, + task_id: Optional[str] = None, + error_type: Optional[str] = None, + error_message: Optional[str] = None, + diagnostics: Optional["_models.RoutineRunDiagnostics"] = None, ) -> None: ... @overload @@ -9803,48 +12345,31 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class RubricBasedEvaluatorDefinition(EvaluatorDefinition, discriminator="rubrics"): - """Rubric-based evaluator definition — stores rubric criteria produced by the generate API. Used - for both quality and safety evaluators. +class RoutineRunDiagnostics(_Model): + """Generic diagnostics captured on a routine run. - :ivar init_parameters: The JSON schema (Draft 2020-12) for the evaluator's input parameters. - This includes parameters like type, properties, required. - :vartype init_parameters: dict[str, any] - :ivar data_schema: The JSON schema (Draft 2020-12) for the evaluator's input data. This - includes parameters like type, properties, required. - :vartype data_schema: dict[str, any] - :ivar metrics: List of output metrics produced by this evaluator. - :vartype metrics: dict[str, ~azure.ai.projects.models.EvaluatorMetric] - :ivar type: Required. Rubric-based evaluator definition. Stores rubric criteria for both - quality and safety evaluators. Can be created via the generate API or manually via - createVersion. - :vartype type: str or ~azure.ai.projects.models.RUBRICS - :ivar rubric_criteria: Rubric criteria — the scoring blueprint used by the LLM judge. Quality - evaluators include a non-editable residual criterion with rubric_id 'general_quality' - (always_applicable: true); safety evaluators include 'general_policy_compliance'. Both use the - same rubric structure. Required. - :vartype rubric_criteria: list[~azure.ai.projects.models.RubricCriterion] + :ivar parameters: MLflow parameters recorded on the run, keyed by parameter name. Required. + :vartype parameters: dict[str, str] + :ivar tags: MLflow tags recorded on the run, keyed by tag name. Required. + :vartype tags: dict[str, str] + :ivar metrics: Latest MLflow metric values recorded on the run, keyed by metric name. Required. + :vartype metrics: dict[str, float] """ - type: Literal[EvaluatorDefinitionType.RUBRICS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Required. Rubric-based evaluator definition. Stores rubric criteria for both quality and safety - evaluators. Can be created via the generate API or manually via createVersion.""" - rubric_criteria: list["_models.RubricCriterion"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Rubric criteria — the scoring blueprint used by the LLM judge. Quality evaluators include a - non-editable residual criterion with rubric_id 'general_quality' (always_applicable: true); - safety evaluators include 'general_policy_compliance'. Both use the same rubric structure. - Required.""" + parameters: dict[str, str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """MLflow parameters recorded on the run, keyed by parameter name. Required.""" + tags: dict[str, str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """MLflow tags recorded on the run, keyed by tag name. Required.""" + metrics: dict[str, float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Latest MLflow metric values recorded on the run, keyed by metric name. Required.""" @overload def __init__( self, *, - rubric_criteria: list["_models.RubricCriterion"], - init_parameters: Optional[dict[str, Any]] = None, - data_schema: Optional[dict[str, Any]] = None, - metrics: Optional[dict[str, "_models.EvaluatorMetric"]] = None, + parameters: dict[str, str], + tags: dict[str, str], + metrics: dict[str, float], ) -> None: ... @overload @@ -9856,56 +12381,61 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type = EvaluatorDefinitionType.RUBRICS # type: ignore -class RubricCriterion(_Model): - """A single rubric criterion — one measurable quality dimension in an evaluator's scoring - blueprint. - - :ivar rubric_id: Stable identifier for this rubric criterion (snake_case, e.g., - ``correct_resolution``). Required. Provided by the user when manually creating a rubric - evaluator or during human-in-the-loop review of a generated catalog; the generation pipeline - produces an initial value the user can edit. Editable when saving new versions. Required. - :vartype rubric_id: str - :ivar description: What this criterion measures (e.g., 'Correctly identifies the user's - reservation intent and pursues the appropriate workflow'). Required. - :vartype description: str - :ivar weight: Relative weight of this criterion (1-10). The generation pipeline assigns exactly - one criterion weight 8-10; all others use 1-6. User edits are not constrained by this - heuristic. Required. - :vartype weight: int - :ivar always_applicable: When true, the LLM judge always scores this criterion regardless of - relevance (skips applicability assessment). The service-generated general quality/policy - criterion has this set to true and is non-editable. Users may set this on their own custom - criteria. - :vartype always_applicable: bool - """ +class RubricBasedEvaluatorDefinition(EvaluatorDefinition, discriminator="rubric"): + """Rubric-based evaluator definition — stores dimensions produced by the generate API. Used for + both quality and safety evaluators. - rubric_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Stable identifier for this rubric criterion (snake_case, e.g., ``correct_resolution``). - Required. Provided by the user when manually creating a rubric evaluator or during - human-in-the-loop review of a generated catalog; the generation pipeline produces an initial - value the user can edit. Editable when saving new versions. Required.""" - description: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """What this criterion measures (e.g., 'Correctly identifies the user's reservation intent and - pursues the appropriate workflow'). Required.""" - weight: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Relative weight of this criterion (1-10). The generation pipeline assigns exactly one criterion - weight 8-10; all others use 1-6. User edits are not constrained by this heuristic. Required.""" - always_applicable: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """When true, the LLM judge always scores this criterion regardless of relevance (skips - applicability assessment). The service-generated general quality/policy criterion has this set - to true and is non-editable. Users may set this on their own custom criteria.""" + :ivar init_parameters: The JSON schema (Draft 2020-12) for the evaluator's input parameters. + This includes parameters like type, properties, required. + :vartype init_parameters: dict[str, any] + :ivar data_schema: The JSON schema (Draft 2020-12) for the evaluator's input data. This + includes parameters like type, properties, required. + :vartype data_schema: dict[str, any] + :ivar metrics: List of output metrics produced by this evaluator. + :vartype metrics: dict[str, ~azure.ai.projects.models.EvaluatorMetric] + :ivar type: Required. Rubric-based evaluator definition. Stores dimensions (the scoring + blueprint) for both quality and safety evaluators. Can be created via the generate API or + manually via createVersion. + :vartype type: str or ~azure.ai.projects.models.RUBRIC + :ivar dimensions: The set of dimensions — the scoring blueprint used by the LLM judge. Quality + evaluators include a non-editable residual dimension with id 'general_quality' + (always_applicable: true); safety evaluators include 'general_policy_compliance'. Both use the + same Dimension structure. Required. + :vartype dimensions: list[~azure.ai.projects.models.Dimension] + :ivar pass_threshold: Pass/fail threshold for the aggregate rubric score, on the same + normalized 0.0-1.0 scale as the emitted ``score``. When the runtime weighted average meets or + exceeds this value, the result is ``pass``. Defaults to 0.5 (equivalent to a raw 1-5 weighted + average of 3.0). The 'any dimension scored 1 → fail' rule still applies regardless of this + threshold. + :vartype pass_threshold: float + """ + + type: Literal[EvaluatorDefinitionType.RUBRIC] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Required. Rubric-based evaluator definition. Stores dimensions (the scoring blueprint) for both + quality and safety evaluators. Can be created via the generate API or manually via + createVersion.""" + dimensions: list["_models.Dimension"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The set of dimensions — the scoring blueprint used by the LLM judge. Quality evaluators include + a non-editable residual dimension with id 'general_quality' (always_applicable: true); safety + evaluators include 'general_policy_compliance'. Both use the same Dimension structure. + Required.""" + pass_threshold: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Pass/fail threshold for the aggregate rubric score, on the same normalized 0.0-1.0 scale as the + emitted ``score``. When the runtime weighted average meets or exceeds this value, the result is + ``pass``. Defaults to 0.5 (equivalent to a raw 1-5 weighted average of 3.0). The 'any dimension + scored 1 → fail' rule still applies regardless of this threshold.""" @overload def __init__( self, *, - rubric_id: str, - description: str, - weight: int, - always_applicable: Optional[bool] = None, + dimensions: list["_models.Dimension"], + init_parameters: Optional[dict[str, Any]] = None, + data_schema: Optional[dict[str, Any]] = None, + metrics: Optional[dict[str, "_models.EvaluatorMetric"]] = None, + pass_threshold: Optional[float] = None, ) -> None: ... @overload @@ -9917,6 +12447,7 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) + self.type = EvaluatorDefinitionType.RUBRIC # type: ignore class SASCredentials(BaseCredentials, discriminator="SAS"): @@ -10028,6 +12559,46 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class ScheduleRoutineTrigger(RoutineTrigger, discriminator="schedule"): + """A recurring cron-based routine trigger. + + :ivar type: The trigger type. Required. A recurring cron-based trigger. + :vartype type: str or ~azure.ai.projects.models.SCHEDULE + :ivar cron_expression: A 5-field cron expression. The service enforces a minimum interval of + five minutes by default. Required. + :vartype cron_expression: str + :ivar time_zone: An IANA or Windows time zone identifier for the schedule. Required. + :vartype time_zone: str + """ + + type: Literal[RoutineTriggerType.SCHEDULE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The trigger type. Required. A recurring cron-based trigger.""" + cron_expression: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A 5-field cron expression. The service enforces a minimum interval of five minutes by default. + Required.""" + time_zone: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """An IANA or Windows time zone identifier for the schedule. Required.""" + + @overload + def __init__( + self, + *, + cron_expression: str, + time_zone: str, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = RoutineTriggerType.SCHEDULE # type: ignore + + class ScheduleRun(_Model): """Schedule run model. @@ -10293,6 +12864,10 @@ class SharepointPreviewTool(Tool, discriminator="sharepoint_grounding_preview"): :vartype name: str :ivar description: Optional user-defined description for this tool or configuration. :vartype description: str + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] :ivar sharepoint_grounding_preview: The sharepoint grounding tool parameters. Required. :vartype sharepoint_grounding_preview: ~azure.ai.projects.models.SharepointGroundingToolParameters @@ -10305,6 +12880,12 @@ class SharepointPreviewTool(Tool, discriminator="sharepoint_grounding_preview"): """Optional user-defined name for this tool or configuration.""" description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Optional user-defined description for this tool or configuration.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" sharepoint_grounding_preview: "_models.SharepointGroundingToolParameters" = rest_field( visibility=["read", "create", "update", "delete", "query"] ) @@ -10317,6 +12898,7 @@ def __init__( sharepoint_grounding_preview: "_models.SharepointGroundingToolParameters", name: Optional[str] = None, description: Optional[str] = None, + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, ) -> None: ... @overload @@ -10657,6 +13239,55 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) +class SystemDataV3(_Model): + """System metadata for a resource. + + :ivar created_at: Timestamp of resource creation. + :vartype created_at: ~datetime.datetime + :ivar created_by: Identity that created the resource. + :vartype created_by: str + :ivar created_by_type: Type of identity that created the resource. + :vartype created_by_type: str + :ivar last_modified_at: Timestamp of last resource modification. + :vartype last_modified_at: ~datetime.datetime + """ + + created_at: Optional[datetime.datetime] = rest_field( + name="createdAt", visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" + ) + """Timestamp of resource creation.""" + created_by: Optional[str] = rest_field(name="createdBy", visibility=["read", "create", "update", "delete", "query"]) + """Identity that created the resource.""" + created_by_type: Optional[str] = rest_field( + name="createdByType", visibility=["read", "create", "update", "delete", "query"] + ) + """Type of identity that created the resource.""" + last_modified_at: Optional[datetime.datetime] = rest_field( + name="lastModifiedAt", visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" + ) + """Timestamp of last resource modification.""" + + @overload + def __init__( + self, + *, + created_at: Optional[datetime.datetime] = None, + created_by: Optional[str] = None, + created_by_type: Optional[str] = None, + last_modified_at: 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 TaxonomyCategory(_Model): """Taxonomy category definition. @@ -10943,6 +13574,48 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.type = TextResponseFormatConfigurationType.TEXT # type: ignore +class TimerRoutineTrigger(RoutineTrigger, discriminator="timer"): + """A one-shot timer routine trigger. + + :ivar type: The trigger type. Required. A one-shot timer trigger. + :vartype type: str or ~azure.ai.projects.models.TIMER + :ivar at: A future timer expression. Supported values include an ISO-8601 timestamp with an + explicit offset, a local timestamp paired with time_zone, or a positive duration from now. + Required. + :vartype at: str + :ivar time_zone: An optional IANA or Windows time zone identifier when the timer uses a local + timestamp. + :vartype time_zone: str + """ + + type: Literal[RoutineTriggerType.TIMER] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """The trigger type. Required. A one-shot timer trigger.""" + at: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A future timer expression. Supported values include an ISO-8601 timestamp with an explicit + offset, a local timestamp paired with time_zone, or a positive duration from now. Required.""" + time_zone: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """An optional IANA or Windows time zone identifier when the timer uses a local timestamp.""" + + @overload + def __init__( + self, + *, + at: str, + time_zone: Optional[str] = None, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, **kwargs) + self.type = RoutineTriggerType.TIMER # type: ignore + + class ToolboxObject(_Model): """A toolbox that stores reusable tool definitions for agents. @@ -11022,6 +13695,10 @@ class ToolboxSearchPreviewTool(Tool, discriminator="toolbox_search_preview"): :vartype name: str :ivar description: Optional user-defined description for this tool or configuration. :vartype description: str + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] """ type: Literal[ToolType.TOOLBOX_SEARCH_PREVIEW] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore @@ -11030,6 +13707,12 @@ class ToolboxSearchPreviewTool(Tool, discriminator="toolbox_search_preview"): """Optional user-defined name for this tool or configuration.""" description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Optional user-defined description for this tool or configuration.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" @overload def __init__( @@ -11037,6 +13720,7 @@ def __init__( *, name: Optional[str] = None, description: Optional[str] = None, + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, ) -> None: ... @overload @@ -11463,6 +14147,45 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.type = ToolChoiceParamType.WEB_SEARCH_PREVIEW_2025_03_11 # type: ignore +class ToolConfig(_Model): + """Per-tool configuration that controls tool visibility and search behavior. + + :ivar pin: When true, the tool is always included in agent context and visible in + ``tools/list``. When false (default), the tool is hidden from ``tools/list`` and only + discoverable via ``tool_search``. + :vartype pin: bool + :ivar additional_search_text: Additional text indexed for tool_search. Supplements the native + tool description to improve discoverability. Does not alter ``tools/list`` output. + :vartype additional_search_text: str + """ + + pin: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """When true, the tool is always included in agent context and visible in ``tools/list``. When + false (default), the tool is hidden from ``tools/list`` and only discoverable via + ``tool_search``.""" + additional_search_text: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Additional text indexed for tool_search. Supplements the native tool description to improve + discoverability. Does not alter ``tools/list`` output.""" + + @overload + def __init__( + self, + *, + pin: Optional[bool] = None, + additional_search_text: 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 ToolDescription(_Model): """Description of a tool that can be used by an agent. @@ -11617,55 +14340,53 @@ class TracesDataGenerationJobSource(DataGenerationJobSource, discriminator="trac :ivar type: The source type for this source, which is Traces. Required. Traces source — conversation traces from Application Insights. :vartype type: str or ~azure.ai.projects.models.TRACES - :ivar agent_id: The unique agent ID used to filter traces. Optional — when omitted, traces are - filtered by ``agent_name`` (and ``agent_version`` if specified). + :ivar agent_id: The unique agent ID used to filter traces. Provide either ``agent_id`` or + ``agent_name`` — at least one is required. :vartype agent_id: str - :ivar agent_name: The agent name to fetch traces for. Required. + :ivar agent_name: The agent name to fetch traces for. Provide either ``agent_id`` or + ``agent_name`` — at least one is required. :vartype agent_name: str :ivar agent_version: The agent version. If not specified, traces for ALL versions of the agent are included within the time window. :vartype agent_version: str :ivar start_time: Start of the time window (Unix timestamp in seconds) for fetching traces. + Required. :vartype start_time: ~datetime.datetime :ivar end_time: End of the time window (Unix timestamp in seconds). Defaults to current time. :vartype end_time: ~datetime.datetime - :ivar max_traces: Maximum number of traces to retrieve. - :vartype max_traces: int """ type: Literal[DataGenerationJobSourceType.TRACES] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The source type for this source, which is Traces. Required. Traces source — conversation traces from Application Insights.""" agent_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique agent ID used to filter traces. Optional — when omitted, traces are filtered by - ``agent_name`` (and ``agent_version`` if specified).""" - agent_name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The agent name to fetch traces for. Required.""" + """The unique agent ID used to filter traces. Provide either ``agent_id`` or ``agent_name`` — at + least one is required.""" + agent_name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The agent name to fetch traces for. Provide either ``agent_id`` or ``agent_name`` — at least + one is required.""" agent_version: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The agent version. If not specified, traces for ALL versions of the agent are included within the time window.""" - start_time: Optional[datetime.datetime] = rest_field( + start_time: datetime.datetime = rest_field( visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" ) - """Start of the time window (Unix timestamp in seconds) for fetching traces.""" + """Start of the time window (Unix timestamp in seconds) for fetching traces. Required.""" end_time: Optional[datetime.datetime] = rest_field( visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" ) """End of the time window (Unix timestamp in seconds). Defaults to current time.""" - max_traces: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Maximum number of traces to retrieve.""" @overload def __init__( self, *, - agent_name: str, + start_time: datetime.datetime, description: Optional[str] = None, agent_id: Optional[str] = None, + agent_name: Optional[str] = None, agent_version: Optional[str] = None, - start_time: Optional[datetime.datetime] = None, end_time: Optional[datetime.datetime] = None, - max_traces: Optional[int] = None, ) -> None: ... @overload @@ -11690,20 +14411,20 @@ class TracesEvaluatorGenerationJobSource(EvaluatorGenerationJobSource, discrimin :ivar type: The source type for this source, which is Traces. Required. Traces source — conversation traces from Application Insights. :vartype type: str or ~azure.ai.projects.models.TRACES - :ivar agent_id: The unique agent ID used to filter traces. Optional — when omitted, traces are - filtered by ``agent_name`` (and ``agent_version`` if specified). + :ivar agent_id: The unique agent ID used to filter traces. Provide either ``agent_id`` or + ``agent_name`` — at least one is required. :vartype agent_id: str - :ivar agent_name: The agent name to fetch traces for. Required. + :ivar agent_name: The agent name to fetch traces for. Provide either ``agent_id`` or + ``agent_name`` — at least one is required. :vartype agent_name: str :ivar agent_version: The agent version. If not specified, traces for ALL versions of the agent are included within the time window. :vartype agent_version: str :ivar start_time: Start of the time window (Unix timestamp in seconds) for fetching traces. + Required. :vartype start_time: ~datetime.datetime :ivar end_time: End of the time window (Unix timestamp in seconds). Defaults to current time. :vartype end_time: ~datetime.datetime - :ivar max_traces: Maximum number of traces to retrieve. - :vartype max_traces: int """ description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) @@ -11713,35 +14434,33 @@ class TracesEvaluatorGenerationJobSource(EvaluatorGenerationJobSource, discrimin """The source type for this source, which is Traces. Required. Traces source — conversation traces from Application Insights.""" agent_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The unique agent ID used to filter traces. Optional — when omitted, traces are filtered by - ``agent_name`` (and ``agent_version`` if specified).""" - agent_name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The agent name to fetch traces for. Required.""" + """The unique agent ID used to filter traces. Provide either ``agent_id`` or ``agent_name`` — at + least one is required.""" + agent_name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The agent name to fetch traces for. Provide either ``agent_id`` or ``agent_name`` — at least + one is required.""" agent_version: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The agent version. If not specified, traces for ALL versions of the agent are included within the time window.""" - start_time: Optional[datetime.datetime] = rest_field( + start_time: datetime.datetime = rest_field( visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" ) - """Start of the time window (Unix timestamp in seconds) for fetching traces.""" + """Start of the time window (Unix timestamp in seconds) for fetching traces. Required.""" end_time: Optional[datetime.datetime] = rest_field( visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" ) """End of the time window (Unix timestamp in seconds). Defaults to current time.""" - max_traces: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Maximum number of traces to retrieve.""" @overload def __init__( self, *, - agent_name: str, + start_time: datetime.datetime, description: Optional[str] = None, agent_id: Optional[str] = None, + agent_name: Optional[str] = None, agent_version: Optional[str] = None, - start_time: Optional[datetime.datetime] = None, end_time: Optional[datetime.datetime] = None, - max_traces: Optional[int] = None, ) -> None: ... @overload @@ -11756,6 +14475,39 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: self.type = EvaluatorGenerationJobSourceType.TRACES # type: ignore +class UpdateModelVersionRequest(_Model): + """Request body for updating a model version. Only description and tags can be modified. + + :ivar description: The asset description text. + :vartype description: str + :ivar tags: Tag dictionary. Tags can be added, removed, and updated. + :vartype tags: dict[str, str] + """ + + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The asset description text.""" + tags: Optional[dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Tag dictionary. Tags can be added, removed, and updated.""" + + @overload + def __init__( + self, + *, + description: Optional[str] = None, + tags: Optional[dict[str, 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 UpdateToolboxRequest(_Model): """UpdateToolboxRequest. @@ -12070,6 +14822,10 @@ class WebSearchTool(Tool, discriminator="web_search"): :vartype name: str :ivar description: Optional user-defined description for this tool or configuration. :vartype description: str + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] :ivar custom_search_configuration: The project connections attached to this tool. There can be a maximum of 1 connection resource attached to the tool. :vartype custom_search_configuration: ~azure.ai.projects.models.WebSearchConfiguration @@ -12094,6 +14850,12 @@ class WebSearchTool(Tool, discriminator="web_search"): """Optional user-defined name for this tool or configuration.""" description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Optional user-defined description for this tool or configuration.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" custom_search_configuration: Optional["_models.WebSearchConfiguration"] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) @@ -12109,6 +14871,7 @@ def __init__( search_context_size: Optional[Literal["low", "medium", "high"]] = None, name: Optional[str] = None, description: Optional[str] = None, + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, custom_search_configuration: Optional["_models.WebSearchConfiguration"] = None, ) -> None: ... @@ -12233,6 +14996,10 @@ class WorkIQPreviewTool(Tool, discriminator="work_iq_preview"): :vartype name: str :ivar description: Optional user-defined description for this tool or configuration. :vartype description: str + :ivar tool_configs: Per-tool configuration map. Keys are tool names or ``*`` (catch-all + default). Resolution order: exact tool name match takes priority over ``*``. Unknown tool names + are silently ignored at runtime. + :vartype tool_configs: dict[str, ~azure.ai.projects.models.ToolConfig] """ type: Literal[ToolType.WORK_IQ_PREVIEW] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore @@ -12243,6 +15010,12 @@ class WorkIQPreviewTool(Tool, discriminator="work_iq_preview"): """Optional user-defined name for this tool or configuration.""" description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Optional user-defined description for this tool or configuration.""" + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) + """Per-tool configuration map. Keys are tool names or ``*`` (catch-all default). Resolution order: + exact tool name match takes priority over ``*``. Unknown tool names are silently ignored at + runtime.""" @overload def __init__( @@ -12251,6 +15024,7 @@ def __init__( project_connection_id: str, name: Optional[str] = None, description: Optional[str] = None, + tool_configs: Optional[dict[str, "_models.ToolConfig"]] = None, ) -> None: ... @overload diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch.py b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch.py index 03b2e81ab05d..4918092f9e7a 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/models/_patch.py @@ -46,14 +46,18 @@ "memory_stores": _FoundryFeaturesOptInKeys.MEMORY_STORES_V1_PREVIEW.value, "red_teams": _FoundryFeaturesOptInKeys.RED_TEAMS_V1_PREVIEW.value, "schedules": _FoundryFeaturesOptInKeys.SCHEDULES_V1_PREVIEW.value, - "toolboxes": _FoundryFeaturesOptInKeys.TOOLBOXES_V1_PREVIEW.value, + "toolboxes": "Toolboxes=V1Preview", "skills": _FoundryFeaturesOptInKeys.SKILLS_V1_PREVIEW.value, "datasets": _FoundryFeaturesOptInKeys.DATA_GENERATION_JOBS_V1_PREVIEW.value, + "models": _FoundryFeaturesOptInKeys.MODELS_V1_PREVIEW.value, + "routines": _FoundryFeaturesOptInKeys.ROUTINES_V1_PREVIEW.value, "agents": ",".join( [ _AgentDefinitionOptInKeys.HOSTED_AGENTS_V1_PREVIEW.value, _AgentDefinitionOptInKeys.AGENT_ENDPOINT_V1_PREVIEW.value, _AgentDefinitionOptInKeys.CODE_AGENTS_V1_PREVIEW.value, + _AgentDefinitionOptInKeys.EXTERNAL_AGENTS_V1_PREVIEW.value, + _FoundryFeaturesOptInKeys.AGENTS_OPTIMIZATION_V1_PREVIEW.value, ] ), } diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py index 72b85abdab2f..5329776741c4 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_operations.py @@ -73,7 +73,7 @@ def build_agents_get_request(agent_name: str, **kwargs: Any) -> HttpRequest: return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_delete_request(agent_name: str, **kwargs: Any) -> HttpRequest: +def build_agents_delete_request(agent_name: str, *, force: Optional[bool] = None, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -89,6 +89,8 @@ def build_agents_delete_request(agent_name: str, **kwargs: Any) -> HttpRequest: _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters + if force is not None: + _params["force"] = _SERIALIZER.query("force", force, "bool") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers @@ -215,7 +217,9 @@ def build_agents_get_version_request(agent_name: str, agent_version: str, **kwar return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_delete_version_request(agent_name: str, agent_version: str, **kwargs: Any) -> HttpRequest: +def build_agents_delete_version_request( + agent_name: str, agent_version: str, *, force: Optional[bool] = None, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -232,6 +236,8 @@ def build_agents_delete_version_request(agent_name: str, agent_version: str, **k _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters + if force is not None: + _params["force"] = _SERIALIZER.query("force", force, "bool") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers @@ -798,33 +804,6 @@ def build_indexes_create_or_update_request(name: str, version: str, **kwargs: An return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_agents_update_agent_from_code_request( # pylint: disable=name-too-long - agent_name: str, *, code_zip_sha256: 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", "v1")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/agents/{agent_name}" - path_format_arguments = { - "agent_name": _SERIALIZER.url("agent_name", agent_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["x-ms-code-zip-sha256"] = _SERIALIZER.header("code_zip_sha256", code_zip_sha256, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - def build_beta_agents_patch_agent_details_request( # pylint: disable=name-too-long agent_name: str, **kwargs: Any ) -> HttpRequest: @@ -854,7 +833,7 @@ def build_beta_agents_patch_agent_details_request( # pylint: disable=name-too-l return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_agents_create_agent_version_from_code_request( # pylint: disable=name-too-long +def build_beta_agents_create_version_from_code_request( # pylint: disable=name-too-long agent_name: str, *, code_zip_sha256: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -881,35 +860,8 @@ def build_beta_agents_create_agent_version_from_code_request( # pylint: disable return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_agents_download_agent_version_code_request( # pylint: disable=name-too-long - agent_name: str, agent_version: 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", "v1")) - accept = _headers.pop("Accept", "application/zip") - - # Construct URL - _url = "/agents/{agent_name}/versions/{agent_version}/code:download" - path_format_arguments = { - "agent_name": _SERIALIZER.url("agent_name", agent_name, "str"), - "agent_version": _SERIALIZER.url("agent_version", agent_version, "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_beta_agents_download_agent_code_request( # pylint: disable=name-too-long - agent_name: str, **kwargs: Any + agent_name: str, *, agent_version: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -926,6 +878,8 @@ def build_beta_agents_download_agent_code_request( # pylint: disable=name-too-l _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters + if agent_version is not None: + _params["agent_version"] = _SERIALIZER.query("agent_version", agent_version, "str") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers @@ -1074,7 +1028,7 @@ def build_beta_agents_get_session_log_stream_request( # pylint: disable=name-to def build_beta_agents_upload_session_file_request( # pylint: disable=name-too-long - agent_name: str, agent_session_id: str, *, path: str, **kwargs: Any + agent_name: str, agent_session_id: str, *, path: str, user_isolation_key: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -1098,13 +1052,15 @@ def build_beta_agents_upload_session_file_request( # pylint: disable=name-too-l # Construct headers _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + if user_isolation_key is not None: + _headers["x-ms-user-isolation-key"] = _SERIALIZER.header("user_isolation_key", user_isolation_key, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) def build_beta_agents_download_session_file_request( # pylint: disable=name-too-long - agent_name: str, agent_session_id: str, *, path: str, **kwargs: Any + agent_name: str, agent_session_id: str, *, path: str, user_isolation_key: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -1126,13 +1082,15 @@ def build_beta_agents_download_session_file_request( # pylint: disable=name-too _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers + if user_isolation_key is not None: + _headers["x-ms-user-isolation-key"] = _SERIALIZER.header("user_isolation_key", user_isolation_key, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_beta_agents_get_session_files_request( # pylint: disable=name-too-long - agent_name: str, agent_session_id: str, *, path: str, **kwargs: Any + agent_name: str, agent_session_id: str, *, path: str, user_isolation_key: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -1154,14 +1112,23 @@ def build_beta_agents_get_session_files_request( # pylint: disable=name-too-lon _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers + if user_isolation_key is not None: + _headers["x-ms-user-isolation-key"] = _SERIALIZER.header("user_isolation_key", user_isolation_key, "str") _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) def build_beta_agents_delete_session_file_request( # pylint: disable=name-too-long - agent_name: str, agent_session_id: str, *, path: str, recursive: Optional[bool] = None, **kwargs: Any + agent_name: str, + agent_session_id: str, + *, + path: str, + recursive: Optional[bool] = None, + user_isolation_key: Optional[str] = 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", "v1")) @@ -1180,11 +1147,41 @@ def build_beta_agents_delete_session_file_request( # pylint: disable=name-too-l _params["recursive"] = _SERIALIZER.query("recursive", recursive, "bool") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + # Construct headers + if user_isolation_key is not None: + _headers["x-ms-user-isolation-key"] = _SERIALIZER.header("user_isolation_key", user_isolation_key, "str") + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_evaluation_taxonomies_get_request( # pylint: disable=name-too-long - name: str, **kwargs: Any + +def build_beta_agents_create_optimization_job_request( # pylint: disable=name-too-long + *, operation_id: Optional[str] = None, **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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/agent_optimization_jobs" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if operation_id is not None: + _headers["Operation-Id"] = _SERIALIZER.header("operation_id", operation_id, "str") + 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_beta_agents_get_optimization_job_request( # pylint: disable=name-too-long + job_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -1193,9 +1190,9 @@ def build_beta_evaluation_taxonomies_get_request( # pylint: disable=name-too-lo accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/evaluationtaxonomies/{name}" + _url = "/agent_optimization_jobs/{jobId}" path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), + "jobId": _SERIALIZER.url("job_id", job_id, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -1209,8 +1206,15 @@ def build_beta_evaluation_taxonomies_get_request( # pylint: disable=name-too-lo return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_evaluation_taxonomies_list_request( # pylint: disable=name-too-long - *, input_name: Optional[str] = None, input_type: Optional[str] = None, **kwargs: Any +def build_beta_agents_list_optimization_jobs_request( # pylint: disable=name-too-long + *, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + after: Optional[str] = None, + before: Optional[str] = None, + status: Optional[Union[str, _models.JobStatus]] = None, + agent_name: Optional[str] = None, + **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -1219,14 +1223,22 @@ def build_beta_evaluation_taxonomies_list_request( # pylint: disable=name-too-l accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/evaluationtaxonomies" + _url = "/agent_optimization_jobs" # Construct parameters + if limit is not None: + _params["limit"] = _SERIALIZER.query("limit", limit, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if after is not None: + _params["after"] = _SERIALIZER.query("after", after, "str") + if before is not None: + _params["before"] = _SERIALIZER.query("before", before, "str") + if status is not None: + _params["status"] = _SERIALIZER.query("status", status, "str") + if agent_name is not None: + _params["agent_name"] = _SERIALIZER.query("agent_name", agent_name, "str") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if input_name is not None: - _params["inputName"] = _SERIALIZER.query("input_name", input_name, "str") - if input_type is not None: - _params["inputType"] = _SERIALIZER.query("input_type", input_type, "str") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -1234,16 +1246,42 @@ def build_beta_evaluation_taxonomies_list_request( # pylint: disable=name-too-l return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_evaluation_taxonomies_delete_request( # pylint: disable=name-too-long - name: str, **kwargs: Any +def build_beta_agents_cancel_optimization_job_request( # pylint: disable=name-too-long + job_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", "v1")) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = "/evaluationtaxonomies/{name}" + _url = "/agent_optimization_jobs/{jobId}:cancel" path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), + "jobId": _SERIALIZER.url("job_id", job_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="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_beta_agents_delete_optimization_job_request( # pylint: disable=name-too-long + job_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "v1")) + # Construct URL + _url = "/agent_optimization_jobs/{jobId}" + path_format_arguments = { + "jobId": _SERIALIZER.url("job_id", job_id, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -1254,49 +1292,60 @@ def build_beta_evaluation_taxonomies_delete_request( # pylint: disable=name-too return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) -def build_beta_evaluation_taxonomies_create_request( # pylint: disable=name-too-long - name: str, **kwargs: Any +def build_beta_agents_list_optimization_candidates_request( # pylint: disable=name-too-long + job_id: str, + *, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + after: Optional[str] = None, + before: Optional[str] = None, + **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", "v1")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/evaluationtaxonomies/{name}" + _url = "/agent_optimization_jobs/{jobId}/candidates" path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), + "jobId": _SERIALIZER.url("job_id", job_id, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters + if limit is not None: + _params["limit"] = _SERIALIZER.query("limit", limit, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if after is not None: + _params["after"] = _SERIALIZER.query("after", after, "str") + if before is not None: + _params["before"] = _SERIALIZER.query("before", before, "str") _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="PUT", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_evaluation_taxonomies_update_request( # pylint: disable=name-too-long - name: str, **kwargs: Any +def build_beta_agents_get_optimization_candidate_request( # pylint: disable=name-too-long + job_id: str, candidate_id: 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", "v1")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/evaluationtaxonomies/{name}" + _url = "/agent_optimization_jobs/{jobId}/candidates/{candidateId}" path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), + "jobId": _SERIALIZER.url("job_id", job_id, "str"), + "candidateId": _SERIALIZER.url("candidate_id", candidate_id, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -1305,19 +1354,13 @@ def build_beta_evaluation_taxonomies_update_request( # pylint: disable=name-too _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) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_evaluators_list_versions_request( # pylint: disable=name-too-long - name: str, - *, - type: Optional[Union[Literal["builtin"], Literal["custom"], Literal["all"], str]] = None, - limit: Optional[int] = None, - **kwargs: Any +def build_beta_agents_get_optimization_candidate_config_request( # pylint: disable=name-too-long + job_id: str, candidate_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -1326,19 +1369,16 @@ def build_beta_evaluators_list_versions_request( # pylint: disable=name-too-lon accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/evaluators/{name}/versions" + _url = "/agent_optimization_jobs/{jobId}/candidates/{candidateId}/config" path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), + "jobId": _SERIALIZER.url("job_id", job_id, "str"), + "candidateId": _SERIALIZER.url("candidate_id", candidate_id, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if type is not None: - _params["type"] = _SERIALIZER.query("type", type, "str") - if limit is not None: - _params["limit"] = _SERIALIZER.query("limit", limit, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -1346,11 +1386,8 @@ def build_beta_evaluators_list_versions_request( # pylint: disable=name-too-lon return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_evaluators_list_request( - *, - type: Optional[Union[Literal["builtin"], Literal["custom"], Literal["all"], str]] = None, - limit: Optional[int] = None, - **kwargs: Any +def build_beta_agents_get_optimization_candidate_results_request( # pylint: disable=name-too-long + job_id: str, candidate_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -1359,14 +1396,16 @@ def build_beta_evaluators_list_request( accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/evaluators" + _url = "/agent_optimization_jobs/{jobId}/candidates/{candidateId}/results" + path_format_arguments = { + "jobId": _SERIALIZER.url("job_id", job_id, "str"), + "candidateId": _SERIALIZER.url("candidate_id", candidate_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if type is not None: - _params["type"] = _SERIALIZER.query("type", type, "str") - if limit is not None: - _params["limit"] = _SERIALIZER.query("limit", limit, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -1374,8 +1413,8 @@ def build_beta_evaluators_list_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_evaluators_get_version_request( # pylint: disable=name-too-long - name: str, version: str, **kwargs: Any +def build_beta_evaluation_taxonomies_get_request( # pylint: disable=name-too-long + name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -1384,10 +1423,9 @@ def build_beta_evaluators_get_version_request( # pylint: disable=name-too-long accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/evaluators/{name}/versions/{version}" + _url = "/evaluationtaxonomies/{name}" path_format_arguments = { "name": _SERIALIZER.url("name", name, "str"), - "version": _SERIALIZER.url("version", version, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -1401,17 +1439,41 @@ def build_beta_evaluators_get_version_request( # pylint: disable=name-too-long return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_evaluators_delete_version_request( # pylint: disable=name-too-long - name: str, version: str, **kwargs: Any +def build_beta_evaluation_taxonomies_list_request( # pylint: disable=name-too-long + *, input_name: Optional[str] = None, input_type: Optional[str] = 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", "v1")) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = "/evaluators/{name}/versions/{version}" + _url = "/evaluationtaxonomies" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if input_name is not None: + _params["inputName"] = _SERIALIZER.query("input_name", input_name, "str") + if input_type is not None: + _params["inputType"] = _SERIALIZER.query("input_type", input_type, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_beta_evaluation_taxonomies_delete_request( # pylint: disable=name-too-long + name: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "v1")) + # Construct URL + _url = "/evaluationtaxonomies/{name}" path_format_arguments = { "name": _SERIALIZER.url("name", name, "str"), - "version": _SERIALIZER.url("version", version, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -1422,7 +1484,7 @@ def build_beta_evaluators_delete_version_request( # pylint: disable=name-too-lo return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) -def build_beta_evaluators_create_version_request( # pylint: disable=name-too-long +def build_beta_evaluation_taxonomies_create_request( # pylint: disable=name-too-long name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -1433,7 +1495,7 @@ def build_beta_evaluators_create_version_request( # pylint: disable=name-too-lo accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/evaluators/{name}/versions" + _url = "/evaluationtaxonomies/{name}" path_format_arguments = { "name": _SERIALIZER.url("name", name, "str"), } @@ -1448,11 +1510,11 @@ def build_beta_evaluators_create_version_request( # pylint: disable=name-too-lo _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) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_evaluators_update_version_request( # pylint: disable=name-too-long - name: str, version: str, **kwargs: Any +def build_beta_evaluation_taxonomies_update_request( # pylint: disable=name-too-long + name: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -1462,7 +1524,175 @@ def build_beta_evaluators_update_version_request( # pylint: disable=name-too-lo accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/evaluators/{name}/versions/{version}" + _url = "/evaluationtaxonomies/{name}" + path_format_arguments = { + "name": _SERIALIZER.url("name", 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_beta_evaluators_list_versions_request( # pylint: disable=name-too-long + name: str, + *, + type: Optional[Union[Literal["builtin"], Literal["custom"], Literal["all"], str]] = None, + limit: 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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/evaluators/{name}/versions" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if type is not None: + _params["type"] = _SERIALIZER.query("type", type, "str") + if limit is not None: + _params["limit"] = _SERIALIZER.query("limit", limit, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_beta_evaluators_list_request( + *, + type: Optional[Union[Literal["builtin"], Literal["custom"], Literal["all"], str]] = None, + limit: 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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/evaluators" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if type is not None: + _params["type"] = _SERIALIZER.query("type", type, "str") + if limit is not None: + _params["limit"] = _SERIALIZER.query("limit", limit, "int") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_beta_evaluators_get_version_request( # pylint: disable=name-too-long + name: str, version: 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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/evaluators/{name}/versions/{version}" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + "version": _SERIALIZER.url("version", version, "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_beta_evaluators_delete_version_request( # pylint: disable=name-too-long + name: str, version: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "v1")) + # Construct URL + _url = "/evaluators/{name}/versions/{version}" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + "version": _SERIALIZER.url("version", version, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_beta_evaluators_create_version_request( # pylint: disable=name-too-long + 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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/evaluators/{name}/versions" + path_format_arguments = { + "name": _SERIALIZER.url("name", 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="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_beta_evaluators_update_version_request( # pylint: disable=name-too-long + name: str, version: 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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/evaluators/{name}/versions/{version}" path_format_arguments = { "name": _SERIALIZER.url("name", name, "str"), "version": _SERIALIZER.url("version", version, "str"), @@ -1481,6 +1711,66 @@ def build_beta_evaluators_update_version_request( # pylint: disable=name-too-lo return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) +def build_beta_evaluators_pending_upload_request( # pylint: disable=name-too-long + name: str, version: 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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/evaluators/{name}/versions/{version}/startPendingUpload" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + "version": _SERIALIZER.url("version", version, "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="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_beta_evaluators_get_credentials_request( # pylint: disable=name-too-long + name: str, version: 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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/evaluators/{name}/versions/{version}/credentials" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + "version": _SERIALIZER.url("version", version, "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="POST", url=_url, params=_params, headers=_headers, **kwargs) + + def build_beta_evaluators_create_generation_job_request( # pylint: disable=name-too-long *, operation_id: Optional[str] = None, **kwargs: Any ) -> HttpRequest: @@ -1539,7 +1829,6 @@ def build_beta_evaluators_list_generation_jobs_request( # pylint: disable=name- order: Optional[Union[str, _models.PageOrder]] = None, after: Optional[str] = None, before: Optional[str] = None, - category: Optional[Union[str, _models.EvaluatorCategory]] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) @@ -1560,8 +1849,6 @@ def build_beta_evaluators_list_generation_jobs_request( # pylint: disable=name- _params["after"] = _SERIALIZER.query("after", after, "str") if before is not None: _params["before"] = _SERIALIZER.query("before", before, "str") - if category is not None: - _params["category"] = _SERIALIZER.query("category", category, "str") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers @@ -1927,15 +2214,18 @@ def build_beta_memory_stores_delete_scope_request( # pylint: disable=name-too-l return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_red_teams_get_request(name: str, **kwargs: Any) -> HttpRequest: +def build_beta_memory_stores_create_memory_request( # pylint: disable=name-too-long + 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", "v1")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/redTeams/runs/{name}" + _url = "/memory_stores/{name}/items" path_format_arguments = { "name": _SERIALIZER.url("name", name, "str"), } @@ -1946,71 +2236,119 @@ def build_beta_red_teams_get_request(name: str, **kwargs: Any) -> HttpRequest: _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="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_red_teams_list_request(**kwargs: Any) -> HttpRequest: +def build_beta_memory_stores_update_memory_request( # pylint: disable=name-too-long + name: str, memory_id: 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", "v1")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/redTeams/runs" + _url = "/memory_stores/{name}/items/{memory_id}" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + "memory_id": _SERIALIZER.url("memory_id", memory_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 + 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="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_red_teams_create_request(**kwargs: Any) -> HttpRequest: +def build_beta_memory_stores_get_memory_request( # pylint: disable=name-too-long + name: str, memory_id: 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", "v1")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/redTeams/runs:run" + _url = "/memory_stores/{name}/items/{memory_id}" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + "memory_id": _SERIALIZER.url("memory_id", memory_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 - 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) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_schedules_delete_request(schedule_id: str, **kwargs: Any) -> HttpRequest: +def build_beta_memory_stores_list_memories_request( # pylint: disable=name-too-long + name: str, + *, + kind: Optional[Union[str, _models.MemoryItemKind]] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + after: Optional[str] = None, + before: Optional[str] = None, + **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", "v1")) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = "/schedules/{id}" + _url = "/memory_stores/{name}/items:list" path_format_arguments = { - "id": _SERIALIZER.url("schedule_id", schedule_id, "str"), + "name": _SERIALIZER.url("name", name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters + if kind is not None: + _params["kind"] = _SERIALIZER.query("kind", kind, "str") + if limit is not None: + _params["limit"] = _SERIALIZER.query("limit", limit, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if after is not None: + _params["after"] = _SERIALIZER.query("after", after, "str") + if before is not None: + _params["before"] = _SERIALIZER.query("before", before, "str") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + # 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="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_schedules_get_request(schedule_id: str, **kwargs: Any) -> HttpRequest: + +def build_beta_memory_stores_delete_memory_request( # pylint: disable=name-too-long + name: str, memory_id: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -2018,9 +2356,10 @@ def build_beta_schedules_get_request(schedule_id: str, **kwargs: Any) -> HttpReq accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/schedules/{id}" + _url = "/memory_stores/{name}/items/{memory_id}" path_format_arguments = { - "id": _SERIALIZER.url("schedule_id", schedule_id, "str"), + "name": _SERIALIZER.url("name", name, "str"), + "memory_id": _SERIALIZER.url("memory_id", memory_id, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -2031,12 +2370,10 @@ def build_beta_schedules_get_request(schedule_id: str, **kwargs: Any) -> HttpReq # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_schedules_list_request( - *, type: Optional[Union[str, _models.ScheduleTaskType]] = None, enabled: Optional[bool] = None, **kwargs: Any -) -> HttpRequest: +def build_beta_models_list_versions_request(name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -2044,14 +2381,15 @@ def build_beta_schedules_list_request( accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/schedules" + _url = "/models/{name}/versions" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if type is not None: - _params["type"] = _SERIALIZER.query("type", type, "str") - if enabled is not None: - _params["enabled"] = _SERIALIZER.query("enabled", enabled, "bool") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -2059,36 +2397,26 @@ def build_beta_schedules_list_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_schedules_create_or_update_request( # pylint: disable=name-too-long - schedule_id: str, **kwargs: Any -) -> HttpRequest: +def build_beta_models_list_request(**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", "v1")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/schedules/{id}" - path_format_arguments = { - "id": _SERIALIZER.url("schedule_id", schedule_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore + _url = "/models" # 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="PUT", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_schedules_get_run_request(schedule_id: str, run_id: str, **kwargs: Any) -> HttpRequest: +def build_beta_models_get_request(name: str, version: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -2096,10 +2424,10 @@ def build_beta_schedules_get_run_request(schedule_id: str, run_id: str, **kwargs accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/schedules/{schedule_id}/runs/{run_id}" + _url = "/models/{name}/versions/{version}" path_format_arguments = { - "schedule_id": _SERIALIZER.url("schedule_id", schedule_id, "str"), - "run_id": _SERIALIZER.url("run_id", run_id, "str"), + "name": _SERIALIZER.url("name", name, "str"), + "version": _SERIALIZER.url("version", version, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -2113,43 +2441,26 @@ def build_beta_schedules_get_run_request(schedule_id: str, run_id: str, **kwargs return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_schedules_list_runs_request( - schedule_id: str, - *, - type: Optional[Union[str, _models.ScheduleTaskType]] = None, - enabled: Optional[bool] = None, - **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) +def build_beta_models_delete_request(name: str, version: str, **kwargs: Any) -> HttpRequest: _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "v1")) - accept = _headers.pop("Accept", "application/json") - # Construct URL - _url = "/schedules/{id}/runs" + _url = "/models/{name}/versions/{version}" path_format_arguments = { - "id": _SERIALIZER.url("schedule_id", schedule_id, "str"), + "name": _SERIALIZER.url("name", name, "str"), + "version": _SERIALIZER.url("version", version, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if type is not None: - _params["type"] = _SERIALIZER.query("type", type, "str") - if enabled is not None: - _params["enabled"] = _SERIALIZER.query("enabled", enabled, "bool") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) -def build_beta_toolboxes_create_version_request( # pylint: disable=name-too-long - name: str, **kwargs: Any -) -> HttpRequest: +def build_beta_models_update_request(name: str, version: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -2158,9 +2469,10 @@ def build_beta_toolboxes_create_version_request( # pylint: disable=name-too-lon accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/toolboxes/{name}/versions" + _url = "/models/{name}/versions/{version}" path_format_arguments = { "name": _SERIALIZER.url("name", name, "str"), + "version": _SERIALIZER.url("version", version, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -2173,20 +2485,22 @@ def build_beta_toolboxes_create_version_request( # pylint: disable=name-too-lon _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) + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_toolboxes_get_request(name: str, **kwargs: Any) -> HttpRequest: +def build_beta_models_create_async_request(name: str, version: 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", "v1")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/toolboxes/{name}" + _url = "/models/{name}/versions/{version}/createAsync" path_format_arguments = { "name": _SERIALIZER.url("name", name, "str"), + "version": _SERIALIZER.url("version", version, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -2195,86 +2509,72 @@ def build_beta_toolboxes_get_request(name: str, **kwargs: Any) -> HttpRequest: _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="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_toolboxes_list_request( - *, - limit: Optional[int] = None, - order: Optional[Union[str, _models.PageOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: +def build_beta_models_pending_upload_request(name: str, version: 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", "v1")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/toolboxes" + _url = "/models/{name}/versions/{version}/startPendingUpload" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + "version": _SERIALIZER.url("version", version, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters - if limit is not None: - _params["limit"] = _SERIALIZER.query("limit", limit, "int") - if order is not None: - _params["order"] = _SERIALIZER.query("order", order, "str") - if after is not None: - _params["after"] = _SERIALIZER.query("after", after, "str") - if before is not None: - _params["before"] = _SERIALIZER.query("before", before, "str") _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="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_toolboxes_list_versions_request( # pylint: disable=name-too-long - name: str, - *, - limit: Optional[int] = None, - order: Optional[Union[str, _models.PageOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any +def build_beta_models_get_credentials_request( # pylint: disable=name-too-long + name: str, version: 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", "v1")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/toolboxes/{name}/versions" + _url = "/models/{name}/versions/{version}/credentials" path_format_arguments = { "name": _SERIALIZER.url("name", name, "str"), + "version": _SERIALIZER.url("version", version, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters - if limit is not None: - _params["limit"] = _SERIALIZER.query("limit", limit, "int") - if order is not None: - _params["order"] = _SERIALIZER.query("order", order, "str") - if after is not None: - _params["after"] = _SERIALIZER.query("after", after, "str") - if before is not None: - _params["before"] = _SERIALIZER.query("before", before, "str") _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="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_toolboxes_get_version_request(name: str, version: str, **kwargs: Any) -> HttpRequest: +def build_beta_red_teams_get_request(name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -2282,10 +2582,9 @@ def build_beta_toolboxes_get_version_request(name: str, version: str, **kwargs: accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/toolboxes/{name}/versions/{version}" + _url = "/redTeams/runs/{name}" path_format_arguments = { "name": _SERIALIZER.url("name", name, "str"), - "version": _SERIALIZER.url("version", version, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -2299,73 +2598,50 @@ def build_beta_toolboxes_get_version_request(name: str, version: str, **kwargs: return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_toolboxes_update_request(name: str, **kwargs: Any) -> HttpRequest: +def build_beta_red_teams_list_request(**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", "v1")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/toolboxes/{name}" - path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore + _url = "/redTeams/runs" # 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) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_toolboxes_delete_request(name: str, **kwargs: Any) -> HttpRequest: +def build_beta_red_teams_create_request(**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", "v1")) - # Construct URL - _url = "/toolboxes/{name}" - path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_beta_toolboxes_delete_version_request( # pylint: disable=name-too-long - name: str, version: str, **kwargs: Any -) -> HttpRequest: - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + accept = _headers.pop("Accept", "application/json") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "v1")) # Construct URL - _url = "/toolboxes/{name}/versions/{version}" - path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), - "version": _SERIALIZER.url("version", version, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore + _url = "/redTeams/runs:run" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + # 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="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_skills_create_request(**kwargs: Any) -> HttpRequest: + +def build_beta_routines_create_or_update_request( # pylint: disable=name-too-long + routine_name: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -2374,7 +2650,12 @@ def build_beta_skills_create_request(**kwargs: Any) -> HttpRequest: accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/skills" + _url = "/routines/{routine_name}" + path_format_arguments = { + "routine_name": _SERIALIZER.url("routine_name", routine_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -2384,31 +2665,34 @@ def build_beta_skills_create_request(**kwargs: Any) -> HttpRequest: _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) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_skills_create_from_package_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long +def build_beta_routines_get_request(routine_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: str = kwargs.pop("content_type") api_version: str = kwargs.pop("api_version", _params.pop("api-version", "v1")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/skills:import" + _url = "/routines/{routine_name}" + path_format_arguments = { + "routine_name": _SERIALIZER.url("routine_name", routine_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["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) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_skills_get_request(name: str, **kwargs: Any) -> HttpRequest: +def build_beta_routines_enable_request(routine_name: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -2416,9 +2700,9 @@ def build_beta_skills_get_request(name: str, **kwargs: Any) -> HttpRequest: accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/skills/{name}" + _url = "/routines/{routine_name}:enable" path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), + "routine_name": _SERIALIZER.url("routine_name", routine_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -2429,20 +2713,20 @@ def build_beta_skills_get_request(name: str, **kwargs: Any) -> HttpRequest: # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_skills_download_request(name: str, **kwargs: Any) -> HttpRequest: +def build_beta_routines_disable_request(routine_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", "v1")) - accept = _headers.pop("Accept", "application/zip") + accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/skills/{name}:download" + _url = "/routines/{routine_name}:disable" path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), + "routine_name": _SERIALIZER.url("routine_name", routine_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -2453,10 +2737,10 @@ def build_beta_skills_download_request(name: str, **kwargs: Any) -> HttpRequest: # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_skills_list_request( +def build_beta_routines_list_request( *, limit: Optional[int] = None, order: Optional[Union[str, _models.PageOrder]] = None, @@ -2471,7 +2755,7 @@ def build_beta_skills_list_request( accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/skills" + _url = "/routines" # Construct parameters if limit is not None: @@ -2490,44 +2774,81 @@ def build_beta_skills_list_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_skills_update_request(name: str, **kwargs: Any) -> HttpRequest: +def build_beta_routines_delete_request(routine_name: str, **kwargs: Any) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "v1")) + # Construct URL + _url = "/routines/{routine_name}" + path_format_arguments = { + "routine_name": _SERIALIZER.url("routine_name", routine_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_beta_routines_list_runs_request( + routine_name: str, + *, + filter: Optional[str] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + after: Optional[str] = None, + before: Optional[str] = None, + **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", "v1")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/skills/{name}" + _url = "/routines/{routine_name}/runs" path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), + "routine_name": _SERIALIZER.url("routine_name", routine_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters + if filter is not None: + _params["filter"] = _SERIALIZER.query("filter", filter, "str") + if limit is not None: + _params["limit"] = _SERIALIZER.query("limit", limit, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if after is not None: + _params["after"] = _SERIALIZER.query("after", after, "str") + if before is not None: + _params["before"] = _SERIALIZER.query("before", before, "str") _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="POST", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_skills_delete_request(name: str, **kwargs: Any) -> HttpRequest: +def build_beta_routines_dispatch_async_request( # pylint: disable=name-too-long + routine_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", "v1")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/skills/{name}" + _url = "/routines/{routine_name}:dispatch_async" path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), + "routine_name": _SERIALIZER.url("routine_name", routine_name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -2536,14 +2857,32 @@ def build_beta_skills_delete_request(name: str, **kwargs: Any) -> HttpRequest: _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="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_datasets_get_generation_job_request( # pylint: disable=name-too-long - job_id: str, **kwargs: Any -) -> HttpRequest: +def build_beta_schedules_delete_request(schedule_id: str, **kwargs: Any) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "v1")) + # Construct URL + _url = "/schedules/{id}" + path_format_arguments = { + "id": _SERIALIZER.url("schedule_id", schedule_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_beta_schedules_get_request(schedule_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -2551,9 +2890,9 @@ def build_beta_datasets_get_generation_job_request( # pylint: disable=name-too- accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/data_generation_jobs/{jobId}" + _url = "/schedules/{id}" path_format_arguments = { - "jobId": _SERIALIZER.url("job_id", job_id, "str"), + "id": _SERIALIZER.url("schedule_id", schedule_id, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -2567,15 +2906,8 @@ def build_beta_datasets_get_generation_job_request( # pylint: disable=name-too- return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_datasets_list_generation_jobs_request( # pylint: disable=name-too-long - *, - limit: Optional[int] = None, - order: Optional[Union[str, _models.PageOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - scenario: Optional[Union[str, _models.DataGenerationJobScenario]] = None, - type: Optional[List[Union[str, _models.DataGenerationJobType]]] = None, - **kwargs: Any +def build_beta_schedules_list_request( + *, type: Optional[Union[str, _models.ScheduleTaskType]] = None, enabled: Optional[bool] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -2584,22 +2916,14 @@ def build_beta_datasets_list_generation_jobs_request( # pylint: disable=name-to accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/data_generation_jobs" + _url = "/schedules" # Construct parameters - if limit is not None: - _params["limit"] = _SERIALIZER.query("limit", limit, "int") - if order is not None: - _params["order"] = _SERIALIZER.query("order", order, "str") - if after is not None: - _params["after"] = _SERIALIZER.query("after", after, "str") - if before is not None: - _params["before"] = _SERIALIZER.query("before", before, "str") - if scenario is not None: - _params["scenario"] = _SERIALIZER.query("scenario", scenario, "str") - if type is not None: - _params["type"] = _SERIALIZER.query("type", type, "[str]", div=",") _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if type is not None: + _params["type"] = _SERIALIZER.query("type", type, "str") + if enabled is not None: + _params["enabled"] = _SERIALIZER.query("enabled", enabled, "bool") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -2607,8 +2931,8 @@ def build_beta_datasets_list_generation_jobs_request( # pylint: disable=name-to return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_datasets_create_generation_job_request( # pylint: disable=name-too-long - *, operation_id: Optional[str] = None, **kwargs: Any +def build_beta_schedules_create_or_update_request( # pylint: disable=name-too-long + schedule_id: str, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -2618,24 +2942,25 @@ def build_beta_datasets_create_generation_job_request( # pylint: disable=name-t accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/data_generation_jobs" + _url = "/schedules/{id}" + path_format_arguments = { + "id": _SERIALIZER.url("schedule_id", schedule_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 - if operation_id is not None: - _headers["Operation-Id"] = _SERIALIZER.header("operation_id", operation_id, "str") 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) + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_datasets_cancel_generation_job_request( # pylint: disable=name-too-long - job_id: str, **kwargs: Any -) -> HttpRequest: +def build_beta_schedules_get_run_request(schedule_id: str, run_id: str, **kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) @@ -2643,9 +2968,10 @@ def build_beta_datasets_cancel_generation_job_request( # pylint: disable=name-t accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/data_generation_jobs/{jobId}:cancel" + _url = "/schedules/{schedule_id}/runs/{run_id}" path_format_arguments = { - "jobId": _SERIALIZER.url("job_id", job_id, "str"), + "schedule_id": _SERIALIZER.url("schedule_id", schedule_id, "str"), + "run_id": _SERIALIZER.url("run_id", run_id, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -2656,150 +2982,3557 @@ def build_beta_datasets_cancel_generation_job_request( # pylint: disable=name-t # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_beta_datasets_delete_generation_job_request( # pylint: disable=name-too-long - job_id: str, **kwargs: Any +def build_beta_schedules_list_runs_request( + schedule_id: str, + *, + type: Optional[Union[str, _models.ScheduleTaskType]] = None, + enabled: Optional[bool] = 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", "v1")) + accept = _headers.pop("Accept", "application/json") + # Construct URL - _url = "/data_generation_jobs/{jobId}" + _url = "/schedules/{id}/runs" path_format_arguments = { - "jobId": _SERIALIZER.url("job_id", job_id, "str"), + "id": _SERIALIZER.url("schedule_id", schedule_id, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if type is not None: + _params["type"] = _SERIALIZER.query("type", type, "str") + if enabled is not None: + _params["enabled"] = _SERIALIZER.query("enabled", enabled, "bool") - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class BetaOperations: # pylint: disable=too-many-instance-attributes - """ - .. warning:: - **DO NOT** instantiate this class directly. - Instead, you should access the following operations through - :class:`~azure.ai.projects.AIProjectClient`'s - :attr:`beta` attribute. - """ +def build_beta_toolboxes_create_version_request( # pylint: disable=name-too-long + name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - 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: AIProjectClientConfiguration = 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") + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "v1")) + accept = _headers.pop("Accept", "application/json") - self.agents = BetaAgentsOperations(self._client, self._config, self._serialize, self._deserialize) - self.evaluation_taxonomies = BetaEvaluationTaxonomiesOperations( - self._client, self._config, self._serialize, self._deserialize - ) - self.evaluators = BetaEvaluatorsOperations(self._client, self._config, self._serialize, self._deserialize) - self.insights = BetaInsightsOperations(self._client, self._config, self._serialize, self._deserialize) - self.memory_stores = BetaMemoryStoresOperations(self._client, self._config, self._serialize, self._deserialize) - self.red_teams = BetaRedTeamsOperations(self._client, self._config, self._serialize, self._deserialize) - self.schedules = BetaSchedulesOperations(self._client, self._config, self._serialize, self._deserialize) - self.toolboxes = BetaToolboxesOperations(self._client, self._config, self._serialize, self._deserialize) - self.skills = BetaSkillsOperations(self._client, self._config, self._serialize, self._deserialize) - self.datasets = BetaDatasetsOperations(self._client, self._config, self._serialize, self._deserialize) + # Construct URL + _url = "/toolboxes/{name}/versions" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + } + _url: str = _url.format(**path_format_arguments) # type: ignore -class AgentsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - Instead, you should access the following operations through - :class:`~azure.ai.projects.AIProjectClient`'s - :attr:`agents` attribute. - """ + # 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") - 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: AIProjectClientConfiguration = 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") + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - @distributed_trace - def get(self, agent_name: str, **kwargs: Any) -> _models.AgentDetails: - """Retrieves the agent. - :param agent_name: The name of the agent to retrieve. Required. - :type agent_name: str - :return: AgentDetails. The AgentDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentDetails - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map: MutableMapping = { - 401: ClientAuthenticationError, - 404: ResourceNotFoundError, - 409: ResourceExistsError, - 304: ResourceNotModifiedError, - } - error_map.update(kwargs.pop("error_map", {}) or {}) +def build_beta_toolboxes_get_request(name: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "v1")) + accept = _headers.pop("Accept", "application/json") - cls: ClsType[_models.AgentDetails] = kwargs.pop("cls", None) + # Construct URL + _url = "/toolboxes/{name}" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + } - _request = build_agents_get_request( - agent_name=agent_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) + _url: str = _url.format(**path_format_arguments) # type: ignore - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + # 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_beta_toolboxes_list_request( + *, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + after: Optional[str] = None, + before: Optional[str] = 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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/toolboxes" + + # Construct parameters + if limit is not None: + _params["limit"] = _SERIALIZER.query("limit", limit, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if after is not None: + _params["after"] = _SERIALIZER.query("after", after, "str") + if before is not None: + _params["before"] = _SERIALIZER.query("before", before, "str") + _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_beta_toolboxes_list_versions_request( # pylint: disable=name-too-long + name: str, + *, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + after: Optional[str] = None, + before: Optional[str] = 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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/toolboxes/{name}/versions" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + if limit is not None: + _params["limit"] = _SERIALIZER.query("limit", limit, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if after is not None: + _params["after"] = _SERIALIZER.query("after", after, "str") + if before is not None: + _params["before"] = _SERIALIZER.query("before", before, "str") + _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_beta_toolboxes_get_version_request(name: str, version: 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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/toolboxes/{name}/versions/{version}" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + "version": _SERIALIZER.url("version", version, "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_beta_toolboxes_update_request(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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/toolboxes/{name}" + path_format_arguments = { + "name": _SERIALIZER.url("name", 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_beta_toolboxes_delete_request(name: str, **kwargs: Any) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "v1")) + # Construct URL + _url = "/toolboxes/{name}" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_beta_toolboxes_delete_version_request( # pylint: disable=name-too-long + name: str, version: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "v1")) + # Construct URL + _url = "/toolboxes/{name}/versions/{version}" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + "version": _SERIALIZER.url("version", version, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +def build_beta_skills_create_request(**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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/skills" + + # 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="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_beta_skills_create_from_package_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: str = kwargs.pop("content_type") + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/skills:import" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _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_beta_skills_get_request(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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/skills/{name}" + path_format_arguments = { + "name": _SERIALIZER.url("name", 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_beta_skills_download_request(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", "v1")) + accept = _headers.pop("Accept", "application/zip") + + # Construct URL + _url = "/skills/{name}:download" + path_format_arguments = { + "name": _SERIALIZER.url("name", 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_beta_skills_list_request( + *, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + after: Optional[str] = None, + before: Optional[str] = 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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/skills" + + # Construct parameters + if limit is not None: + _params["limit"] = _SERIALIZER.query("limit", limit, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if after is not None: + _params["after"] = _SERIALIZER.query("after", after, "str") + if before is not None: + _params["before"] = _SERIALIZER.query("before", before, "str") + _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_beta_skills_update_request(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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/skills/{name}" + path_format_arguments = { + "name": _SERIALIZER.url("name", 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="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_beta_skills_delete_request(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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/skills/{name}" + path_format_arguments = { + "name": _SERIALIZER.url("name", 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_beta_datasets_get_generation_job_request( # pylint: disable=name-too-long + job_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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/data_generation_jobs/{jobId}" + path_format_arguments = { + "jobId": _SERIALIZER.url("job_id", job_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_beta_datasets_list_generation_jobs_request( # pylint: disable=name-too-long + *, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + after: Optional[str] = None, + before: Optional[str] = None, + scenario: Optional[Union[str, _models.DataGenerationJobScenario]] = None, + type: Optional[List[Union[str, _models.DataGenerationJobType]]] = 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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/data_generation_jobs" + + # Construct parameters + if limit is not None: + _params["limit"] = _SERIALIZER.query("limit", limit, "int") + if order is not None: + _params["order"] = _SERIALIZER.query("order", order, "str") + if after is not None: + _params["after"] = _SERIALIZER.query("after", after, "str") + if before is not None: + _params["before"] = _SERIALIZER.query("before", before, "str") + if scenario is not None: + _params["scenario"] = _SERIALIZER.query("scenario", scenario, "str") + if type is not None: + _params["type"] = _SERIALIZER.query("type", type, "[str]", div=",") + _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_beta_datasets_create_generation_job_request( # pylint: disable=name-too-long + *, operation_id: Optional[str] = None, **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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/data_generation_jobs" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if operation_id is not None: + _headers["Operation-Id"] = _SERIALIZER.header("operation_id", operation_id, "str") + 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_beta_datasets_cancel_generation_job_request( # pylint: disable=name-too-long + job_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", "v1")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/data_generation_jobs/{jobId}:cancel" + path_format_arguments = { + "jobId": _SERIALIZER.url("job_id", job_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="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_beta_datasets_delete_generation_job_request( # pylint: disable=name-too-long + job_id: str, **kwargs: Any +) -> HttpRequest: + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "v1")) + # Construct URL + _url = "/data_generation_jobs/{jobId}" + path_format_arguments = { + "jobId": _SERIALIZER.url("job_id", job_id, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + + +class BetaOperations: # pylint: disable=too-many-instance-attributes + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.AIProjectClient`'s + :attr:`beta` 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: AIProjectClientConfiguration = 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") + + self.agents = BetaAgentsOperations(self._client, self._config, self._serialize, self._deserialize) + self.evaluation_taxonomies = BetaEvaluationTaxonomiesOperations( + self._client, self._config, self._serialize, self._deserialize + ) + self.evaluators = BetaEvaluatorsOperations(self._client, self._config, self._serialize, self._deserialize) + self.insights = BetaInsightsOperations(self._client, self._config, self._serialize, self._deserialize) + self.memory_stores = BetaMemoryStoresOperations(self._client, self._config, self._serialize, self._deserialize) + self.models = BetaModelsOperations(self._client, self._config, self._serialize, self._deserialize) + self.red_teams = BetaRedTeamsOperations(self._client, self._config, self._serialize, self._deserialize) + self.routines = BetaRoutinesOperations(self._client, self._config, self._serialize, self._deserialize) + self.schedules = BetaSchedulesOperations(self._client, self._config, self._serialize, self._deserialize) + self.toolboxes = BetaToolboxesOperations(self._client, self._config, self._serialize, self._deserialize) + self.skills = BetaSkillsOperations(self._client, self._config, self._serialize, self._deserialize) + self.datasets = BetaDatasetsOperations(self._client, self._config, self._serialize, self._deserialize) + + +class AgentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.AIProjectClient`'s + :attr:`agents` 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: AIProjectClientConfiguration = 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 get(self, agent_name: str, **kwargs: Any) -> _models.AgentDetails: + """Retrieves the agent. + + :param agent_name: The name of the agent to retrieve. Required. + :type agent_name: str + :return: AgentDetails. The AgentDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentDetails + :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.AgentDetails] = kwargs.pop("cls", None) + + _request = build_agents_get_request( + agent_name=agent_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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.AgentDetails, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete(self, agent_name: str, *, force: Optional[bool] = None, **kwargs: Any) -> _models.DeleteAgentResponse: + """Deletes an agent. For hosted agents, if any version has active sessions, the request is + rejected with HTTP 409 unless ``force`` is set to true. When force is true, all associated + sessions are cascade-deleted along with the agent and its versions. + + :param agent_name: The name of the agent to delete. Required. + :type agent_name: str + :keyword force: For Hosted Agents, if true, force-deletes the agent even if its versions have + active sessions, cascading deletion to all associated sessions. This value is not relevant for + other Agent types. Defaults to false. Default value is None. + :paramtype force: bool + :return: DeleteAgentResponse. The DeleteAgentResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DeleteAgentResponse + :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.DeleteAgentResponse] = kwargs.pop("cls", None) + + _request = build_agents_delete_request( + agent_name=agent_name, + force=force, + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.DeleteAgentResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, + *, + kind: Optional[Union[str, _models.AgentKind]] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + before: Optional[str] = None, + **kwargs: Any + ) -> ItemPaged["_models.AgentDetails"]: + """Returns the list of all agents. + + :keyword kind: Filter agents by kind. If not provided, all agents are returned. Known values + are: "prompt", "hosted", "workflow", and "external". Default value is None. + :paramtype kind: str or ~azure.ai.projects.models.AgentKind + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :return: An iterator like instance of AgentDetails + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.AgentDetails] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.AgentDetails]] = 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(_continuation_token=None): + + _request = build_agents_list_request( + kind=kind, + limit=limit, + order=order, + after=_continuation_token, + before=before, + 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) + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.AgentDetails], + deserialized.get("data", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("last_id") or None, iter(list_of_elem) + + def get_next(_continuation_token=None): + _request = prepare_request(_continuation_token) + + _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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def create_version( + self, + agent_name: str, + *, + definition: _models.AgentDefinition, + content_type: str = "application/json", + metadata: Optional[dict[str, str]] = None, + description: Optional[str] = None, + blueprint_reference: Optional[_models.AgentBlueprintReference] = None, + **kwargs: Any + ) -> _models.AgentVersionDetails: + """Create a new agent version. + + :param agent_name: The unique name that identifies the agent. Name can be used to + retrieve/update/delete the agent. + + * Must start and end with alphanumeric characters, + * Can contain hyphens in the middle + * Must not exceed 63 characters. Required. + :type agent_name: str + :keyword definition: The agent definition. This can be a workflow, hosted agent, or a simple + agent definition. Required. + :paramtype definition: ~azure.ai.projects.models.AgentDefinition + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword metadata: Set of 16 key-value pairs that can be attached to an object. This can be + useful for storing additional information about the object in a structured + format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings + with a maximum length of 512 characters. Default value is None. + :paramtype metadata: dict[str, str] + :keyword description: A human-readable description of the agent. Default value is None. + :paramtype description: str + :keyword blueprint_reference: The blueprint reference for the agent. Default value is None. + :paramtype blueprint_reference: ~azure.ai.projects.models.AgentBlueprintReference + :return: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentVersionDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_version( + self, agent_name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AgentVersionDetails: + """Create a new agent version. + + :param agent_name: The unique name that identifies the agent. Name can be used to + retrieve/update/delete the agent. + + * Must start and end with alphanumeric characters, + * Can contain hyphens in the middle + * Must not exceed 63 characters. Required. + :type agent_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: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentVersionDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_version( + self, agent_name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AgentVersionDetails: + """Create a new agent version. + + :param agent_name: The unique name that identifies the agent. Name can be used to + retrieve/update/delete the agent. + + * Must start and end with alphanumeric characters, + * Can contain hyphens in the middle + * Must not exceed 63 characters. Required. + :type agent_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: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentVersionDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_version( + self, + agent_name: str, + body: Union[JSON, IO[bytes]] = _Unset, + *, + definition: _models.AgentDefinition = _Unset, + metadata: Optional[dict[str, str]] = None, + description: Optional[str] = None, + blueprint_reference: Optional[_models.AgentBlueprintReference] = None, + **kwargs: Any + ) -> _models.AgentVersionDetails: + """Create a new agent version. + + :param agent_name: The unique name that identifies the agent. Name can be used to + retrieve/update/delete the agent. + + * Must start and end with alphanumeric characters, + * Can contain hyphens in the middle + * Must not exceed 63 characters. Required. + :type agent_name: str + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword definition: The agent definition. This can be a workflow, hosted agent, or a simple + agent definition. Required. + :paramtype definition: ~azure.ai.projects.models.AgentDefinition + :keyword metadata: Set of 16 key-value pairs that can be attached to an object. This can be + useful for storing additional information about the object in a structured + format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings + with a maximum length of 512 characters. Default value is None. + :paramtype metadata: dict[str, str] + :keyword description: A human-readable description of the agent. Default value is None. + :paramtype description: str + :keyword blueprint_reference: The blueprint reference for the agent. Default value is None. + :paramtype blueprint_reference: ~azure.ai.projects.models.AgentBlueprintReference + :return: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentVersionDetails + :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.AgentVersionDetails] = kwargs.pop("cls", None) + + if body is _Unset: + if definition is _Unset: + raise TypeError("missing required argument: definition") + body = { + "blueprint_reference": blueprint_reference, + "definition": definition, + "description": description, + "metadata": metadata, + } + 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_agents_create_version_request( + agent_name=agent_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]: + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.AgentVersionDetails, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create_version_from_manifest( + self, + agent_name: str, + *, + manifest_id: str, + parameter_values: dict[str, Any], + content_type: str = "application/json", + metadata: Optional[dict[str, str]] = None, + description: Optional[str] = None, + **kwargs: Any + ) -> _models.AgentVersionDetails: + """Create a new agent version from a manifest. + + :param agent_name: The unique name that identifies the agent. Name can be used to + retrieve/update/delete the agent. + + * Must start and end with alphanumeric characters, + * Can contain hyphens in the middle + * Must not exceed 63 characters. Required. + :type agent_name: str + :keyword manifest_id: The manifest ID to import the agent version from. Required. + :paramtype manifest_id: str + :keyword parameter_values: The inputs to the manifest that will result in a fully materialized + Agent. Required. + :paramtype parameter_values: dict[str, any] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword metadata: Set of 16 key-value pairs that can be attached to an object. This can be + useful for storing additional information about the object in a structured + format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings + with a maximum length of 512 characters. Default value is None. + :paramtype metadata: dict[str, str] + :keyword description: A human-readable description of the agent. Default value is None. + :paramtype description: str + :return: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentVersionDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_version_from_manifest( + self, agent_name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AgentVersionDetails: + """Create a new agent version from a manifest. + + :param agent_name: The unique name that identifies the agent. Name can be used to + retrieve/update/delete the agent. + + * Must start and end with alphanumeric characters, + * Can contain hyphens in the middle + * Must not exceed 63 characters. Required. + :type agent_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: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentVersionDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_version_from_manifest( + self, agent_name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AgentVersionDetails: + """Create a new agent version from a manifest. + + :param agent_name: The unique name that identifies the agent. Name can be used to + retrieve/update/delete the agent. + + * Must start and end with alphanumeric characters, + * Can contain hyphens in the middle + * Must not exceed 63 characters. Required. + :type agent_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: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentVersionDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_version_from_manifest( + self, + agent_name: str, + body: Union[JSON, IO[bytes]] = _Unset, + *, + manifest_id: str = _Unset, + parameter_values: dict[str, Any] = _Unset, + metadata: Optional[dict[str, str]] = None, + description: Optional[str] = None, + **kwargs: Any + ) -> _models.AgentVersionDetails: + """Create a new agent version from a manifest. + + :param agent_name: The unique name that identifies the agent. Name can be used to + retrieve/update/delete the agent. + + * Must start and end with alphanumeric characters, + * Can contain hyphens in the middle + * Must not exceed 63 characters. Required. + :type agent_name: str + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword manifest_id: The manifest ID to import the agent version from. Required. + :paramtype manifest_id: str + :keyword parameter_values: The inputs to the manifest that will result in a fully materialized + Agent. Required. + :paramtype parameter_values: dict[str, any] + :keyword metadata: Set of 16 key-value pairs that can be attached to an object. This can be + useful for storing additional information about the object in a structured + format, and querying for objects via API or the dashboard. + + Keys are strings with a maximum length of 64 characters. Values are strings + with a maximum length of 512 characters. Default value is None. + :paramtype metadata: dict[str, str] + :keyword description: A human-readable description of the agent. Default value is None. + :paramtype description: str + :return: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentVersionDetails + :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.AgentVersionDetails] = kwargs.pop("cls", None) + + if body is _Unset: + if manifest_id is _Unset: + raise TypeError("missing required argument: manifest_id") + if parameter_values is _Unset: + raise TypeError("missing required argument: parameter_values") + body = { + "description": description, + "manifest_id": manifest_id, + "metadata": metadata, + "parameter_values": parameter_values, + } + 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_agents_create_version_from_manifest_request( + agent_name=agent_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]: + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.AgentVersionDetails, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_version(self, agent_name: str, agent_version: str, **kwargs: Any) -> _models.AgentVersionDetails: + """Retrieves a specific version of an agent. + + :param agent_name: The name of the agent to retrieve. Required. + :type agent_name: str + :param agent_version: The version of the agent to retrieve. Required. + :type agent_version: str + :return: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentVersionDetails + :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.AgentVersionDetails] = kwargs.pop("cls", None) + + _request = build_agents_get_version_request( + agent_name=agent_name, + agent_version=agent_version, + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.AgentVersionDetails, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_version( + self, agent_name: str, agent_version: str, *, force: Optional[bool] = None, **kwargs: Any + ) -> _models.DeleteAgentVersionResponse: + """Deletes a specific version of an agent. For hosted agents, if the version has active sessions, + the request is rejected with HTTP 409 unless ``force`` is set to true. When force is true, all + sessions associated with this version are cascade-deleted. + + :param agent_name: The name of the agent to delete. Required. + :type agent_name: str + :param agent_version: The version of the agent to delete. Required. + :type agent_version: str + :keyword force: For Hosted Agents, if true, force-deletes the version even if it has active + sessions, cascading deletion to all associated sessions. This value is not relevant for other + Agent types. Defaults to false. Default value is None. + :paramtype force: bool + :return: DeleteAgentVersionResponse. The DeleteAgentVersionResponse is compatible with + MutableMapping + :rtype: ~azure.ai.projects.models.DeleteAgentVersionResponse + :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.DeleteAgentVersionResponse] = kwargs.pop("cls", None) + + _request = build_agents_delete_version_request( + agent_name=agent_name, + agent_version=agent_version, + force=force, + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.DeleteAgentVersionResponse, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list_versions( + self, + agent_name: str, + *, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + before: Optional[str] = None, + **kwargs: Any + ) -> ItemPaged["_models.AgentVersionDetails"]: + """Returns the list of versions of an agent. + + :param agent_name: The name of the agent to retrieve versions for. Required. + :type agent_name: str + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :return: An iterator like instance of AgentVersionDetails + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.AgentVersionDetails] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.AgentVersionDetails]] = 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(_continuation_token=None): + + _request = build_agents_list_versions_request( + agent_name=agent_name, + limit=limit, + order=order, + after=_continuation_token, + before=before, + 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) + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.AgentVersionDetails], + deserialized.get("data", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("last_id") or None, iter(list_of_elem) + + def get_next(_continuation_token=None): + _request = prepare_request(_continuation_token) + + _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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class EvaluationRulesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.AIProjectClient`'s + :attr:`evaluation_rules` 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: AIProjectClientConfiguration = 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 get(self, id: str, **kwargs: Any) -> _models.EvaluationRule: + """Get an evaluation rule. + + :param id: Unique identifier for the evaluation rule. Required. + :type id: str + :return: EvaluationRule. The EvaluationRule is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationRule + :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.EvaluationRule] = kwargs.pop("cls", None) + + _request = build_evaluation_rules_get_request( + id=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.EvaluationRule, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete(self, id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete an evaluation rule. + + :param id: Unique identifier for the evaluation rule. Required. + :type id: str + :return: None + :rtype: None + :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[None] = kwargs.pop("cls", None) + + _request = build_evaluation_rules_delete_request( + id=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) + + _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 [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def create_or_update( + self, id: str, evaluation_rule: _models.EvaluationRule, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluationRule: + """Create or update an evaluation rule. + + :param id: Unique identifier for the evaluation rule. Required. + :type id: str + :param evaluation_rule: Evaluation rule resource. Required. + :type evaluation_rule: ~azure.ai.projects.models.EvaluationRule + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EvaluationRule. The EvaluationRule is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationRule + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, id: str, evaluation_rule: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluationRule: + """Create or update an evaluation rule. + + :param id: Unique identifier for the evaluation rule. Required. + :type id: str + :param evaluation_rule: Evaluation rule resource. Required. + :type evaluation_rule: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EvaluationRule. The EvaluationRule is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationRule + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, id: str, evaluation_rule: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluationRule: + """Create or update an evaluation rule. + + :param id: Unique identifier for the evaluation rule. Required. + :type id: str + :param evaluation_rule: Evaluation rule resource. Required. + :type evaluation_rule: 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: EvaluationRule. The EvaluationRule is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationRule + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, id: str, evaluation_rule: Union[_models.EvaluationRule, JSON, IO[bytes]], **kwargs: Any + ) -> _models.EvaluationRule: + """Create or update an evaluation rule. + + :param id: Unique identifier for the evaluation rule. Required. + :type id: str + :param evaluation_rule: Evaluation rule resource. Is one of the following types: + EvaluationRule, JSON, IO[bytes] Required. + :type evaluation_rule: ~azure.ai.projects.models.EvaluationRule or JSON or IO[bytes] + :return: EvaluationRule. The EvaluationRule is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationRule + :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.EvaluationRule] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(evaluation_rule, (IOBase, bytes)): + _content = evaluation_rule + else: + _content = json.dumps(evaluation_rule, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_evaluation_rules_create_or_update_request( + id=id, + 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.EvaluationRule, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, + *, + action_type: Optional[Union[str, _models.EvaluationRuleActionType]] = None, + agent_name: Optional[str] = None, + enabled: Optional[bool] = None, + **kwargs: Any + ) -> ItemPaged["_models.EvaluationRule"]: + """List all evaluation rules. + + :keyword action_type: Filter by the type of evaluation rule. Known values are: + "continuousEvaluation" and "humanEvaluationPreview". Default value is None. + :paramtype action_type: str or ~azure.ai.projects.models.EvaluationRuleActionType + :keyword agent_name: Filter by the agent name. Default value is None. + :paramtype agent_name: str + :keyword enabled: Filter by the enabled status. Default value is None. + :paramtype enabled: bool + :return: An iterator like instance of EvaluationRule + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.EvaluationRule] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.EvaluationRule]] = 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_evaluation_rules_list_request( + action_type=action_type, + agent_name=agent_name, + enabled=enabled, + 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.EvaluationRule], + 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 ConnectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.AIProjectClient`'s + :attr:`connections` 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: AIProjectClientConfiguration = 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 _get(self, name: str, **kwargs: Any) -> _models.Connection: + """Get a connection by name, without populating connection credentials. + + :param name: The friendly name of the connection, provided by the user. Required. + :type name: str + :return: Connection. The Connection is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Connection + :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.Connection] = kwargs.pop("cls", None) + + _request = build_connections_get_request( + name=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) + + response_headers = {} + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Connection, response.json()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def _get_with_credentials(self, name: str, **kwargs: Any) -> _models.Connection: + """Get a connection by name, with its connection credentials. + + :param name: The friendly name of the connection, provided by the user. Required. + :type name: str + :return: Connection. The Connection is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Connection + :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.Connection] = kwargs.pop("cls", None) + + _request = build_connections_get_with_credentials_request( + name=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) + + response_headers = {} + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Connection, response.json()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, + *, + connection_type: Optional[Union[str, _models.ConnectionType]] = None, + default_connection: Optional[bool] = None, + **kwargs: Any + ) -> ItemPaged["_models.Connection"]: + """List all connections in the project, without populating connection credentials. + + :keyword connection_type: List connections of this specific type. Known values are: + "AzureOpenAI", "AzureBlob", "AzureStorageAccount", "CognitiveSearch", "CosmosDB", "ApiKey", + "AppConfig", "AppInsights", "CustomKeys", and "RemoteTool_Preview". Default value is None. + :paramtype connection_type: str or ~azure.ai.projects.models.ConnectionType + :keyword default_connection: List connections that are default connections. Default value is + None. + :paramtype default_connection: bool + :return: An iterator like instance of Connection + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.Connection] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Connection]] = 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_connections_list_request( + connection_type=connection_type, + default_connection=default_connection, + 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.Connection], + 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 DatasetsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.AIProjectClient`'s + :attr:`datasets` 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: AIProjectClientConfiguration = 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_versions(self, name: str, **kwargs: Any) -> ItemPaged["_models.DatasetVersion"]: + """List all versions of the given DatasetVersion. + + :param name: The name of the resource. Required. + :type name: str + :return: An iterator like instance of DatasetVersion + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.DatasetVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.DatasetVersion]] = 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_datasets_list_versions_request( + name=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) + + 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.DatasetVersion], + 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 list(self, **kwargs: Any) -> ItemPaged["_models.DatasetVersion"]: + """List the latest version of each DatasetVersion. + + :return: An iterator like instance of DatasetVersion + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.DatasetVersion] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.DatasetVersion]] = 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_datasets_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.DatasetVersion], + 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(self, name: str, version: str, **kwargs: Any) -> _models.DatasetVersion: + """Get the specific version of the DatasetVersion. The service returns 404 Not Found error if the + DatasetVersion does not exist. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the DatasetVersion to retrieve. Required. + :type version: str + :return: DatasetVersion. The DatasetVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetVersion + :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.DatasetVersion] = kwargs.pop("cls", None) + + _request = build_datasets_get_request( + name=name, + version=version, + 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.DatasetVersion, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete(self, name: str, version: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete the specific version of the DatasetVersion. The service returns 204 No Content if the + DatasetVersion was deleted successfully or if the DatasetVersion does not exist. + + :param name: The name of the resource. Required. + :type name: str + :param version: The version of the DatasetVersion to delete. Required. + :type version: str + :return: None + :rtype: None + :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[None] = kwargs.pop("cls", None) + + _request = build_datasets_delete_request( + name=name, + version=version, + 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) + + _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 [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def create_or_update( + self, + name: str, + version: str, + dataset_version: _models.DatasetVersion, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> _models.DatasetVersion: + """Create a new or update an existing DatasetVersion with the given version id. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the DatasetVersion to create or update. Required. + :type version: str + :param dataset_version: The DatasetVersion to create or update. Required. + :type dataset_version: ~azure.ai.projects.models.DatasetVersion + :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: DatasetVersion. The DatasetVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + name: str, + version: str, + dataset_version: JSON, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> _models.DatasetVersion: + """Create a new or update an existing DatasetVersion with the given version id. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the DatasetVersion to create or update. Required. + :type version: str + :param dataset_version: The DatasetVersion to create or update. Required. + :type dataset_version: 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: DatasetVersion. The DatasetVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + name: str, + version: str, + dataset_version: IO[bytes], + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> _models.DatasetVersion: + """Create a new or update an existing DatasetVersion with the given version id. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the DatasetVersion to create or update. Required. + :type version: str + :param dataset_version: The DatasetVersion to create or update. Required. + :type dataset_version: 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: DatasetVersion. The DatasetVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, name: str, version: str, dataset_version: Union[_models.DatasetVersion, JSON, IO[bytes]], **kwargs: Any + ) -> _models.DatasetVersion: + """Create a new or update an existing DatasetVersion with the given version id. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the DatasetVersion to create or update. Required. + :type version: str + :param dataset_version: The DatasetVersion to create or update. Is one of the following types: + DatasetVersion, JSON, IO[bytes] Required. + :type dataset_version: ~azure.ai.projects.models.DatasetVersion or JSON or IO[bytes] + :return: DatasetVersion. The DatasetVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetVersion + :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.DatasetVersion] = kwargs.pop("cls", None) + + content_type = content_type or "application/merge-patch+json" + _content = None + if isinstance(dataset_version, (IOBase, bytes)): + _content = dataset_version + else: + _content = json.dumps(dataset_version, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_datasets_create_or_update_request( + name=name, + version=version, + 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.DatasetVersion, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def pending_upload( + self, + name: str, + version: str, + pending_upload_request: _models.PendingUploadRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PendingUploadResult: + """Start a new or get an existing pending upload of a dataset for a specific version. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the DatasetVersion to operate on. Required. + :type version: str + :param pending_upload_request: The pending upload request parameters. Required. + :type pending_upload_request: ~azure.ai.projects.models.PendingUploadRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PendingUploadResult. The PendingUploadResult is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def pending_upload( + self, + name: str, + version: str, + pending_upload_request: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PendingUploadResult: + """Start a new or get an existing pending upload of a dataset for a specific version. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the DatasetVersion to operate on. Required. + :type version: str + :param pending_upload_request: The pending upload request parameters. Required. + :type pending_upload_request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PendingUploadResult. The PendingUploadResult is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def pending_upload( + self, + name: str, + version: str, + pending_upload_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PendingUploadResult: + """Start a new or get an existing pending upload of a dataset for a specific version. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the DatasetVersion to operate on. Required. + :type version: str + :param pending_upload_request: The pending upload request parameters. Required. + :type pending_upload_request: 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: PendingUploadResult. The PendingUploadResult is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def pending_upload( + self, + name: str, + version: str, + pending_upload_request: Union[_models.PendingUploadRequest, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.PendingUploadResult: + """Start a new or get an existing pending upload of a dataset for a specific version. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the DatasetVersion to operate on. Required. + :type version: str + :param pending_upload_request: The pending upload request parameters. Is one of the following + types: PendingUploadRequest, JSON, IO[bytes] Required. + :type pending_upload_request: ~azure.ai.projects.models.PendingUploadRequest or JSON or + IO[bytes] + :return: PendingUploadResult. The PendingUploadResult is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResult + :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.PendingUploadResult] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(pending_upload_request, (IOBase, bytes)): + _content = pending_upload_request + else: + _content = json.dumps(pending_upload_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_datasets_pending_upload_request( + name=name, + version=version, + 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]: + 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.PendingUploadResult, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_credentials(self, name: str, version: str, **kwargs: Any) -> _models.DatasetCredential: + """Get the SAS credential to access the storage account associated with a Dataset version. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the DatasetVersion to operate on. Required. + :type version: str + :return: DatasetCredential. The DatasetCredential is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetCredential + :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.DatasetCredential] = kwargs.pop("cls", None) + + _request = build_datasets_get_credentials_request( + name=name, + version=version, + 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.DatasetCredential, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class DeploymentsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.AIProjectClient`'s + :attr:`deployments` 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: AIProjectClientConfiguration = 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 get(self, name: str, **kwargs: Any) -> _models.Deployment: + """Get a deployed model. + + :param name: Name of the deployment. Required. + :type name: str + :return: Deployment. The Deployment is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Deployment + :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.Deployment] = kwargs.pop("cls", None) + + _request = build_deployments_get_request( + name=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) + + response_headers = {} + response_headers["x-ms-client-request-id"] = self._deserialize( + "str", response.headers.get("x-ms-client-request-id") + ) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Deployment, response.json()) + + if cls: + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, + *, + model_publisher: Optional[str] = None, + model_name: Optional[str] = None, + deployment_type: Optional[Union[str, _models.DeploymentType]] = None, + **kwargs: Any + ) -> ItemPaged["_models.Deployment"]: + """List all deployed models in the project. + + :keyword model_publisher: Model publisher to filter models by. Default value is None. + :paramtype model_publisher: str + :keyword model_name: Model name (the publisher specific name) to filter models by. Default + value is None. + :paramtype model_name: str + :keyword deployment_type: Type of deployment to filter list by. "ModelDeployment" Default value + is None. + :paramtype deployment_type: str or ~azure.ai.projects.models.DeploymentType + :return: An iterator like instance of Deployment + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.Deployment] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Deployment]] = 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_deployments_list_request( + model_publisher=model_publisher, + model_name=model_name, + deployment_type=deployment_type, + 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.Deployment], + 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 IndexesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.AIProjectClient`'s + :attr:`indexes` 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: AIProjectClientConfiguration = 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_versions(self, name: str, **kwargs: Any) -> ItemPaged["_models.Index"]: + """List all versions of the given Index. + + :param name: The name of the resource. Required. + :type name: str + :return: An iterator like instance of Index + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.Index] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Index]] = 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_indexes_list_versions_request( + name=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) + + 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.Index], + 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 list(self, **kwargs: Any) -> ItemPaged["_models.Index"]: + """List the latest version of each Index. + + :return: An iterator like instance of Index + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.Index] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Index]] = 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_indexes_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.Index], + 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(self, name: str, version: str, **kwargs: Any) -> _models.Index: + """Get the specific version of the Index. The service returns 404 Not Found error if the Index + does not exist. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the Index to retrieve. Required. + :type version: str + :return: Index. The Index is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Index + :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.Index] = kwargs.pop("cls", None) + + _request = build_indexes_get_request( + name=name, + version=version, + 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.Index, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete(self, name: str, version: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete the specific version of the Index. The service returns 204 No Content if the Index was + deleted successfully or if the Index does not exist. + + :param name: The name of the resource. Required. + :type name: str + :param version: The version of the Index to delete. Required. + :type version: str + :return: None + :rtype: None + :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[None] = kwargs.pop("cls", None) + + _request = build_indexes_delete_request( + name=name, + version=version, + 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) + + _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 [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def create_or_update( + self, + name: str, + version: str, + index: _models.Index, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> _models.Index: + """Create a new or update an existing Index with the given version id. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the Index to create or update. Required. + :type version: str + :param index: The Index to create or update. Required. + :type index: ~azure.ai.projects.models.Index + :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: Index. The Index is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Index + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, name: str, version: str, index: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> _models.Index: + """Create a new or update an existing Index with the given version id. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the Index to create or update. Required. + :type version: str + :param index: The Index to create or update. Required. + :type index: 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: Index. The Index is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Index + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_or_update( + self, + name: str, + version: str, + index: IO[bytes], + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> _models.Index: + """Create a new or update an existing Index with the given version id. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the Index to create or update. Required. + :type version: str + :param index: The Index to create or update. Required. + :type index: 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: Index. The Index is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Index + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_or_update( + self, name: str, version: str, index: Union[_models.Index, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Index: + """Create a new or update an existing Index with the given version id. + + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the Index to create or update. Required. + :type version: str + :param index: The Index to create or update. Is one of the following types: Index, JSON, + IO[bytes] Required. + :type index: ~azure.ai.projects.models.Index or JSON or IO[bytes] + :return: Index. The Index is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Index + :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.Index] = kwargs.pop("cls", None) + + content_type = content_type or "application/merge-patch+json" + _content = None + if isinstance(index, (IOBase, bytes)): + _content = index + else: + _content = json.dumps(index, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_indexes_create_or_update_request( + name=name, + version=version, + 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]: + 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) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) + raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.AgentDetails, response.json()) + deserialized = _deserialize(_models.Index, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + +class BetaAgentsOperations: # pylint: disable=too-many-public-methods + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.AIProjectClient`'s + :attr:`agents` 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: AIProjectClientConfiguration = 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 patch_agent_details( + self, + agent_name: str, + *, + content_type: str = "application/merge-patch+json", + agent_endpoint: Optional[_models.AgentEndpointConfig] = None, + agent_card: Optional[_models.AgentCard] = None, + **kwargs: Any + ) -> _models.AgentDetails: + """Updates an agent endpoint. + + :param agent_name: The name of the agent to retrieve. Required. + :type agent_name: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/merge-patch+json". + :paramtype content_type: str + :keyword agent_endpoint: The endpoint configuration for the agent. Default value is None. + :paramtype agent_endpoint: ~azure.ai.projects.models.AgentEndpointConfig + :keyword agent_card: Optional agent card for the agent. Default value is None. + :paramtype agent_card: ~azure.ai.projects.models.AgentCard + :return: AgentDetails. The AgentDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def patch_agent_details( + self, agent_name: str, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> _models.AgentDetails: + """Updates an agent endpoint. + + :param agent_name: The name of the agent to retrieve. Required. + :type agent_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/merge-patch+json". + :paramtype content_type: str + :return: AgentDetails. The AgentDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def patch_agent_details( + self, agent_name: str, body: IO[bytes], *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> _models.AgentDetails: + """Updates an agent endpoint. + + :param agent_name: The name of the agent to retrieve. Required. + :type agent_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/merge-patch+json". + :paramtype content_type: str + :return: AgentDetails. The AgentDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + @distributed_trace - def delete(self, agent_name: str, **kwargs: Any) -> _models.DeleteAgentResponse: - """Deletes an agent. + def patch_agent_details( + self, + agent_name: str, + body: Union[JSON, IO[bytes]] = _Unset, + *, + agent_endpoint: Optional[_models.AgentEndpointConfig] = None, + agent_card: Optional[_models.AgentCard] = None, + **kwargs: Any + ) -> _models.AgentDetails: + """Updates an agent endpoint. - :param agent_name: The name of the agent to delete. Required. + :param agent_name: The name of the agent to retrieve. Required. :type agent_name: str - :return: DeleteAgentResponse. The DeleteAgentResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.DeleteAgentResponse + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword agent_endpoint: The endpoint configuration for the agent. Default value is None. + :paramtype agent_endpoint: ~azure.ai.projects.models.AgentEndpointConfig + :keyword agent_card: Optional agent card for the agent. Default value is None. + :paramtype agent_card: ~azure.ai.projects.models.AgentCard + :return: AgentDetails. The AgentDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentDetails :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -2810,14 +6543,27 @@ def delete(self, agent_name: str, **kwargs: Any) -> _models.DeleteAgentResponse: } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.DeleteAgentResponse] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AgentDetails] = kwargs.pop("cls", None) - _request = build_agents_delete_request( + if body is _Unset: + body = {"agent_card": agent_card, "agent_endpoint": agent_endpoint} + body = {k: v for k, v in body.items() if v is not None} + content_type = content_type or "application/merge-patch+json" + _content = None + if isinstance(body, (IOBase, bytes)): + _content = body + else: + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_beta_agents_patch_agent_details_request( agent_name=agent_name, + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -2850,121 +6596,23 @@ def delete(self, agent_name: str, **kwargs: Any) -> _models.DeleteAgentResponse: if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.DeleteAgentResponse, response.json()) + deserialized = _deserialize(_models.AgentDetails, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @distributed_trace - def list( - self, - *, - kind: Optional[Union[str, _models.AgentKind]] = None, - limit: Optional[int] = None, - order: Optional[Union[str, _models.PageOrder]] = None, - before: Optional[str] = None, - **kwargs: Any - ) -> ItemPaged["_models.AgentDetails"]: - """Returns the list of all agents. - - :keyword kind: Filter agents by kind. If not provided, all agents are returned. Known values - are: "prompt", "hosted", and "workflow". Default value is None. - :paramtype kind: str or ~azure.ai.projects.models.AgentKind - :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and - 100, and the - default is 20. Default value is None. - :paramtype limit: int - :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for - ascending order and``desc`` - for descending order. Known values are: "asc" and "desc". Default value is None. - :paramtype order: str or ~azure.ai.projects.models.PageOrder - :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your - place in the list. - For instance, if you make a list request and receive 100 objects, ending with obj_foo, your - subsequent call can include before=obj_foo in order to fetch the previous page of the list. - Default value is None. - :paramtype before: str - :return: An iterator like instance of AgentDetails - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.AgentDetails] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.AgentDetails]] = 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(_continuation_token=None): - - _request = build_agents_list_request( - kind=kind, - limit=limit, - order=order, - after=_continuation_token, - before=before, - 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) - return _request - - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize( - List[_models.AgentDetails], - deserialized.get("data", []), - ) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("last_id") or None, iter(list_of_elem) - - def get_next(_continuation_token=None): - _request = prepare_request(_continuation_token) - - _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) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) - - return pipeline_response - - return ItemPaged(get_next, extract_data) - @overload - def create_version( + def create_version_from_code( self, agent_name: str, + content: _models.CreateAgentVersionFromCodeContent, *, - definition: _models.AgentDefinition, - content_type: str = "application/json", - metadata: Optional[dict[str, str]] = None, - description: Optional[str] = None, - blueprint_reference: Optional[_models.AgentBlueprintReference] = None, + code_zip_sha256: str, **kwargs: Any ) -> _models.AgentVersionDetails: - """Create a new agent version. + """create_version_from_code. :param agent_name: The unique name that identifies the agent. Name can be used to retrieve/update/delete the agent. @@ -2973,33 +6621,21 @@ def create_version( * Can contain hyphens in the middle * Must not exceed 63 characters. Required. :type agent_name: str - :keyword definition: The agent definition. This can be a workflow, hosted agent, or a simple - agent definition. Required. - :paramtype definition: ~azure.ai.projects.models.AgentDefinition - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword metadata: Set of 16 key-value pairs that can be attached to an object. This can be - useful for storing additional information about the object in a structured - format, and querying for objects via API or the dashboard. - - Keys are strings with a maximum length of 64 characters. Values are strings - with a maximum length of 512 characters. Default value is None. - :paramtype metadata: dict[str, str] - :keyword description: A human-readable description of the agent. Default value is None. - :paramtype description: str - :keyword blueprint_reference: The blueprint reference for the agent. Default value is None. - :paramtype blueprint_reference: ~azure.ai.projects.models.AgentBlueprintReference + :param content: Required. + :type content: ~azure.ai.projects.models.CreateAgentVersionFromCodeContent + :keyword code_zip_sha256: SHA-256 hex digest of the uploaded code zip. Used for change + detection (dedup) and integrity verification. Required. + :paramtype code_zip_sha256: str :return: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping :rtype: ~azure.ai.projects.models.AgentVersionDetails :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_version( - self, agent_name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + def create_version_from_code( + self, agent_name: str, content: JSON, *, code_zip_sha256: str, **kwargs: Any ) -> _models.AgentVersionDetails: - """Create a new agent version. + """create_version_from_code. :param agent_name: The unique name that identifies the agent. Name can be used to retrieve/update/delete the agent. @@ -3008,21 +6644,26 @@ def create_version( * Can contain hyphens in the middle * Must not exceed 63 characters. Required. :type agent_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 + :param content: Required. + :type content: JSON + :keyword code_zip_sha256: SHA-256 hex digest of the uploaded code zip. Used for change + detection (dedup) and integrity verification. Required. + :paramtype code_zip_sha256: str :return: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping :rtype: ~azure.ai.projects.models.AgentVersionDetails :raises ~azure.core.exceptions.HttpResponseError: """ - @overload - def create_version( - self, agent_name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + @distributed_trace + def create_version_from_code( + self, + agent_name: str, + content: Union[_models.CreateAgentVersionFromCodeContent, JSON], + *, + code_zip_sha256: str, + **kwargs: Any ) -> _models.AgentVersionDetails: - """Create a new agent version. + """create_version_from_code. :param agent_name: The unique name that identifies the agent. Name can be used to retrieve/update/delete the agent. @@ -3031,55 +6672,97 @@ def create_version( * Can contain hyphens in the middle * Must not exceed 63 characters. Required. :type agent_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 + :param content: Is either a CreateAgentVersionFromCodeContent type or a JSON type. Required. + :type content: ~azure.ai.projects.models.CreateAgentVersionFromCodeContent or JSON + :keyword code_zip_sha256: SHA-256 hex digest of the uploaded code zip. Used for change + detection (dedup) and integrity verification. Required. + :paramtype code_zip_sha256: str :return: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping :rtype: ~azure.ai.projects.models.AgentVersionDetails :raises ~azure.core.exceptions.HttpResponseError: """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) - @distributed_trace - def create_version( - self, - agent_name: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - definition: _models.AgentDefinition = _Unset, - metadata: Optional[dict[str, str]] = None, - description: Optional[str] = None, - blueprint_reference: Optional[_models.AgentBlueprintReference] = None, - **kwargs: Any - ) -> _models.AgentVersionDetails: - """Create a new agent version. + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - :param agent_name: The unique name that identifies the agent. Name can be used to - retrieve/update/delete the agent. + cls: ClsType[_models.AgentVersionDetails] = kwargs.pop("cls", None) - * Must start and end with alphanumeric characters, - * Can contain hyphens in the middle - * Must not exceed 63 characters. Required. - :type agent_name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword definition: The agent definition. This can be a workflow, hosted agent, or a simple - agent definition. Required. - :paramtype definition: ~azure.ai.projects.models.AgentDefinition - :keyword metadata: Set of 16 key-value pairs that can be attached to an object. This can be - useful for storing additional information about the object in a structured - format, and querying for objects via API or the dashboard. + _body = content.as_dict() if isinstance(content, _Model) else content + _file_fields: list[str] = ["code"] + _data_fields: list[str] = ["metadata"] + _files = prepare_multipart_form_data(_body, _file_fields, _data_fields) - Keys are strings with a maximum length of 64 characters. Values are strings - with a maximum length of 512 characters. Default value is None. - :paramtype metadata: dict[str, str] - :keyword description: A human-readable description of the agent. Default value is None. - :paramtype description: str - :keyword blueprint_reference: The blueprint reference for the agent. Default value is None. - :paramtype blueprint_reference: ~azure.ai.projects.models.AgentBlueprintReference - :return: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentVersionDetails + _request = build_beta_agents_create_version_from_code_request( + agent_name=agent_name, + code_zip_sha256=code_zip_sha256, + api_version=self._config.api_version, + files=_files, + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.AgentVersionDetails, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def download_agent_code( + self, agent_name: str, *, agent_version: Optional[str] = None, **kwargs: Any + ) -> Iterator[bytes]: + """Download the code zip for a code-based hosted agent. + Returns the previously-uploaded zip (``application/zip``). + + If ``agent_version`` is supplied, returns that version's code zip; otherwise + returns the latest version's code zip. + + The SHA-256 digest of the returned bytes matches the ``content_hash`` on the + resolved version's ``code_configuration``. + + :param agent_name: The name of the agent. Required. + :type agent_name: str + :keyword agent_version: The version of the agent whose code zip should be downloaded. + If omitted, the latest version's code zip is returned. Default value is None. + :paramtype agent_version: str + :return: Iterator[bytes] + :rtype: Iterator[bytes] :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3090,34 +6773,15 @@ def create_version( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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.AgentVersionDetails] = kwargs.pop("cls", None) - - if body is _Unset: - if definition is _Unset: - raise TypeError("missing required argument: definition") - body = { - "blueprint_reference": blueprint_reference, - "definition": definition, - "description": description, - "metadata": metadata, - } - 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 + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - _request = build_agents_create_version_request( + _request = build_beta_agents_download_agent_code_request( agent_name=agent_name, - content_type=content_type, + agent_version=agent_version, api_version=self._config.api_version, - content=_content, headers=_headers, params=_params, ) @@ -3127,7 +6791,7 @@ def create_version( _request.url = self._client.format_url(_request.url, **path_format_arguments) _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _stream = kwargs.pop("stream", True) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -3147,144 +6811,111 @@ def create_version( ) raise HttpResponseError(response=response, model=error) - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.AgentVersionDetails, response.json()) + response_headers = {} + response_headers["x-ms-agent-version"] = self._deserialize("str", response.headers.get("x-ms-agent-version")) + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + + deserialized = response.iter_bytes() if _decompress else response.iter_raw() if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore @overload - def create_version_from_manifest( + def create_session( self, agent_name: str, *, - manifest_id: str, - parameter_values: dict[str, Any], + version_indicator: _models.VersionIndicator, content_type: str = "application/json", - metadata: Optional[dict[str, str]] = None, - description: Optional[str] = None, + agent_session_id: Optional[str] = None, **kwargs: Any - ) -> _models.AgentVersionDetails: - """Create a new agent version from a manifest. - - :param agent_name: The unique name that identifies the agent. Name can be used to - retrieve/update/delete the agent. + ) -> _models.AgentSessionResource: + """Creates a new session for an agent endpoint. The endpoint resolves the backing agent version + from ``version_indicator`` and enforces session ownership using the provided isolation key for + session-mutating operations. - * Must start and end with alphanumeric characters, - * Can contain hyphens in the middle - * Must not exceed 63 characters. Required. + :param agent_name: The name of the agent to create a session for. Required. :type agent_name: str - :keyword manifest_id: The manifest ID to import the agent version from. Required. - :paramtype manifest_id: str - :keyword parameter_values: The inputs to the manifest that will result in a fully materialized - Agent. Required. - :paramtype parameter_values: dict[str, any] + :keyword version_indicator: Determines which agent version backs the session. Required. + :paramtype version_indicator: ~azure.ai.projects.models.VersionIndicator :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword metadata: Set of 16 key-value pairs that can be attached to an object. This can be - useful for storing additional information about the object in a structured - format, and querying for objects via API or the dashboard. - - Keys are strings with a maximum length of 64 characters. Values are strings - with a maximum length of 512 characters. Default value is None. - :paramtype metadata: dict[str, str] - :keyword description: A human-readable description of the agent. Default value is None. - :paramtype description: str - :return: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentVersionDetails + :keyword agent_session_id: Optional caller-provided session ID. If specified, it must be unique + within the agent endpoint. Auto-generated if omitted. Default value is None. + :paramtype agent_session_id: str + :return: AgentSessionResource. The AgentSessionResource is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentSessionResource :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_version_from_manifest( + def create_session( self, agent_name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AgentVersionDetails: - """Create a new agent version from a manifest. - - :param agent_name: The unique name that identifies the agent. Name can be used to - retrieve/update/delete the agent. + ) -> _models.AgentSessionResource: + """Creates a new session for an agent endpoint. The endpoint resolves the backing agent version + from ``version_indicator`` and enforces session ownership using the provided isolation key for + session-mutating operations. - * Must start and end with alphanumeric characters, - * Can contain hyphens in the middle - * Must not exceed 63 characters. Required. + :param agent_name: The name of the agent to create a session for. Required. :type agent_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: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentVersionDetails + :return: AgentSessionResource. The AgentSessionResource is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentSessionResource :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_version_from_manifest( + def create_session( self, agent_name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AgentVersionDetails: - """Create a new agent version from a manifest. - - :param agent_name: The unique name that identifies the agent. Name can be used to - retrieve/update/delete the agent. + ) -> _models.AgentSessionResource: + """Creates a new session for an agent endpoint. The endpoint resolves the backing agent version + from ``version_indicator`` and enforces session ownership using the provided isolation key for + session-mutating operations. - * Must start and end with alphanumeric characters, - * Can contain hyphens in the middle - * Must not exceed 63 characters. Required. + :param agent_name: The name of the agent to create a session for. Required. :type agent_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: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentVersionDetails + :return: AgentSessionResource. The AgentSessionResource is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentSessionResource :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def create_version_from_manifest( + def create_session( self, agent_name: str, body: Union[JSON, IO[bytes]] = _Unset, *, - manifest_id: str = _Unset, - parameter_values: dict[str, Any] = _Unset, - metadata: Optional[dict[str, str]] = None, - description: Optional[str] = None, + version_indicator: _models.VersionIndicator = _Unset, + agent_session_id: Optional[str] = None, **kwargs: Any - ) -> _models.AgentVersionDetails: - """Create a new agent version from a manifest. - - :param agent_name: The unique name that identifies the agent. Name can be used to - retrieve/update/delete the agent. + ) -> _models.AgentSessionResource: + """Creates a new session for an agent endpoint. The endpoint resolves the backing agent version + from ``version_indicator`` and enforces session ownership using the provided isolation key for + session-mutating operations. - * Must start and end with alphanumeric characters, - * Can contain hyphens in the middle - * Must not exceed 63 characters. Required. + :param agent_name: The name of the agent to create a session for. Required. :type agent_name: str :param body: Is either a JSON type or a IO[bytes] type. Required. :type body: JSON or IO[bytes] - :keyword manifest_id: The manifest ID to import the agent version from. Required. - :paramtype manifest_id: str - :keyword parameter_values: The inputs to the manifest that will result in a fully materialized - Agent. Required. - :paramtype parameter_values: dict[str, any] - :keyword metadata: Set of 16 key-value pairs that can be attached to an object. This can be - useful for storing additional information about the object in a structured - format, and querying for objects via API or the dashboard. - - Keys are strings with a maximum length of 64 characters. Values are strings - with a maximum length of 512 characters. Default value is None. - :paramtype metadata: dict[str, str] - :keyword description: A human-readable description of the agent. Default value is None. - :paramtype description: str - :return: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentVersionDetails + :keyword version_indicator: Determines which agent version backs the session. Required. + :paramtype version_indicator: ~azure.ai.projects.models.VersionIndicator + :keyword agent_session_id: Optional caller-provided session ID. If specified, it must be unique + within the agent endpoint. Auto-generated if omitted. Default value is None. + :paramtype agent_session_id: str + :return: AgentSessionResource. The AgentSessionResource is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentSessionResource :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3299,19 +6930,12 @@ def create_version_from_manifest( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AgentVersionDetails] = kwargs.pop("cls", None) + cls: ClsType[_models.AgentSessionResource] = kwargs.pop("cls", None) if body is _Unset: - if manifest_id is _Unset: - raise TypeError("missing required argument: manifest_id") - if parameter_values is _Unset: - raise TypeError("missing required argument: parameter_values") - body = { - "description": description, - "manifest_id": manifest_id, - "metadata": metadata, - "parameter_values": parameter_values, - } + if version_indicator is _Unset: + raise TypeError("missing required argument: version_indicator") + body = {"agent_session_id": agent_session_id, "version_indicator": version_indicator} body = {k: v for k, v in body.items() if v is not None} content_type = content_type or "application/json" _content = None @@ -3320,7 +6944,7 @@ def create_version_from_manifest( else: _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_agents_create_version_from_manifest_request( + _request = build_beta_agents_create_session_request( agent_name=agent_name, content_type=content_type, api_version=self._config.api_version, @@ -3341,7 +6965,7 @@ def create_version_from_manifest( response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [201]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -3357,7 +6981,7 @@ def create_version_from_manifest( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.AgentVersionDetails, response.json()) + deserialized = _deserialize(_models.AgentSessionResource, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -3365,15 +6989,15 @@ def create_version_from_manifest( return deserialized # type: ignore @distributed_trace - def get_version(self, agent_name: str, agent_version: str, **kwargs: Any) -> _models.AgentVersionDetails: - """Retrieves a specific version of an agent. + def get_session(self, agent_name: str, session_id: str, **kwargs: Any) -> _models.AgentSessionResource: + """Retrieves a session by ID. - :param agent_name: The name of the agent to retrieve. Required. + :param agent_name: The name of the agent. Required. :type agent_name: str - :param agent_version: The version of the agent to retrieve. Required. - :type agent_version: str - :return: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentVersionDetails + :param session_id: The session identifier. Required. + :type session_id: str + :return: AgentSessionResource. The AgentSessionResource is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentSessionResource :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3387,11 +7011,11 @@ def get_version(self, agent_name: str, agent_version: str, **kwargs: Any) -> _mo _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.AgentVersionDetails] = kwargs.pop("cls", None) + cls: ClsType[_models.AgentSessionResource] = kwargs.pop("cls", None) - _request = build_agents_get_version_request( + _request = build_beta_agents_get_session_request( agent_name=agent_name, - agent_version=agent_version, + session_id=session_id, api_version=self._config.api_version, headers=_headers, params=_params, @@ -3425,7 +7049,7 @@ def get_version(self, agent_name: str, agent_version: str, **kwargs: Any) -> _mo if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.AgentVersionDetails, response.json()) + deserialized = _deserialize(_models.AgentSessionResource, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -3433,16 +7057,18 @@ def get_version(self, agent_name: str, agent_version: str, **kwargs: Any) -> _mo return deserialized # type: ignore @distributed_trace - def delete_version(self, agent_name: str, agent_version: str, **kwargs: Any) -> _models.DeleteAgentVersionResponse: - """Deletes a specific version of an agent. + def delete_session( # pylint: disable=inconsistent-return-statements + self, agent_name: str, session_id: str, **kwargs: Any + ) -> None: + """Deletes a session synchronously. Returns 204 No Content when the session is deleted or does not + exist. - :param agent_name: The name of the agent to delete. Required. + :param agent_name: The name of the agent. Required. :type agent_name: str - :param agent_version: The version of the agent to delete. Required. - :type agent_version: str - :return: DeleteAgentVersionResponse. The DeleteAgentVersionResponse is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.DeleteAgentVersionResponse + :param session_id: The session identifier. Required. + :type session_id: str + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3456,11 +7082,11 @@ def delete_version(self, agent_name: str, agent_version: str, **kwargs: Any) -> _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.DeleteAgentVersionResponse] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_agents_delete_version_request( + _request = build_beta_agents_delete_session_request( agent_name=agent_name, - agent_version=agent_version, + session_id=session_id, api_version=self._config.api_version, headers=_headers, params=_params, @@ -3470,39 +7096,26 @@ def delete_version(self, agent_name: str, agent_version: str, **kwargs: Any) -> } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _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 + if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize( _models.ApiErrorResponse, response, ) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.DeleteAgentVersionResponse, response.json()) + raise HttpResponseError(response=response, model=error) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def list_versions( + def list_sessions( self, agent_name: str, *, @@ -3510,10 +7123,10 @@ def list_versions( order: Optional[Union[str, _models.PageOrder]] = None, before: Optional[str] = None, **kwargs: Any - ) -> ItemPaged["_models.AgentVersionDetails"]: - """Returns the list of versions of an agent. + ) -> ItemPaged["_models.AgentSessionResource"]: + """Returns a list of sessions for the specified agent. - :param agent_name: The name of the agent to retrieve versions for. Required. + :param agent_name: The name of the agent. Required. :type agent_name: str :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the @@ -3529,14 +7142,14 @@ def list_versions( subsequent call can include before=obj_foo in order to fetch the previous page of the list. Default value is None. :paramtype before: str - :return: An iterator like instance of AgentVersionDetails - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.AgentVersionDetails] + :return: An iterator like instance of AgentSessionResource + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.AgentSessionResource] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.AgentVersionDetails]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.AgentSessionResource]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -3548,7 +7161,7 @@ def list_versions( def prepare_request(_continuation_token=None): - _request = build_agents_list_versions_request( + _request = build_beta_agents_list_sessions_request( agent_name=agent_name, limit=limit, order=order, @@ -3567,7 +7180,7 @@ def prepare_request(_continuation_token=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() list_of_elem = _deserialize( - List[_models.AgentVersionDetails], + List[_models.AgentSessionResource], deserialized.get("data", []), ) if cls: @@ -3595,32 +7208,45 @@ def get_next(_continuation_token=None): return ItemPaged(get_next, extract_data) + @distributed_trace + def get_session_log_stream( + self, agent_name: str, agent_version: str, session_id: str, **kwargs: Any + ) -> _models.SessionLogEvent: + """Streams console logs (stdout / stderr) for a specific hosted agent session + as a Server-Sent Events (SSE) stream. -class EvaluationRulesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. + Each SSE frame contains: - Instead, you should access the following operations through - :class:`~azure.ai.projects.AIProjectClient`'s - :attr:`evaluation_rules` attribute. - """ + * `event`: always `"log"` + * `data`: a plain-text log line (currently JSON-formatted, but the schema is not contractual and may include additional keys or change format over time; clients should treat it as an opaque string) - 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: AIProjectClientConfiguration = 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") + Example SSE frames: - @distributed_trace - def get(self, id: str, **kwargs: Any) -> _models.EvaluationRule: - """Get an evaluation rule. + .. code-block:: - :param id: Unique identifier for the evaluation rule. Required. - :type id: str - :return: EvaluationRule. The EvaluationRule is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationRule + event: log + data: {"timestamp":"2026-03-10T09:33:17.121Z","stream":"stdout","message":"Starting FoundryCBAgent server on port 8088"} + + event: log + data: {"timestamp":"2026-03-10T09:33:17.130Z","stream":"stderr","message":"INFO: Application startup complete."} + + event: log + data: {"timestamp":"2026-03-10T09:34:52.714Z","stream":"status","message":"Successfully connected to container"} + + event: log + data: {"timestamp":"2026-03-10T09:35:52.714Z","stream":"status","message":"No logs since last 60 seconds"} + + The stream remains open until the client disconnects or the server + terminates the connection. Clients should handle reconnection as needed. + + :param agent_name: The name of the hosted agent. Required. + :type agent_name: str + :param agent_version: The version of the agent. Required. + :type agent_version: str + :param session_id: The session ID (maps to an ADC sandbox). Required. + :type session_id: str + :return: SessionLogEvent. The SessionLogEvent is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.SessionLogEvent :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3634,10 +7260,12 @@ def get(self, id: str, **kwargs: Any) -> _models.EvaluationRule: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.EvaluationRule] = kwargs.pop("cls", None) + cls: ClsType[_models.SessionLogEvent] = kwargs.pop("cls", None) - _request = build_evaluation_rules_get_request( - id=id, + _request = build_beta_agents_get_session_log_stream_request( + agent_name=agent_name, + agent_version=agent_version, + session_id=session_id, api_version=self._config.api_version, headers=_headers, params=_params, @@ -3648,7 +7276,7 @@ def get(self, id: str, **kwargs: Any) -> _models.EvaluationRule: _request.url = self._client.format_url(_request.url, **path_format_arguments) _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _stream = True pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -3662,26 +7290,53 @@ def get(self, id: str, **kwargs: Any) -> _models.EvaluationRule: except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + response_headers = {} + response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.EvaluationRule, response.json()) + deserialized = _deserialize(_models.SessionLogEvent, response.text()) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore @distributed_trace - def delete(self, id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """Delete an evaluation rule. + def _upload_session_file( + self, + agent_name: str, + agent_session_id: str, + content: bytes, + *, + path: str, + user_isolation_key: Optional[str] = None, + **kwargs: Any + ) -> _models.SessionFileWriteResult: + """Upload a file to the session sandbox via binary stream. Maximum file size is 50 MB. Uploads + exceeding this limit return 413 Payload Too Large. - :param id: Unique identifier for the evaluation rule. Required. - :type id: str - :return: None - :rtype: None + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param agent_session_id: The session ID. Required. + :type agent_session_id: str + :param content: Required. + :type content: bytes + :keyword path: The destination file path within the sandbox, relative to the session home + directory. Required. + :paramtype path: str + :keyword user_isolation_key: Opaque per-user isolation key used to scope endpoint-scoped data + (responses, conversations, sessions) to a specific end user. Default value is None. + :paramtype user_isolation_key: str + :return: SessionFileWriteResult. The SessionFileWriteResult is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.SessionFileWriteResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3692,14 +7347,22 @@ def delete(self, id: str, **kwargs: Any) -> None: # pylint: disable=inconsisten } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/octet-stream")) + cls: ClsType[_models.SessionFileWriteResult] = kwargs.pop("cls", None) - _request = build_evaluation_rules_delete_request( - id=id, + _content = content + + _request = build_beta_agents_upload_session_file_request( + agent_name=agent_name, + agent_session_id=agent_session_id, + path=path, + user_isolation_key=user_isolation_key, + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -3708,87 +7371,143 @@ def delete(self, id: str, **kwargs: Any) -> None: # pylint: disable=inconsisten } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 [204]: + if response.status_code not in [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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.SessionFileWriteResult, response.json()) if cls: - return cls(pipeline_response, None, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - @overload - def create_or_update( - self, id: str, evaluation_rule: _models.EvaluationRule, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationRule: - """Create or update an evaluation rule. + return deserialized # type: ignore - :param id: Unique identifier for the evaluation rule. Required. - :type id: str - :param evaluation_rule: Evaluation rule resource. Required. - :type evaluation_rule: ~azure.ai.projects.models.EvaluationRule - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationRule. The EvaluationRule is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationRule + @distributed_trace + def download_session_file( + self, + agent_name: str, + agent_session_id: str, + *, + path: str, + user_isolation_key: Optional[str] = None, + **kwargs: Any + ) -> Iterator[bytes]: + """Download a file from the session sandbox as a binary stream. + + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param agent_session_id: The session ID. Required. + :type agent_session_id: str + :keyword path: The file path to download from the sandbox, relative to the session home + directory. Required. + :paramtype path: str + :keyword user_isolation_key: Opaque per-user isolation key used to scope endpoint-scoped data + (responses, conversations, sessions) to a specific end user. Default value is None. + :paramtype user_isolation_key: str + :return: Iterator[bytes] + :rtype: Iterator[bytes] :raises ~azure.core.exceptions.HttpResponseError: """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) - @overload - def create_or_update( - self, id: str, evaluation_rule: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationRule: - """Create or update an evaluation rule. + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - :param id: Unique identifier for the evaluation rule. Required. - :type id: str - :param evaluation_rule: Evaluation rule resource. Required. - :type evaluation_rule: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationRule. The EvaluationRule is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationRule - :raises ~azure.core.exceptions.HttpResponseError: - """ + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + + _request = build_beta_agents_download_session_file_request( + agent_name=agent_name, + agent_session_id=agent_session_id, + path=path, + user_isolation_key=user_isolation_key, + 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", 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]: + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) - @overload - def create_or_update( - self, id: str, evaluation_rule: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationRule: - """Create or update an evaluation rule. + deserialized = response.iter_bytes() if _decompress else response.iter_raw() - :param id: Unique identifier for the evaluation rule. Required. - :type id: str - :param evaluation_rule: Evaluation rule resource. Required. - :type evaluation_rule: 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: EvaluationRule. The EvaluationRule is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationRule - :raises ~azure.core.exceptions.HttpResponseError: - """ + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore @distributed_trace - def create_or_update( - self, id: str, evaluation_rule: Union[_models.EvaluationRule, JSON, IO[bytes]], **kwargs: Any - ) -> _models.EvaluationRule: - """Create or update an evaluation rule. + def get_session_files( + self, + agent_name: str, + agent_session_id: str, + *, + path: str, + user_isolation_key: Optional[str] = None, + **kwargs: Any + ) -> _models.SessionDirectoryListResult: + """List files and directories at a given path in the session sandbox. Returns only the immediate + children of the specified directory (non-recursive). - :param id: Unique identifier for the evaluation rule. Required. - :type id: str - :param evaluation_rule: Evaluation rule resource. Is one of the following types: - EvaluationRule, JSON, IO[bytes] Required. - :type evaluation_rule: ~azure.ai.projects.models.EvaluationRule or JSON or IO[bytes] - :return: EvaluationRule. The EvaluationRule is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationRule + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param agent_session_id: The session ID. Required. + :type agent_session_id: str + :keyword path: The directory path to list, relative to the session home directory. Required. + :paramtype path: str + :keyword user_isolation_key: Opaque per-user isolation key used to scope endpoint-scoped data + (responses, conversations, sessions) to a specific end user. Default value is None. + :paramtype user_isolation_key: str + :return: SessionDirectoryListResult. The SessionDirectoryListResult is compatible with + MutableMapping + :rtype: ~azure.ai.projects.models.SessionDirectoryListResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3799,24 +7518,17 @@ def create_or_update( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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.EvaluationRule] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(evaluation_rule, (IOBase, bytes)): - _content = evaluation_rule - else: - _content = json.dumps(evaluation_rule, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + cls: ClsType[_models.SessionDirectoryListResult] = kwargs.pop("cls", None) - _request = build_evaluation_rules_create_or_update_request( - id=id, - content_type=content_type, + _request = build_beta_agents_get_session_files_request( + agent_name=agent_name, + agent_session_id=agent_session_id, + path=path, + user_isolation_key=user_isolation_key, api_version=self._config.api_version, - content=_content, headers=_headers, params=_params, ) @@ -3833,19 +7545,23 @@ 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 except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.EvaluationRule, response.json()) + deserialized = _deserialize(_models.SessionDirectoryListResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -3853,32 +7569,36 @@ def create_or_update( return deserialized # type: ignore @distributed_trace - def list( + def delete_session_file( # pylint: disable=inconsistent-return-statements self, + agent_name: str, + agent_session_id: str, *, - action_type: Optional[Union[str, _models.EvaluationRuleActionType]] = None, - agent_name: Optional[str] = None, - enabled: Optional[bool] = None, + path: str, + recursive: Optional[bool] = None, + user_isolation_key: Optional[str] = None, **kwargs: Any - ) -> ItemPaged["_models.EvaluationRule"]: - """List all evaluation rules. + ) -> None: + """Delete a file or directory from the session sandbox. If ``recursive`` is false (default) and + the target is a non-empty directory, the API returns 409 Conflict. - :keyword action_type: Filter by the type of evaluation rule. Known values are: - "continuousEvaluation" and "humanEvaluationPreview". Default value is None. - :paramtype action_type: str or ~azure.ai.projects.models.EvaluationRuleActionType - :keyword agent_name: Filter by the agent name. Default value is None. - :paramtype agent_name: str - :keyword enabled: Filter by the enabled status. Default value is None. - :paramtype enabled: bool - :return: An iterator like instance of EvaluationRule - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.EvaluationRule] + :param agent_name: The name of the agent. Required. + :type agent_name: str + :param agent_session_id: The session ID. Required. + :type agent_session_id: str + :keyword path: The file or directory path to delete, relative to the session home directory. + Required. + :paramtype path: str + :keyword recursive: Whether to recursively delete directory contents. Defaults to false. + Default value is None. + :paramtype recursive: bool + :keyword user_isolation_key: Opaque per-user isolation key used to scope endpoint-scoped data + (responses, conversations, sessions) to a specific end user. Default value is None. + :paramtype user_isolation_key: str + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.EvaluationRule]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -3887,99 +7607,137 @@ def list( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - _request = build_evaluation_rules_list_request( - action_type=action_type, - agent_name=agent_name, - enabled=enabled, - 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) + cls: ClsType[None] = kwargs.pop("cls", None) - 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) + _request = build_beta_agents_delete_session_file_request( + agent_name=agent_name, + agent_session_id=agent_session_id, + path=path, + recursive=recursive, + user_isolation_key=user_isolation_key, + 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) - return _request + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize( - List[_models.EvaluationRule], - deserialized.get("value", []), + response = pipeline_response.http_response + + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, ) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("nextLink") or None, iter(list_of_elem) + raise HttpResponseError(response=response, model=error) - def get_next(next_link=None): - _request = prepare_request(next_link) + if cls: + return cls(pipeline_response, None, {}) # type: ignore - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response + @overload + def create_optimization_job( + self, + job: _models.OptimizationJob, + *, + operation_id: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.OptimizationJob: + """Creates an agent optimization job. - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + Create an optimization job. Returns 201 with the queued job. Honours ``Operation-Id`` for + idempotent retry. - return pipeline_response + :param job: The job to create. Required. + :type job: ~azure.ai.projects.models.OptimizationJob + :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the + server creates the job unconditionally. Default value is None. + :paramtype operation_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: OptimizationJob. The OptimizationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.OptimizationJob + :raises ~azure.core.exceptions.HttpResponseError: + """ - return ItemPaged(get_next, extract_data) + @overload + def create_optimization_job( + self, job: JSON, *, operation_id: Optional[str] = None, content_type: str = "application/json", **kwargs: Any + ) -> _models.OptimizationJob: + """Creates an agent optimization job. + Create an optimization job. Returns 201 with the queued job. Honours ``Operation-Id`` for + idempotent retry. -class ConnectionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. + :param job: The job to create. Required. + :type job: JSON + :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the + server creates the job unconditionally. Default value is None. + :paramtype operation_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: OptimizationJob. The OptimizationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.OptimizationJob + :raises ~azure.core.exceptions.HttpResponseError: + """ - Instead, you should access the following operations through - :class:`~azure.ai.projects.AIProjectClient`'s - :attr:`connections` attribute. - """ + @overload + def create_optimization_job( + self, + job: IO[bytes], + *, + operation_id: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.OptimizationJob: + """Creates an agent optimization job. - 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: AIProjectClientConfiguration = 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") + Create an optimization job. Returns 201 with the queued job. Honours ``Operation-Id`` for + idempotent retry. + + :param job: The job to create. Required. + :type job: IO[bytes] + :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the + server creates the job unconditionally. Default value is None. + :paramtype operation_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: OptimizationJob. The OptimizationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.OptimizationJob + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace - def _get(self, name: str, **kwargs: Any) -> _models.Connection: - """Get a connection by name, without populating connection credentials. + def create_optimization_job( + self, job: Union[_models.OptimizationJob, JSON, IO[bytes]], *, operation_id: Optional[str] = None, **kwargs: Any + ) -> _models.OptimizationJob: + """Creates an agent optimization job. - :param name: The friendly name of the connection, provided by the user. Required. - :type name: str - :return: Connection. The Connection is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Connection + Create an optimization job. Returns 201 with the queued job. Honours ``Operation-Id`` for + idempotent retry. + + :param job: The job to create. Is one of the following types: OptimizationJob, JSON, IO[bytes] + Required. + :type job: ~azure.ai.projects.models.OptimizationJob or JSON or IO[bytes] + :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the + server creates the job unconditionally. Default value is None. + :paramtype operation_id: str + :return: OptimizationJob. The OptimizationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.OptimizationJob :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -3990,14 +7748,24 @@ def _get(self, name: str, **kwargs: Any) -> _models.Connection: } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.Connection] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.OptimizationJob] = kwargs.pop("cls", None) - _request = build_connections_get_request( - name=name, + content_type = content_type or "application/json" + _content = None + if isinstance(job, (IOBase, bytes)): + _content = job + else: + _content = json.dumps(job, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_beta_agents_create_optimization_job_request( + operation_id=operation_id, + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -4014,24 +7782,27 @@ def _get(self, name: str, **kwargs: Any) -> _models.Connection: response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) response_headers = {} - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) + response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.Connection, response.json()) + deserialized = _deserialize(_models.OptimizationJob, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -4039,13 +7810,15 @@ def _get(self, name: str, **kwargs: Any) -> _models.Connection: return deserialized # type: ignore @distributed_trace - def _get_with_credentials(self, name: str, **kwargs: Any) -> _models.Connection: - """Get a connection by name, with its connection credentials. + def get_optimization_job(self, job_id: str, **kwargs: Any) -> _models.OptimizationJob: + """Get info about an agent optimization job. - :param name: The friendly name of the connection, provided by the user. Required. - :type name: str - :return: Connection. The Connection is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Connection + Get an optimization job by id. Emits ``Retry-After`` while the job is non-terminal. + + :param job_id: The ID of the job. Required. + :type job_id: str + :return: OptimizationJob. The OptimizationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.OptimizationJob :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4059,10 +7832,10 @@ def _get_with_credentials(self, name: str, **kwargs: Any) -> _models.Connection: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.Connection] = kwargs.pop("cls", None) + cls: ClsType[_models.OptimizationJob] = kwargs.pop("cls", None) - _request = build_connections_get_with_credentials_request( - name=name, + _request = build_beta_agents_get_optimization_job_request( + job_id=job_id, api_version=self._config.api_version, headers=_headers, params=_params, @@ -4087,17 +7860,19 @@ def _get_with_credentials(self, name: str, **kwargs: Any) -> _models.Connection: except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) response_headers = {} - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.Connection, response.json()) + deserialized = _deserialize(_models.OptimizationJob, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -4105,30 +7880,48 @@ def _get_with_credentials(self, name: str, **kwargs: Any) -> _models.Connection: return deserialized # type: ignore @distributed_trace - def list( + def list_optimization_jobs( self, *, - connection_type: Optional[Union[str, _models.ConnectionType]] = None, - default_connection: Optional[bool] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + before: Optional[str] = None, + status: Optional[Union[str, _models.JobStatus]] = None, + agent_name: Optional[str] = None, **kwargs: Any - ) -> ItemPaged["_models.Connection"]: - """List all connections in the project, without populating connection credentials. + ) -> ItemPaged["_models.OptimizationJob"]: + """Returns a list of agent optimization jobs. - :keyword connection_type: List connections of this specific type. Known values are: - "AzureOpenAI", "AzureBlob", "AzureStorageAccount", "CognitiveSearch", "CosmosDB", "ApiKey", - "AppConfig", "AppInsights", "CustomKeys", and "RemoteTool_Preview". Default value is None. - :paramtype connection_type: str or ~azure.ai.projects.models.ConnectionType - :keyword default_connection: List connections that are default connections. Default value is - None. - :paramtype default_connection: bool - :return: An iterator like instance of Connection - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.Connection] + List optimization jobs. Supports cursor pagination and optional ``status`` / ``agent_name`` + filters. + + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :keyword status: Filter to jobs in this lifecycle state. Known values are: "queued", + "in_progress", "succeeded", "failed", and "cancelled". Default value is None. + :paramtype status: str or ~azure.ai.projects.models.JobStatus + :keyword agent_name: Filter to jobs targeting this agent name. Default value is None. + :paramtype agent_name: str + :return: An iterator like instance of OptimizationJob + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.OptimizationJob] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.Connection]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.OptimizationJob]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -4138,57 +7931,37 @@ def list( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: - - _request = build_connections_list_request( - connection_type=connection_type, - default_connection=default_connection, - 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) + def prepare_request(_continuation_token=None): + _request = build_beta_agents_list_optimization_jobs_request( + limit=limit, + order=order, + after=_continuation_token, + before=before, + status=status, + agent_name=agent_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) return _request def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() list_of_elem = _deserialize( - List[_models.Connection], - deserialized.get("value", []), + List[_models.OptimizationJob], + deserialized.get("data", []), ) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("nextLink") or None, iter(list_of_elem) + return deserialized.get("last_id") or None, iter(list_of_elem) - def get_next(next_link=None): - _request = prepare_request(next_link) + def get_next(_continuation_token=None): + _request = prepare_request(_continuation_token) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access @@ -4198,45 +7971,181 @@ def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def cancel_optimization_job(self, job_id: str, **kwargs: Any) -> _models.OptimizationJob: + """Cancels an agent optimization job. + + Request cancellation. Idempotent on terminal states. + + :param job_id: The ID of the job to cancel. Required. + :type job_id: str + :return: OptimizationJob. The OptimizationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.OptimizationJob + :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.OptimizationJob] = kwargs.pop("cls", None) + + _request = build_beta_agents_cancel_optimization_job_request( + job_id=job_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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.OptimizationJob, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete_optimization_job( # pylint: disable=inconsistent-return-statements + self, job_id: str, **kwargs: Any + ) -> None: + """Deletes an agent optimization job. + + Delete the job and its candidate artifacts. Cancels first if non-terminal. + + :param job_id: The ID of the job to delete. Required. + :type job_id: str + :return: None + :rtype: None + :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 {} - return pipeline_response + cls: ClsType[None] = kwargs.pop("cls", None) - return ItemPaged(get_next, extract_data) + _request = build_beta_agents_delete_optimization_job_request( + job_id=job_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) + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) -class DatasetsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. + response = pipeline_response.http_response - Instead, you should access the following operations through - :class:`~azure.ai.projects.AIProjectClient`'s - :attr:`datasets` attribute. - """ + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) - 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: AIProjectClientConfiguration = 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") + if cls: + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def list_versions(self, name: str, **kwargs: Any) -> ItemPaged["_models.DatasetVersion"]: - """List all versions of the given DatasetVersion. + def list_optimization_candidates( + self, + job_id: str, + *, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + after: Optional[str] = None, + before: Optional[str] = None, + **kwargs: Any + ) -> _models.AgentsPagedResultOptimizationCandidate: + """Returns a list of candidates for an optimization job. - :param name: The name of the resource. Required. - :type name: str - :return: An iterator like instance of DatasetVersion - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.DatasetVersion] + List candidates produced by a job. + + :param job_id: The optimization job id. Required. + :type job_id: str + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword after: A cursor for use in pagination. ``after`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include after=obj_foo in order to fetch the next page of the list. Default + value is None. + :paramtype after: str + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :return: AgentsPagedResultOptimizationCandidate. The AgentsPagedResultOptimizationCandidate is + compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentsPagedResultOptimizationCandidate :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.DatasetVersion]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -4245,84 +8154,73 @@ def list_versions(self, name: str, **kwargs: Any) -> ItemPaged["_models.DatasetV } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: - - _request = build_datasets_list_versions_request( - name=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) + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - 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) + cls: ClsType[_models.AgentsPagedResultOptimizationCandidate] = kwargs.pop("cls", None) - return _request + _request = build_beta_agents_list_optimization_candidates_request( + job_id=job_id, + limit=limit, + order=order, + after=after, + before=before, + 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) - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize( - List[_models.DatasetVersion], - deserialized.get("value", []), - ) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("nextLink") or None, iter(list_of_elem) + _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 + ) - def get_next(next_link=None): - _request = prepare_request(next_link) + response = pipeline_response.http_response - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, ) - response = pipeline_response.http_response + raise HttpResponseError(response=response, model=error) - if response.status_code not in [200]: - 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.AgentsPagedResultOptimizationCandidate, response.json()) - return pipeline_response + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - return ItemPaged(get_next, extract_data) + return deserialized # type: ignore @distributed_trace - def list(self, **kwargs: Any) -> ItemPaged["_models.DatasetVersion"]: - """List the latest version of each DatasetVersion. + def get_optimization_candidate( + self, job_id: str, candidate_id: str, **kwargs: Any + ) -> _models.OptimizationCandidate: + """Get a candidate by id. - :return: An iterator like instance of DatasetVersion - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.DatasetVersion] + Get a single candidate manifest and aggregated evaluation summary. + + :param job_id: The optimization job id. Required. + :type job_id: str + :param candidate_id: The candidate id. Required. + :type candidate_id: str + :return: OptimizationCandidate. The OptimizationCandidate is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.OptimizationCandidate :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.DatasetVersion]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -4331,81 +8229,141 @@ def list(self, **kwargs: Any) -> ItemPaged["_models.DatasetVersion"]: } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - _request = build_datasets_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) + cls: ClsType[_models.OptimizationCandidate] = kwargs.pop("cls", None) - 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) + _request = build_beta_agents_get_optimization_candidate_request( + job_id=job_id, + candidate_id=candidate_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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.OptimizationCandidate, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get_optimization_candidate_config( + self, job_id: str, candidate_id: str, **kwargs: Any + ) -> _models.CandidateDeployConfig: + """Get candidate deploy config. + + Get the candidate's deploy config JSON. Used to compose ``agents.create_version(...)`` from a + candidate. + + :param job_id: The optimization job id. Required. + :type job_id: str + :param candidate_id: The candidate id. Required. + :type candidate_id: str + :return: CandidateDeployConfig. The CandidateDeployConfig is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.CandidateDeployConfig + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) - return _request + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize( - List[_models.DatasetVersion], - deserialized.get("value", []), - ) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("nextLink") or None, iter(list_of_elem) + cls: ClsType[_models.CandidateDeployConfig] = kwargs.pop("cls", None) - def get_next(next_link=None): - _request = prepare_request(next_link) + _request = build_beta_agents_get_optimization_candidate_config_request( + job_id=job_id, + candidate_id=candidate_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) - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs + _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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, ) - response = pipeline_response.http_response + raise HttpResponseError(response=response, model=error) - if response.status_code not in [200]: - 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.CandidateDeployConfig, response.json()) - return pipeline_response + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - return ItemPaged(get_next, extract_data) + return deserialized # type: ignore @distributed_trace - def get(self, name: str, version: str, **kwargs: Any) -> _models.DatasetVersion: - """Get the specific version of the DatasetVersion. The service returns 404 Not Found error if the - DatasetVersion does not exist. + def get_optimization_candidate_results( + self, job_id: str, candidate_id: str, **kwargs: Any + ) -> _models.CandidateResults: + """Get candidate evaluation results. - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the DatasetVersion to retrieve. Required. - :type version: str - :return: DatasetVersion. The DatasetVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.DatasetVersion + Get full per-task evaluation results for a candidate. + + :param job_id: The optimization job id. Required. + :type job_id: str + :param candidate_id: The candidate id. Required. + :type candidate_id: str + :return: CandidateResults. The CandidateResults is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.CandidateResults :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4419,11 +8377,11 @@ def get(self, name: str, version: str, **kwargs: Any) -> _models.DatasetVersion: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.DatasetVersion] = kwargs.pop("cls", None) + cls: ClsType[_models.CandidateResults] = kwargs.pop("cls", None) - _request = build_datasets_get_request( - name=name, - version=version, + _request = build_beta_agents_get_optimization_candidate_results_request( + job_id=job_id, + candidate_id=candidate_id, api_version=self._config.api_version, headers=_headers, params=_params, @@ -4448,29 +8406,48 @@ def get(self, name: str, version: str, **kwargs: Any) -> _models.DatasetVersion: except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.DatasetVersion, response.json()) + deserialized = _deserialize(_models.CandidateResults, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + +class BetaEvaluationTaxonomiesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.AIProjectClient`'s + :attr:`evaluation_taxonomies` 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: AIProjectClientConfiguration = 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 delete(self, name: str, version: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """Delete the specific version of the DatasetVersion. The service returns 204 No Content if the - DatasetVersion was deleted successfully or if the DatasetVersion does not exist. + def get(self, name: str, **kwargs: Any) -> _models.EvaluationTaxonomy: + """Get an evaluation run by name. :param name: The name of the resource. Required. :type name: str - :param version: The version of the DatasetVersion to delete. Required. - :type version: str - :return: None - :rtype: None + :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationTaxonomy :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4484,11 +8461,10 @@ def delete(self, name: str, version: str, **kwargs: Any) -> None: # pylint: dis _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models.EvaluationTaxonomy] = kwargs.pop("cls", None) - _request = build_datasets_delete_request( + _request = build_beta_evaluation_taxonomies_get_request( name=name, - version=version, api_version=self._config.api_version, headers=_headers, params=_params, @@ -4498,113 +8474,137 @@ def delete(self, name: str, version: str, **kwargs: Any) -> None: # pylint: dis } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 [204]: + 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.EvaluationTaxonomy, response.json()) + if cls: - return cls(pipeline_response, None, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore - @overload - def create_or_update( - self, - name: str, - version: str, - dataset_version: _models.DatasetVersion, - *, - content_type: str = "application/merge-patch+json", - **kwargs: Any - ) -> _models.DatasetVersion: - """Create a new or update an existing DatasetVersion with the given version id. + return deserialized # type: ignore - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the DatasetVersion to create or update. Required. - :type version: str - :param dataset_version: The DatasetVersion to create or update. Required. - :type dataset_version: ~azure.ai.projects.models.DatasetVersion - :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: DatasetVersion. The DatasetVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.DatasetVersion + @distributed_trace + def list( + self, *, input_name: Optional[str] = None, input_type: Optional[str] = None, **kwargs: Any + ) -> ItemPaged["_models.EvaluationTaxonomy"]: + """List evaluation taxonomies. + + :keyword input_name: Filter by the evaluation input name. Default value is None. + :paramtype input_name: str + :keyword input_type: Filter by taxonomy input type. Default value is None. + :paramtype input_type: str + :return: An iterator like instance of EvaluationTaxonomy + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.EvaluationTaxonomy] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - @overload - def create_or_update( - self, - name: str, - version: str, - dataset_version: JSON, - *, - content_type: str = "application/merge-patch+json", - **kwargs: Any - ) -> _models.DatasetVersion: - """Create a new or update an existing DatasetVersion with the given version id. + cls: ClsType[List[_models.EvaluationTaxonomy]] = 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_beta_evaluation_taxonomies_list_request( + input_name=input_name, + input_type=input_type, + 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, + headers=_headers, + ) + 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.EvaluationTaxonomy], + 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 - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the DatasetVersion to create or update. Required. - :type version: str - :param dataset_version: The DatasetVersion to create or update. Required. - :type dataset_version: 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: DatasetVersion. The DatasetVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.DatasetVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) - @overload - def create_or_update( - self, - name: str, - version: str, - dataset_version: IO[bytes], - *, - content_type: str = "application/merge-patch+json", - **kwargs: Any - ) -> _models.DatasetVersion: - """Create a new or update an existing DatasetVersion with the given version id. + return pipeline_response - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the DatasetVersion to create or update. Required. - :type version: str - :param dataset_version: The DatasetVersion to create or update. Required. - :type dataset_version: 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: DatasetVersion. The DatasetVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.DatasetVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ + return ItemPaged(get_next, extract_data) @distributed_trace - def create_or_update( - self, name: str, version: str, dataset_version: Union[_models.DatasetVersion, JSON, IO[bytes]], **kwargs: Any - ) -> _models.DatasetVersion: - """Create a new or update an existing DatasetVersion with the given version id. + def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete an evaluation taxonomy by name. :param name: The name of the resource. Required. :type name: str - :param version: The specific version id of the DatasetVersion to create or update. Required. - :type version: str - :param dataset_version: The DatasetVersion to create or update. Is one of the following types: - DatasetVersion, JSON, IO[bytes] Required. - :type dataset_version: ~azure.ai.projects.models.DatasetVersion or JSON or IO[bytes] - :return: DatasetVersion. The DatasetVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.DatasetVersion + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4615,25 +8615,14 @@ def create_or_update( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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.DatasetVersion] = kwargs.pop("cls", None) - - content_type = content_type or "application/merge-patch+json" - _content = None - if isinstance(dataset_version, (IOBase, bytes)): - _content = dataset_version - else: - _content = json.dumps(dataset_version, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_datasets_create_or_update_request( + _request = build_beta_evaluation_taxonomies_delete_request( name=name, - version=version, - content_type=content_type, api_version=self._config.api_version, - content=_content, headers=_headers, params=_params, ) @@ -4642,205 +8631,87 @@ def create_or_update( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _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 + if response.status_code not in [204]: 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.DatasetVersion, response.json()) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore + return cls(pipeline_response, None, {}) # type: ignore @overload - def pending_upload( - self, - name: str, - version: str, - pending_upload_request: _models.PendingUploadRequest, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PendingUploadResult: - """Start a new or get an existing pending upload of a dataset for a specific version. + def create( + self, name: str, taxonomy: _models.EvaluationTaxonomy, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluationTaxonomy: + """Create an evaluation taxonomy. - :param name: The name of the resource. Required. + :param name: The name of the evaluation taxonomy. Required. :type name: str - :param version: The specific version id of the DatasetVersion to operate on. Required. - :type version: str - :param pending_upload_request: The pending upload request parameters. Required. - :type pending_upload_request: ~azure.ai.projects.models.PendingUploadRequest + :param taxonomy: The evaluation taxonomy. Required. + :type taxonomy: ~azure.ai.projects.models.EvaluationTaxonomy :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: PendingUploadResult. The PendingUploadResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.PendingUploadResult + :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationTaxonomy :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def pending_upload( - self, - name: str, - version: str, - pending_upload_request: JSON, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PendingUploadResult: - """Start a new or get an existing pending upload of a dataset for a specific version. + def create( + self, name: str, taxonomy: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluationTaxonomy: + """Create an evaluation taxonomy. - :param name: The name of the resource. Required. + :param name: The name of the evaluation taxonomy. Required. :type name: str - :param version: The specific version id of the DatasetVersion to operate on. Required. - :type version: str - :param pending_upload_request: The pending upload request parameters. Required. - :type pending_upload_request: JSON + :param taxonomy: The evaluation taxonomy. Required. + :type taxonomy: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: PendingUploadResult. The PendingUploadResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.PendingUploadResult + :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationTaxonomy :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def pending_upload( - self, - name: str, - version: str, - pending_upload_request: IO[bytes], - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.PendingUploadResult: - """Start a new or get an existing pending upload of a dataset for a specific version. + def create( + self, name: str, taxonomy: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluationTaxonomy: + """Create an evaluation taxonomy. - :param name: The name of the resource. Required. + :param name: The name of the evaluation taxonomy. Required. :type name: str - :param version: The specific version id of the DatasetVersion to operate on. Required. - :type version: str - :param pending_upload_request: The pending upload request parameters. Required. - :type pending_upload_request: IO[bytes] + :param taxonomy: The evaluation taxonomy. Required. + :type taxonomy: 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: PendingUploadResult. The PendingUploadResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.PendingUploadResult - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def pending_upload( - self, - name: str, - version: str, - pending_upload_request: Union[_models.PendingUploadRequest, JSON, IO[bytes]], - **kwargs: Any - ) -> _models.PendingUploadResult: - """Start a new or get an existing pending upload of a dataset for a specific version. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the DatasetVersion to operate on. Required. - :type version: str - :param pending_upload_request: The pending upload request parameters. Is one of the following - types: PendingUploadRequest, JSON, IO[bytes] Required. - :type pending_upload_request: ~azure.ai.projects.models.PendingUploadRequest or JSON or - IO[bytes] - :return: PendingUploadResult. The PendingUploadResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.PendingUploadResult + :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationTaxonomy :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.PendingUploadResult] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(pending_upload_request, (IOBase, bytes)): - _content = pending_upload_request - else: - _content = json.dumps(pending_upload_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_datasets_pending_upload_request( - name=name, - version=version, - 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]: - 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.PendingUploadResult, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore + """ @distributed_trace - def get_credentials(self, name: str, version: str, **kwargs: Any) -> _models.DatasetCredential: - """Get the SAS credential to access the storage account associated with a Dataset version. + def create( + self, name: str, taxonomy: Union[_models.EvaluationTaxonomy, JSON, IO[bytes]], **kwargs: Any + ) -> _models.EvaluationTaxonomy: + """Create an evaluation taxonomy. - :param name: The name of the resource. Required. + :param name: The name of the evaluation taxonomy. Required. :type name: str - :param version: The specific version id of the DatasetVersion to operate on. Required. - :type version: str - :return: DatasetCredential. The DatasetCredential is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.DatasetCredential + :param taxonomy: The evaluation taxonomy. Is one of the following types: EvaluationTaxonomy, + JSON, IO[bytes] Required. + :type taxonomy: ~azure.ai.projects.models.EvaluationTaxonomy or JSON or IO[bytes] + :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationTaxonomy :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4851,15 +8722,24 @@ def get_credentials(self, name: str, version: str, **kwargs: Any) -> _models.Dat } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.DatasetCredential] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.EvaluationTaxonomy] = kwargs.pop("cls", None) - _request = build_datasets_get_credentials_request( + content_type = content_type or "application/json" + _content = None + if isinstance(taxonomy, (IOBase, bytes)): + _content = taxonomy + else: + _content = json.dumps(taxonomy, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_beta_evaluation_taxonomies_create_request( name=name, - version=version, + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -4876,7 +8756,7 @@ def get_credentials(self, name: str, version: str, **kwargs: Any) -> _models.Dat response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [200, 201]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -4888,39 +8768,80 @@ def get_credentials(self, name: str, version: str, **kwargs: Any) -> _models.Dat if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.DatasetCredential, response.json()) + deserialized = _deserialize(_models.EvaluationTaxonomy, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + @overload + def update( + self, name: str, taxonomy: _models.EvaluationTaxonomy, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluationTaxonomy: + """Update an evaluation taxonomy. -class DeploymentsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. + :param name: The name of the evaluation taxonomy. Required. + :type name: str + :param taxonomy: The evaluation taxonomy. Required. + :type taxonomy: ~azure.ai.projects.models.EvaluationTaxonomy + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationTaxonomy + :raises ~azure.core.exceptions.HttpResponseError: + """ - Instead, you should access the following operations through - :class:`~azure.ai.projects.AIProjectClient`'s - :attr:`deployments` attribute. - """ + @overload + def update( + self, name: str, taxonomy: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluationTaxonomy: + """Update an evaluation taxonomy. - 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: AIProjectClientConfiguration = 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") + :param name: The name of the evaluation taxonomy. Required. + :type name: str + :param taxonomy: The evaluation taxonomy. Required. + :type taxonomy: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationTaxonomy + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update( + self, name: str, taxonomy: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluationTaxonomy: + """Update an evaluation taxonomy. + + :param name: The name of the evaluation taxonomy. Required. + :type name: str + :param taxonomy: The evaluation taxonomy. Required. + :type taxonomy: 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: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationTaxonomy + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace - def get(self, name: str, **kwargs: Any) -> _models.Deployment: - """Get a deployed model. + def update( + self, name: str, taxonomy: Union[_models.EvaluationTaxonomy, JSON, IO[bytes]], **kwargs: Any + ) -> _models.EvaluationTaxonomy: + """Update an evaluation taxonomy. - :param name: Name of the deployment. Required. + :param name: The name of the evaluation taxonomy. Required. :type name: str - :return: Deployment. The Deployment is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Deployment + :param taxonomy: The evaluation taxonomy. Is one of the following types: EvaluationTaxonomy, + JSON, IO[bytes] Required. + :type taxonomy: ~azure.ai.projects.models.EvaluationTaxonomy or JSON or IO[bytes] + :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluationTaxonomy :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -4931,14 +8852,24 @@ def get(self, name: str, **kwargs: Any) -> _models.Deployment: } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.Deployment] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.EvaluationTaxonomy] = kwargs.pop("cls", None) - _request = build_deployments_get_request( + content_type = content_type or "application/json" + _content = None + if isinstance(taxonomy, (IOBase, bytes)): + _content = taxonomy + else: + _content = json.dumps(taxonomy, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_beta_evaluation_taxonomies_update_request( name=name, + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -4951,146 +8882,38 @@ def get(self, name: str, **kwargs: Any) -> _models.Deployment: _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) - - response_headers = {} - response_headers["x-ms-client-request-id"] = self._deserialize( - "str", response.headers.get("x-ms-client-request-id") - ) - - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.Deployment, response.json()) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, - *, - model_publisher: Optional[str] = None, - model_name: Optional[str] = None, - deployment_type: Optional[Union[str, _models.DeploymentType]] = None, - **kwargs: Any - ) -> ItemPaged["_models.Deployment"]: - """List all deployed models in the project. - - :keyword model_publisher: Model publisher to filter models by. Default value is None. - :paramtype model_publisher: str - :keyword model_name: Model name (the publisher specific name) to filter models by. Default - value is None. - :paramtype model_name: str - :keyword deployment_type: Type of deployment to filter list by. "ModelDeployment" Default value - is None. - :paramtype deployment_type: str or ~azure.ai.projects.models.DeploymentType - :return: An iterator like instance of Deployment - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.Deployment] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.Deployment]] = 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_deployments_list_request( - model_publisher=model_publisher, - model_name=model_name, - deployment_type=deployment_type, - 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.Deployment], - 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) + response = pipeline_response.http_response - return pipeline_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) - return ItemPaged(get_next, extract_data) + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.EvaluationTaxonomy, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized # type: ignore -class IndexesOperations: + +class BetaEvaluatorsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.ai.projects.AIProjectClient`'s - :attr:`indexes` attribute. + :attr:`evaluators` attribute. """ def __init__(self, *args, **kwargs) -> None: @@ -5101,19 +8924,33 @@ def __init__(self, *args, **kwargs) -> None: self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def list_versions(self, name: str, **kwargs: Any) -> ItemPaged["_models.Index"]: - """List all versions of the given Index. + def list_versions( + self, + name: str, + *, + type: Optional[Union[Literal["builtin"], Literal["custom"], Literal["all"], str]] = None, + limit: Optional[int] = None, + **kwargs: Any + ) -> ItemPaged["_models.EvaluatorVersion"]: + """List all versions of the given evaluator. :param name: The name of the resource. Required. :type name: str - :return: An iterator like instance of Index - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.Index] + :keyword type: Filter evaluators by type. Possible values: 'all', 'custom', 'builtin'. Is one + of the following types: Literal["builtin"], Literal["custom"], Literal["all"], str Default + value is None. + :paramtype type: str or str or str or str + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. Default value is None. + :paramtype limit: int + :return: An iterator like instance of EvaluatorVersion + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.EvaluatorVersion] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.Index]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.EvaluatorVersion]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -5126,8 +8963,10 @@ def list_versions(self, name: str, **kwargs: Any) -> ItemPaged["_models.Index"]: def prepare_request(next_link=None): if not next_link: - _request = build_indexes_list_versions_request( + _request = build_beta_evaluators_list_versions_request( name=name, + type=type, + limit=limit, api_version=self._config.api_version, headers=_headers, params=_params, @@ -5150,92 +8989,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 - ) - 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.Index], - 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 list(self, **kwargs: Any) -> ItemPaged["_models.Index"]: - """List the latest version of each Index. - - :return: An iterator like instance of Index - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.Index] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.Index]] = 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_indexes_list_request( - api_version=self._config.api_version, + "GET", + urllib.parse.urljoin(next_link, _parsed_next_link.path), + params=_next_request_params, 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( @@ -5249,7 +9006,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() list_of_elem = _deserialize( - List[_models.Index], + List[_models.EvaluatorVersion], deserialized.get("value", []), ) if cls: @@ -5274,209 +9031,119 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) @distributed_trace - def get(self, name: str, version: str, **kwargs: Any) -> _models.Index: - """Get the specific version of the Index. The service returns 404 Not Found error if the Index - does not exist. - - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the Index to retrieve. Required. - :type version: str - :return: Index. The Index is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Index - :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.Index] = kwargs.pop("cls", None) - - _request = build_indexes_get_request( - name=name, - version=version, - 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.Index, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete(self, name: str, version: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """Delete the specific version of the Index. The service returns 204 No Content if the Index was - deleted successfully or if the Index does not exist. + def list( + self, + *, + type: Optional[Union[Literal["builtin"], Literal["custom"], Literal["all"], str]] = None, + limit: Optional[int] = None, + **kwargs: Any + ) -> ItemPaged["_models.EvaluatorVersion"]: + """List the latest version of each evaluator. - :param name: The name of the resource. Required. - :type name: str - :param version: The version of the Index to delete. Required. - :type version: str - :return: None - :rtype: None + :keyword type: Filter evaluators by type. Possible values: 'all', 'custom', 'builtin'. Is one + of the following types: Literal["builtin"], Literal["custom"], Literal["all"], str Default + value is None. + :paramtype type: str or str or str or str + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the default is 20. Default value is None. + :paramtype limit: int + :return: An iterator like instance of EvaluatorVersion + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.EvaluatorVersion] :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[None] = kwargs.pop("cls", None) + cls: ClsType[List[_models.EvaluatorVersion]] = kwargs.pop("cls", None) - _request = build_indexes_delete_request( - name=name, - version=version, - 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), + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + error_map.update(kwargs.pop("error_map", {}) or {}) - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + def prepare_request(next_link=None): + if not next_link: - response = pipeline_response.http_response + _request = build_beta_evaluators_list_request( + type=type, + limit=limit, + 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) - if response.status_code not in [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + 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, + headers=_headers, + ) + 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) - if cls: - return cls(pipeline_response, None, {}) # type: ignore + return _request - @overload - def create_or_update( - self, - name: str, - version: str, - index: _models.Index, - *, - content_type: str = "application/merge-patch+json", - **kwargs: Any - ) -> _models.Index: - """Create a new or update an existing Index with the given version id. + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.EvaluatorVersion], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the Index to create or update. Required. - :type version: str - :param index: The Index to create or update. Required. - :type index: ~azure.ai.projects.models.Index - :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: Index. The Index is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Index - :raises ~azure.core.exceptions.HttpResponseError: - """ + def get_next(next_link=None): + _request = prepare_request(next_link) - @overload - def create_or_update( - self, name: str, version: str, index: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any - ) -> _models.Index: - """Create a new or update an existing Index with the given version id. + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the Index to create or update. Required. - :type version: str - :param index: The Index to create or update. Required. - :type index: 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: Index. The Index is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Index - :raises ~azure.core.exceptions.HttpResponseError: - """ + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) - @overload - def create_or_update( - self, - name: str, - version: str, - index: IO[bytes], - *, - content_type: str = "application/merge-patch+json", - **kwargs: Any - ) -> _models.Index: - """Create a new or update an existing Index with the given version id. + return pipeline_response - :param name: The name of the resource. Required. - :type name: str - :param version: The specific version id of the Index to create or update. Required. - :type version: str - :param index: The Index to create or update. Required. - :type index: 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: Index. The Index is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Index - :raises ~azure.core.exceptions.HttpResponseError: - """ + return ItemPaged(get_next, extract_data) @distributed_trace - def create_or_update( - self, name: str, version: str, index: Union[_models.Index, JSON, IO[bytes]], **kwargs: Any - ) -> _models.Index: - """Create a new or update an existing Index with the given version id. + def get_version(self, name: str, version: str, **kwargs: Any) -> _models.EvaluatorVersion: + """Get the specific version of the EvaluatorVersion. The service returns 404 Not Found error if + the EvaluatorVersion does not exist. :param name: The name of the resource. Required. :type name: str - :param version: The specific version id of the Index to create or update. Required. + :param version: The specific version id of the EvaluatorVersion to retrieve. Required. :type version: str - :param index: The Index to create or update. Is one of the following types: Index, JSON, - IO[bytes] Required. - :type index: ~azure.ai.projects.models.Index or JSON or IO[bytes] - :return: Index. The Index is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Index + :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorVersion :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5487,25 +9154,15 @@ def create_or_update( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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.Index] = kwargs.pop("cls", None) - - content_type = content_type or "application/merge-patch+json" - _content = None - if isinstance(index, (IOBase, bytes)): - _content = index - else: - _content = json.dumps(index, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + cls: ClsType[_models.EvaluatorVersion] = kwargs.pop("cls", None) - _request = build_indexes_create_or_update_request( + _request = build_beta_evaluators_get_version_request( name=name, version=version, - content_type=content_type, api_version=self._config.api_version, - content=_content, headers=_headers, params=_params, ) @@ -5522,7 +9179,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 @@ -5534,116 +9191,26 @@ def create_or_update( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.Index, response.json()) + deserialized = _deserialize(_models.EvaluatorVersion, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - -class BetaAgentsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.ai.projects.AIProjectClient`'s - :attr:`agents` 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: AIProjectClientConfiguration = 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 update_agent_from_code( - self, - agent_name: str, - content: _models.CreateAgentVersionFromCodeContent, - *, - code_zip_sha256: str, - **kwargs: Any - ) -> _models.AgentDetails: - """Updates a code-based agent by uploading new code and creating a new version. If the code and - definition are unchanged (matched by x-ms-code-zip-sha256 header), returns the existing - version. The request body is multipart/form-data with a JSON metadata part and a binary code - part (part order is irrelevant). Maximum upload size is 250 MB. - - :param agent_name: The unique name that identifies the agent. Name can be used to - retrieve/update/delete the agent. - - * Must start and end with alphanumeric characters, - * Can contain hyphens in the middle - * Must not exceed 63 characters. Required. - :type agent_name: str - :param content: Required. - :type content: ~azure.ai.projects.models.CreateAgentVersionFromCodeContent - :keyword code_zip_sha256: SHA-256 hex digest of the uploaded code zip. Used for change - detection (dedup) and integrity verification. Required. - :paramtype code_zip_sha256: str - :return: AgentDetails. The AgentDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentDetails - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update_agent_from_code( - self, agent_name: str, content: JSON, *, code_zip_sha256: str, **kwargs: Any - ) -> _models.AgentDetails: - """Updates a code-based agent by uploading new code and creating a new version. If the code and - definition are unchanged (matched by x-ms-code-zip-sha256 header), returns the existing - version. The request body is multipart/form-data with a JSON metadata part and a binary code - part (part order is irrelevant). Maximum upload size is 250 MB. - - :param agent_name: The unique name that identifies the agent. Name can be used to - retrieve/update/delete the agent. - - * Must start and end with alphanumeric characters, - * Can contain hyphens in the middle - * Must not exceed 63 characters. Required. - :type agent_name: str - :param content: Required. - :type content: JSON - :keyword code_zip_sha256: SHA-256 hex digest of the uploaded code zip. Used for change - detection (dedup) and integrity verification. Required. - :paramtype code_zip_sha256: str - :return: AgentDetails. The AgentDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentDetails - :raises ~azure.core.exceptions.HttpResponseError: - """ - @distributed_trace - def update_agent_from_code( - self, - agent_name: str, - content: Union[_models.CreateAgentVersionFromCodeContent, JSON], - *, - code_zip_sha256: str, - **kwargs: Any - ) -> _models.AgentDetails: - """Updates a code-based agent by uploading new code and creating a new version. If the code and - definition are unchanged (matched by x-ms-code-zip-sha256 header), returns the existing - version. The request body is multipart/form-data with a JSON metadata part and a binary code - part (part order is irrelevant). Maximum upload size is 250 MB. - - :param agent_name: The unique name that identifies the agent. Name can be used to - retrieve/update/delete the agent. + def delete_version( # pylint: disable=inconsistent-return-statements + self, name: str, version: str, **kwargs: Any + ) -> None: + """Delete the specific version of the EvaluatorVersion. The service returns 204 No Content if the + EvaluatorVersion was deleted successfully or if the EvaluatorVersion does not exist. - * Must start and end with alphanumeric characters, - * Can contain hyphens in the middle - * Must not exceed 63 characters. Required. - :type agent_name: str - :param content: Is either a CreateAgentVersionFromCodeContent type or a JSON type. Required. - :type content: ~azure.ai.projects.models.CreateAgentVersionFromCodeContent or JSON - :keyword code_zip_sha256: SHA-256 hex digest of the uploaded code zip. Used for change - detection (dedup) and integrity verification. Required. - :paramtype code_zip_sha256: str - :return: AgentDetails. The AgentDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentDetails + :param name: The name of the resource. Required. + :type name: str + :param version: The version of the EvaluatorVersion to delete. Required. + :type version: str + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5657,18 +9224,12 @@ def update_agent_from_code( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.AgentDetails] = kwargs.pop("cls", None) - - _body = content.as_dict() if isinstance(content, _Model) else content - _file_fields: list[str] = ["code"] - _data_fields: list[str] = ["metadata"] - _files = prepare_multipart_form_data(_body, _file_fields, _data_fields) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_beta_agents_update_agent_from_code_request( - agent_name=agent_name, - code_zip_sha256=code_zip_sha256, + _request = build_beta_evaluators_delete_version_request( + name=name, + version=version, api_version=self._config.api_version, - files=_files, headers=_headers, params=_params, ) @@ -5677,121 +9238,92 @@ def update_agent_from_code( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _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 + if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.AgentDetails, response.json()) + raise HttpResponseError(response=response) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore + return cls(pipeline_response, None, {}) # type: ignore @overload - def patch_agent_details( + def create_version( self, - agent_name: str, + name: str, + evaluator_version: _models.EvaluatorVersion, *, - content_type: str = "application/merge-patch+json", - agent_endpoint: Optional[_models.AgentEndpointConfig] = None, - agent_card: Optional[_models.AgentCard] = None, + content_type: str = "application/json", **kwargs: Any - ) -> _models.AgentDetails: - """Updates an agent endpoint. + ) -> _models.EvaluatorVersion: + """Create a new EvaluatorVersion with auto incremented version id. - :param agent_name: The name of the agent to retrieve. Required. - :type agent_name: str + :param name: The name of the resource. Required. + :type name: str + :param evaluator_version: Required. + :type evaluator_version: ~azure.ai.projects.models.EvaluatorVersion :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". + Default value is "application/json". :paramtype content_type: str - :keyword agent_endpoint: The endpoint configuration for the agent. Default value is None. - :paramtype agent_endpoint: ~azure.ai.projects.models.AgentEndpointConfig - :keyword agent_card: Optional agent card for the agent. Default value is None. - :paramtype agent_card: ~azure.ai.projects.models.AgentCard - :return: AgentDetails. The AgentDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentDetails + :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorVersion :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def patch_agent_details( - self, agent_name: str, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any - ) -> _models.AgentDetails: - """Updates an agent endpoint. + def create_version( + self, name: str, evaluator_version: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluatorVersion: + """Create a new EvaluatorVersion with auto incremented version id. - :param agent_name: The name of the agent to retrieve. Required. - :type agent_name: str - :param body: Required. - :type body: JSON + :param name: The name of the resource. Required. + :type name: str + :param evaluator_version: Required. + :type evaluator_version: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". + Default value is "application/json". :paramtype content_type: str - :return: AgentDetails. The AgentDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentDetails + :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorVersion :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def patch_agent_details( - self, agent_name: str, body: IO[bytes], *, content_type: str = "application/merge-patch+json", **kwargs: Any - ) -> _models.AgentDetails: - """Updates an agent endpoint. + def create_version( + self, name: str, evaluator_version: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluatorVersion: + """Create a new EvaluatorVersion with auto incremented version id. - :param agent_name: The name of the agent to retrieve. Required. - :type agent_name: str - :param body: Required. - :type body: IO[bytes] + :param name: The name of the resource. Required. + :type name: str + :param evaluator_version: Required. + :type evaluator_version: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/merge-patch+json". + Default value is "application/json". :paramtype content_type: str - :return: AgentDetails. The AgentDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentDetails + :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorVersion :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def patch_agent_details( - self, - agent_name: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - agent_endpoint: Optional[_models.AgentEndpointConfig] = None, - agent_card: Optional[_models.AgentCard] = None, - **kwargs: Any - ) -> _models.AgentDetails: - """Updates an agent endpoint. + def create_version( + self, name: str, evaluator_version: Union[_models.EvaluatorVersion, JSON, IO[bytes]], **kwargs: Any + ) -> _models.EvaluatorVersion: + """Create a new EvaluatorVersion with auto incremented version id. - :param agent_name: The name of the agent to retrieve. Required. - :type agent_name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword agent_endpoint: The endpoint configuration for the agent. Default value is None. - :paramtype agent_endpoint: ~azure.ai.projects.models.AgentEndpointConfig - :keyword agent_card: Optional agent card for the agent. Default value is None. - :paramtype agent_card: ~azure.ai.projects.models.AgentCard - :return: AgentDetails. The AgentDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentDetails + :param name: The name of the resource. Required. + :type name: str + :param evaluator_version: Is one of the following types: EvaluatorVersion, JSON, IO[bytes] + Required. + :type evaluator_version: ~azure.ai.projects.models.EvaluatorVersion or JSON or IO[bytes] + :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorVersion :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5806,20 +9338,17 @@ def patch_agent_details( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AgentDetails] = kwargs.pop("cls", None) + cls: ClsType[_models.EvaluatorVersion] = kwargs.pop("cls", None) - if body is _Unset: - body = {"agent_card": agent_card, "agent_endpoint": agent_endpoint} - body = {k: v for k, v in body.items() if v is not None} - content_type = content_type or "application/merge-patch+json" + content_type = content_type or "application/json" _content = None - if isinstance(body, (IOBase, bytes)): - _content = body + if isinstance(evaluator_version, (IOBase, bytes)): + _content = evaluator_version else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(evaluator_version, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_agents_patch_agent_details_request( - agent_name=agent_name, + _request = build_beta_evaluators_create_version_request( + name=name, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -5839,23 +9368,19 @@ def patch_agent_details( response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [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) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) + raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.AgentDetails, response.json()) + deserialized = _deserialize(_models.EvaluatorVersion, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -5863,81 +9388,96 @@ def patch_agent_details( return deserialized # type: ignore @overload - def create_agent_version_from_code( + def update_version( self, - agent_name: str, - content: _models.CreateAgentVersionFromCodeContent, + name: str, + version: str, + evaluator_version: _models.EvaluatorVersion, *, - code_zip_sha256: str, + content_type: str = "application/json", **kwargs: Any - ) -> _models.AgentVersionDetails: - """create_agent_version_from_code. - - :param agent_name: The unique name that identifies the agent. Name can be used to - retrieve/update/delete the agent. + ) -> _models.EvaluatorVersion: + """Update an existing EvaluatorVersion with the given version id. - * Must start and end with alphanumeric characters, - * Can contain hyphens in the middle - * Must not exceed 63 characters. Required. - :type agent_name: str - :param content: Required. - :type content: ~azure.ai.projects.models.CreateAgentVersionFromCodeContent - :keyword code_zip_sha256: SHA-256 hex digest of the uploaded code zip. Used for change - detection (dedup) and integrity verification. Required. - :paramtype code_zip_sha256: str - :return: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentVersionDetails + :param name: The name of the resource. Required. + :type name: str + :param version: The version of the EvaluatorVersion to update. Required. + :type version: str + :param evaluator_version: Evaluator resource. Required. + :type evaluator_version: ~azure.ai.projects.models.EvaluatorVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorVersion :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_agent_version_from_code( - self, agent_name: str, content: JSON, *, code_zip_sha256: str, **kwargs: Any - ) -> _models.AgentVersionDetails: - """create_agent_version_from_code. + def update_version( + self, name: str, version: str, evaluator_version: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluatorVersion: + """Update an existing EvaluatorVersion with the given version id. - :param agent_name: The unique name that identifies the agent. Name can be used to - retrieve/update/delete the agent. + :param name: The name of the resource. Required. + :type name: str + :param version: The version of the EvaluatorVersion to update. Required. + :type version: str + :param evaluator_version: Evaluator resource. Required. + :type evaluator_version: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def update_version( + self, + name: str, + version: str, + evaluator_version: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EvaluatorVersion: + """Update an existing EvaluatorVersion with the given version id. - * Must start and end with alphanumeric characters, - * Can contain hyphens in the middle - * Must not exceed 63 characters. Required. - :type agent_name: str - :param content: Required. - :type content: JSON - :keyword code_zip_sha256: SHA-256 hex digest of the uploaded code zip. Used for change - detection (dedup) and integrity verification. Required. - :paramtype code_zip_sha256: str - :return: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentVersionDetails + :param name: The name of the resource. Required. + :type name: str + :param version: The version of the EvaluatorVersion to update. Required. + :type version: str + :param evaluator_version: Evaluator resource. Required. + :type evaluator_version: 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: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorVersion :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def create_agent_version_from_code( + def update_version( self, - agent_name: str, - content: Union[_models.CreateAgentVersionFromCodeContent, JSON], - *, - code_zip_sha256: str, + name: str, + version: str, + evaluator_version: Union[_models.EvaluatorVersion, JSON, IO[bytes]], **kwargs: Any - ) -> _models.AgentVersionDetails: - """create_agent_version_from_code. - - :param agent_name: The unique name that identifies the agent. Name can be used to - retrieve/update/delete the agent. + ) -> _models.EvaluatorVersion: + """Update an existing EvaluatorVersion with the given version id. - * Must start and end with alphanumeric characters, - * Can contain hyphens in the middle - * Must not exceed 63 characters. Required. - :type agent_name: str - :param content: Is either a CreateAgentVersionFromCodeContent type or a JSON type. Required. - :type content: ~azure.ai.projects.models.CreateAgentVersionFromCodeContent or JSON - :keyword code_zip_sha256: SHA-256 hex digest of the uploaded code zip. Used for change - detection (dedup) and integrity verification. Required. - :paramtype code_zip_sha256: str - :return: AgentVersionDetails. The AgentVersionDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentVersionDetails + :param name: The name of the resource. Required. + :type name: str + :param version: The version of the EvaluatorVersion to update. Required. + :type version: str + :param evaluator_version: Evaluator resource. Is one of the following types: EvaluatorVersion, + JSON, IO[bytes] Required. + :type evaluator_version: ~azure.ai.projects.models.EvaluatorVersion or JSON or IO[bytes] + :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorVersion :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5948,21 +9488,25 @@ def create_agent_version_from_code( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.AgentVersionDetails] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.EvaluatorVersion] = kwargs.pop("cls", None) - _body = content.as_dict() if isinstance(content, _Model) else content - _file_fields: list[str] = ["code"] - _data_fields: list[str] = ["metadata"] - _files = prepare_multipart_form_data(_body, _file_fields, _data_fields) + content_type = content_type or "application/json" + _content = None + if isinstance(evaluator_version, (IOBase, bytes)): + _content = evaluator_version + else: + _content = json.dumps(evaluator_version, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_agents_create_agent_version_from_code_request( - agent_name=agent_name, - code_zip_sha256=code_zip_sha256, + _request = build_beta_evaluators_update_version_request( + name=name, + version=version, + content_type=content_type, api_version=self._config.api_version, - files=_files, + content=_content, headers=_headers, params=_params, ) @@ -5986,103 +9530,116 @@ def create_agent_version_from_code( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) + raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.AgentVersionDetails, response.json()) + deserialized = _deserialize(_models.EvaluatorVersion, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @distributed_trace - def download_agent_version_code(self, agent_name: str, agent_version: str, **kwargs: Any) -> Iterator[bytes]: - """Download the code zip for a specific version of a code-based hosted agent. Returns the - previously-uploaded zip (``application/zip``). The SHA-256 digest of the returned bytes matches - the ``content_hash`` on the agent version's ``code_configuration``. + @overload + def pending_upload( + self, + name: str, + version: str, + pending_upload_request: _models.PendingUploadRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PendingUploadResult: + """Start a new or get an existing pending upload of an evaluator for a specific version. - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param agent_version: The version of the agent whose code zip should be downloaded. Required. - :type agent_version: str - :return: Iterator[bytes] - :rtype: Iterator[bytes] + :param name: Required. + :type name: str + :param version: The specific version id of the EvaluatorVersion to operate on. Required. + :type version: str + :param pending_upload_request: The pending upload request parameters. Required. + :type pending_upload_request: ~azure.ai.projects.models.PendingUploadRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PendingUploadResult. The PendingUploadResult is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResult :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[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_beta_agents_download_agent_version_code_request( - agent_name=agent_name, - agent_version=agent_version, - 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", 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]: - 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) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) - response_headers = {} - response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) + @overload + def pending_upload( + self, + name: str, + version: str, + pending_upload_request: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PendingUploadResult: + """Start a new or get an existing pending upload of an evaluator for a specific version. - deserialized = response.iter_bytes() if _decompress else response.iter_raw() + :param name: Required. + :type name: str + :param version: The specific version id of the EvaluatorVersion to operate on. Required. + :type version: str + :param pending_upload_request: The pending upload request parameters. Required. + :type pending_upload_request: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: PendingUploadResult. The PendingUploadResult is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResult + :raises ~azure.core.exceptions.HttpResponseError: + """ - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore + @overload + def pending_upload( + self, + name: str, + version: str, + pending_upload_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PendingUploadResult: + """Start a new or get an existing pending upload of an evaluator for a specific version. - return deserialized # type: ignore + :param name: Required. + :type name: str + :param version: The specific version id of the EvaluatorVersion to operate on. Required. + :type version: str + :param pending_upload_request: The pending upload request parameters. Required. + :type pending_upload_request: 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: PendingUploadResult. The PendingUploadResult is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResult + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace - def download_agent_code(self, agent_name: str, **kwargs: Any) -> Iterator[bytes]: - """Download the code zip for the latest version of a code-based hosted agent. Returns the - previously-uploaded zip (``application/zip``). The SHA-256 digest of the returned bytes matches - the ``content_hash`` on the latest version's ``code_configuration``. + def pending_upload( + self, + name: str, + version: str, + pending_upload_request: Union[_models.PendingUploadRequest, JSON, IO[bytes]], + **kwargs: Any + ) -> _models.PendingUploadResult: + """Start a new or get an existing pending upload of an evaluator for a specific version. - :param agent_name: The name of the agent whose latest-version code zip should be downloaded. - Required. - :type agent_name: str - :return: Iterator[bytes] - :rtype: Iterator[bytes] + :param name: Required. + :type name: str + :param version: The specific version id of the EvaluatorVersion to operate on. Required. + :type version: str + :param pending_upload_request: The pending upload request parameters. Is one of the following + types: PendingUploadRequest, JSON, IO[bytes] Required. + :type pending_upload_request: ~azure.ai.projects.models.PendingUploadRequest or JSON or + IO[bytes] + :return: PendingUploadResult. The PendingUploadResult is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6093,14 +9650,25 @@ def download_agent_code(self, agent_name: str, **kwargs: Any) -> Iterator[bytes] } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PendingUploadResult] = kwargs.pop("cls", None) - _request = build_beta_agents_download_agent_code_request( - agent_name=agent_name, + content_type = content_type or "application/json" + _content = None + if isinstance(pending_upload_request, (IOBase, bytes)): + _content = pending_upload_request + else: + _content = json.dumps(pending_upload_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_beta_evaluators_pending_upload_request( + name=name, + version=version, + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -6110,7 +9678,7 @@ def download_agent_code(self, agent_name: str, **kwargs: Any) -> Iterator[bytes] _request.url = self._client.format_url(_request.url, **path_format_arguments) _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", True) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -6130,110 +9698,114 @@ def download_agent_code(self, agent_name: str, **kwargs: Any) -> Iterator[bytes] ) raise HttpResponseError(response=response, model=error) - response_headers = {} - response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - - deserialized = response.iter_bytes() if _decompress else response.iter_raw() + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.PendingUploadResult, response.json()) if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore @overload - def create_session( + def get_credentials( self, - agent_name: str, + name: str, + version: str, + credential_request: _models.EvaluatorCredentialRequest, *, - version_indicator: _models.VersionIndicator, content_type: str = "application/json", - agent_session_id: Optional[str] = None, **kwargs: Any - ) -> _models.AgentSessionResource: - """Creates a new session for an agent endpoint. The endpoint resolves the backing agent version - from ``version_indicator`` and enforces session ownership using the provided isolation key for - session-mutating operations. + ) -> _models.DatasetCredential: + """Get the SAS credential to access the storage account associated with an Evaluator version. - :param agent_name: The name of the agent to create a session for. Required. - :type agent_name: str - :keyword version_indicator: Determines which agent version backs the session. Required. - :paramtype version_indicator: ~azure.ai.projects.models.VersionIndicator + :param name: Required. + :type name: str + :param version: The specific version id of the EvaluatorVersion to operate on. Required. + :type version: str + :param credential_request: The credential request parameters. Required. + :type credential_request: ~azure.ai.projects.models.EvaluatorCredentialRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword agent_session_id: Optional caller-provided session ID. If specified, it must be unique - within the agent endpoint. Auto-generated if omitted. Default value is None. - :paramtype agent_session_id: str - :return: AgentSessionResource. The AgentSessionResource is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentSessionResource + :return: DatasetCredential. The DatasetCredential is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetCredential :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_session( - self, agent_name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AgentSessionResource: - """Creates a new session for an agent endpoint. The endpoint resolves the backing agent version - from ``version_indicator`` and enforces session ownership using the provided isolation key for - session-mutating operations. + def get_credentials( + self, + name: str, + version: str, + credential_request: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DatasetCredential: + """Get the SAS credential to access the storage account associated with an Evaluator version. - :param agent_name: The name of the agent to create a session for. Required. - :type agent_name: str - :param body: Required. - :type body: JSON + :param name: Required. + :type name: str + :param version: The specific version id of the EvaluatorVersion to operate on. Required. + :type version: str + :param credential_request: The credential request parameters. Required. + :type credential_request: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: AgentSessionResource. The AgentSessionResource is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentSessionResource + :return: DatasetCredential. The DatasetCredential is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetCredential :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_session( - self, agent_name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AgentSessionResource: - """Creates a new session for an agent endpoint. The endpoint resolves the backing agent version - from ``version_indicator`` and enforces session ownership using the provided isolation key for - session-mutating operations. + def get_credentials( + self, + name: str, + version: str, + credential_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.DatasetCredential: + """Get the SAS credential to access the storage account associated with an Evaluator version. - :param agent_name: The name of the agent to create a session for. Required. - :type agent_name: str - :param body: Required. - :type body: IO[bytes] + :param name: Required. + :type name: str + :param version: The specific version id of the EvaluatorVersion to operate on. Required. + :type version: str + :param credential_request: The credential request parameters. Required. + :type credential_request: 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: AgentSessionResource. The AgentSessionResource is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentSessionResource + :return: DatasetCredential. The DatasetCredential is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetCredential :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def create_session( + def get_credentials( self, - agent_name: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - version_indicator: _models.VersionIndicator = _Unset, - agent_session_id: Optional[str] = None, + name: str, + version: str, + credential_request: Union[_models.EvaluatorCredentialRequest, JSON, IO[bytes]], **kwargs: Any - ) -> _models.AgentSessionResource: - """Creates a new session for an agent endpoint. The endpoint resolves the backing agent version - from ``version_indicator`` and enforces session ownership using the provided isolation key for - session-mutating operations. + ) -> _models.DatasetCredential: + """Get the SAS credential to access the storage account associated with an Evaluator version. - :param agent_name: The name of the agent to create a session for. Required. - :type agent_name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword version_indicator: Determines which agent version backs the session. Required. - :paramtype version_indicator: ~azure.ai.projects.models.VersionIndicator - :keyword agent_session_id: Optional caller-provided session ID. If specified, it must be unique - within the agent endpoint. Auto-generated if omitted. Default value is None. - :paramtype agent_session_id: str - :return: AgentSessionResource. The AgentSessionResource is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentSessionResource + :param name: Required. + :type name: str + :param version: The specific version id of the EvaluatorVersion to operate on. Required. + :type version: str + :param credential_request: The credential request parameters. Is one of the following types: + EvaluatorCredentialRequest, JSON, IO[bytes] Required. + :type credential_request: ~azure.ai.projects.models.EvaluatorCredentialRequest or JSON or + IO[bytes] + :return: DatasetCredential. The DatasetCredential is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetCredential :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6248,22 +9820,18 @@ def create_session( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AgentSessionResource] = kwargs.pop("cls", None) + cls: ClsType[_models.DatasetCredential] = kwargs.pop("cls", None) - if body is _Unset: - if version_indicator is _Unset: - raise TypeError("missing required argument: version_indicator") - body = {"agent_session_id": agent_session_id, "version_indicator": version_indicator} - 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 + if isinstance(credential_request, (IOBase, bytes)): + _content = credential_request else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(credential_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_agents_create_session_request( - agent_name=agent_name, + _request = build_beta_evaluators_get_credentials_request( + name=name, + version=version, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -6283,7 +9851,7 @@ def create_session( response = pipeline_response.http_response - if response.status_code not in [201]: + if response.status_code not in [200]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -6299,23 +9867,110 @@ def create_session( if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.AgentSessionResource, response.json()) + deserialized = _deserialize(_models.DatasetCredential, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + @overload + def create_generation_job( + self, + job: _models.EvaluatorGenerationJob, + *, + operation_id: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EvaluatorGenerationJob: + """Creates an evaluator generation job. + + Creates an evaluator generation job. The service generates rubric-based evaluator definitions + from the provided source materials asynchronously. + + :param job: The job to create. Required. + :type job: ~azure.ai.projects.models.EvaluatorGenerationJob + :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the + server creates the job unconditionally. Default value is None. + :paramtype operation_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_generation_job( + self, job: JSON, *, operation_id: Optional[str] = None, content_type: str = "application/json", **kwargs: Any + ) -> _models.EvaluatorGenerationJob: + """Creates an evaluator generation job. + + Creates an evaluator generation job. The service generates rubric-based evaluator definitions + from the provided source materials asynchronously. + + :param job: The job to create. Required. + :type job: JSON + :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the + server creates the job unconditionally. Default value is None. + :paramtype operation_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_generation_job( + self, + job: IO[bytes], + *, + operation_id: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.EvaluatorGenerationJob: + """Creates an evaluator generation job. + + Creates an evaluator generation job. The service generates rubric-based evaluator definitions + from the provided source materials asynchronously. + + :param job: The job to create. Required. + :type job: IO[bytes] + :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the + server creates the job unconditionally. Default value is None. + :paramtype operation_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob + :raises ~azure.core.exceptions.HttpResponseError: + """ + @distributed_trace - def get_session(self, agent_name: str, session_id: str, **kwargs: Any) -> _models.AgentSessionResource: - """Retrieves a session by ID. + def create_generation_job( + self, + job: Union[_models.EvaluatorGenerationJob, JSON, IO[bytes]], + *, + operation_id: Optional[str] = None, + **kwargs: Any + ) -> _models.EvaluatorGenerationJob: + """Creates an evaluator generation job. - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param session_id: The session identifier. Required. - :type session_id: str - :return: AgentSessionResource. The AgentSessionResource is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentSessionResource + Creates an evaluator generation job. The service generates rubric-based evaluator definitions + from the provided source materials asynchronously. + + :param job: The job to create. Is one of the following types: EvaluatorGenerationJob, JSON, + IO[bytes] Required. + :type job: ~azure.ai.projects.models.EvaluatorGenerationJob or JSON or IO[bytes] + :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the + server creates the job unconditionally. Default value is None. + :paramtype operation_id: str + :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6326,15 +9981,24 @@ def get_session(self, agent_name: str, session_id: str, **kwargs: Any) -> _model } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.AgentSessionResource] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.EvaluatorGenerationJob] = kwargs.pop("cls", None) - _request = build_beta_agents_get_session_request( - agent_name=agent_name, - session_id=session_id, + content_type = content_type or "application/json" + _content = None + if isinstance(job, (IOBase, bytes)): + _content = job + else: + _content = json.dumps(job, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_beta_evaluators_create_generation_job_request( + operation_id=operation_id, + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -6351,7 +10015,7 @@ def get_session(self, agent_name: str, session_id: str, **kwargs: Any) -> _model response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [201]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -6364,29 +10028,30 @@ def get_session(self, agent_name: str, session_id: str, **kwargs: Any) -> _model ) raise HttpResponseError(response=response, model=error) + response_headers = {} + response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) + if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.AgentSessionResource, response.json()) + deserialized = _deserialize(_models.EvaluatorGenerationJob, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore @distributed_trace - def delete_session( # pylint: disable=inconsistent-return-statements - self, agent_name: str, session_id: str, **kwargs: Any - ) -> None: - """Deletes a session synchronously. Returns 204 No Content when the session is deleted or does not - exist. + def get_generation_job(self, job_id: str, **kwargs: Any) -> _models.EvaluatorGenerationJob: + """Get info about an evaluator generation job. - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param session_id: The session identifier. Required. - :type session_id: str - :return: None - :rtype: None + Gets the details of an evaluator generation job by its ID. + + :param job_id: The ID of the job. Required. + :type job_id: str + :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6400,11 +10065,10 @@ def delete_session( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models.EvaluatorGenerationJob] = kwargs.pop("cls", None) - _request = build_beta_agents_delete_session_request( - agent_name=agent_name, - session_id=session_id, + _request = build_beta_evaluators_get_generation_job_request( + job_id=job_id, api_version=self._config.api_version, headers=_headers, params=_params, @@ -6414,14 +10078,20 @@ def delete_session( # pylint: disable=inconsistent-return-statements } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 [204]: + 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) error = _failsafe_deserialize( _models.ApiErrorResponse, @@ -6429,23 +10099,32 @@ def delete_session( # pylint: disable=inconsistent-return-statements ) raise HttpResponseError(response=response, model=error) + response_headers = {} + response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.EvaluatorGenerationJob, response.json()) + if cls: - return cls(pipeline_response, None, {}) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore + + return deserialized # type: ignore @distributed_trace - def list_sessions( + def list_generation_jobs( self, - agent_name: str, *, limit: Optional[int] = None, order: Optional[Union[str, _models.PageOrder]] = None, before: Optional[str] = None, **kwargs: Any - ) -> ItemPaged["_models.AgentSessionResource"]: - """Returns a list of sessions for the specified agent. + ) -> ItemPaged["_models.EvaluatorGenerationJob"]: + """Returns a list of evaluator generation jobs. + + Returns a list of evaluator generation jobs. - :param agent_name: The name of the agent. Required. - :type agent_name: str :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and 100, and the default is 20. Default value is None. @@ -6460,14 +10139,14 @@ def list_sessions( subsequent call can include before=obj_foo in order to fetch the previous page of the list. Default value is None. :paramtype before: str - :return: An iterator like instance of AgentSessionResource - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.AgentSessionResource] + :return: An iterator like instance of EvaluatorGenerationJob + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.EvaluatorGenerationJob] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.AgentSessionResource]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.EvaluatorGenerationJob]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -6479,8 +10158,7 @@ def list_sessions( def prepare_request(_continuation_token=None): - _request = build_beta_agents_list_sessions_request( - agent_name=agent_name, + _request = build_beta_evaluators_list_generation_jobs_request( limit=limit, order=order, after=_continuation_token, @@ -6498,7 +10176,7 @@ def prepare_request(_continuation_token=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() list_of_elem = _deserialize( - List[_models.AgentSessionResource], + List[_models.EvaluatorGenerationJob], deserialized.get("data", []), ) if cls: @@ -6527,203 +10205,15 @@ def get_next(_continuation_token=None): return ItemPaged(get_next, extract_data) @distributed_trace - def get_session_log_stream( - self, agent_name: str, agent_version: str, session_id: str, **kwargs: Any - ) -> _models.SessionLogEvent: - """Streams console logs (stdout / stderr) for a specific hosted agent session - as a Server-Sent Events (SSE) stream. - - Each SSE frame contains: - - * `event`: always `"log"` - * `data`: a plain-text log line (currently JSON-formatted, but the schema is not contractual and may include additional keys or change format over time; clients should treat it as an opaque string) - - Example SSE frames: - - .. code-block:: - - event: log - data: {"timestamp":"2026-03-10T09:33:17.121Z","stream":"stdout","message":"Starting FoundryCBAgent server on port 8088"} - - event: log - data: {"timestamp":"2026-03-10T09:33:17.130Z","stream":"stderr","message":"INFO: Application startup complete."} - - event: log - data: {"timestamp":"2026-03-10T09:34:52.714Z","stream":"status","message":"Successfully connected to container"} - - event: log - data: {"timestamp":"2026-03-10T09:35:52.714Z","stream":"status","message":"No logs since last 60 seconds"} - - The stream remains open until the client disconnects or the server - terminates the connection. Clients should handle reconnection as needed. - - :param agent_name: The name of the hosted agent. Required. - :type agent_name: str - :param agent_version: The version of the agent. Required. - :type agent_version: str - :param session_id: The session ID (maps to an ADC sandbox). Required. - :type session_id: str - :return: SessionLogEvent. The SessionLogEvent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.SessionLogEvent - :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.SessionLogEvent] = kwargs.pop("cls", None) - - _request = build_beta_agents_get_session_log_stream_request( - agent_name=agent_name, - agent_version=agent_version, - session_id=session_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 = 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]: - 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) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) - - response_headers = {} - response_headers["Content-Type"] = self._deserialize("str", response.headers.get("Content-Type")) - - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.SessionLogEvent, response.text()) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def _upload_session_file( - self, agent_name: str, agent_session_id: str, content: bytes, *, path: str, **kwargs: Any - ) -> _models.SessionFileWriteResult: - """Upload a file to the session sandbox via binary stream. Maximum file size is 50 MB. Uploads - exceeding this limit return 413 Payload Too Large. - - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param agent_session_id: The session ID. Required. - :type agent_session_id: str - :param content: Required. - :type content: bytes - :keyword path: The destination file path within the sandbox, relative to the session home - directory. Required. - :paramtype path: str - :return: SessionFileWriteResult. The SessionFileWriteResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.SessionFileWriteResult - :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: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/octet-stream")) - cls: ClsType[_models.SessionFileWriteResult] = kwargs.pop("cls", None) - - _content = content - - _request = build_beta_agents_upload_session_file_request( - agent_name=agent_name, - agent_session_id=agent_session_id, - path=path, - 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 [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) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.SessionFileWriteResult, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore + def cancel_generation_job(self, job_id: str, **kwargs: Any) -> _models.EvaluatorGenerationJob: + """Cancels an evaluator generation job. - @distributed_trace - def download_session_file( - self, agent_name: str, agent_session_id: str, *, path: str, **kwargs: Any - ) -> Iterator[bytes]: - """Download a file from the session sandbox as a binary stream. + Cancels an evaluator generation job by its ID. - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param agent_session_id: The session ID. Required. - :type agent_session_id: str - :keyword path: The file path to download from the sandbox, relative to the session home - directory. Required. - :paramtype path: str - :return: Iterator[bytes] - :rtype: Iterator[bytes] + :param job_id: The ID of the job to cancel. Required. + :type job_id: str + :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6737,12 +10227,10 @@ def download_session_file( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + cls: ClsType[_models.EvaluatorGenerationJob] = kwargs.pop("cls", None) - _request = build_beta_agents_download_session_file_request( - agent_name=agent_name, - agent_session_id=agent_session_id, - path=path, + _request = build_beta_evaluators_cancel_generation_job_request( + job_id=job_id, api_version=self._config.api_version, headers=_headers, params=_params, @@ -6753,7 +10241,7 @@ def download_session_file( _request.url = self._client.format_url(_request.url, **path_format_arguments) _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", True) + _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access _request, stream=_stream, **kwargs ) @@ -6773,7 +10261,10 @@ def download_session_file( ) raise HttpResponseError(response=response, model=error) - deserialized = response.iter_bytes() if _decompress else response.iter_raw() + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.EvaluatorGenerationJob, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -6781,21 +10272,16 @@ def download_session_file( return deserialized # type: ignore @distributed_trace - def get_session_files( - self, agent_name: str, agent_session_id: str, *, path: str, **kwargs: Any - ) -> _models.SessionDirectoryListResult: - """List files and directories at a given path in the session sandbox. Returns only the immediate - children of the specified directory (non-recursive). + def delete_generation_job( # pylint: disable=inconsistent-return-statements + self, job_id: str, **kwargs: Any + ) -> None: + """Deletes an evaluator generation job by its ID. Deletes the job record only; the generated + evaluator (if any) is preserved. - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param agent_session_id: The session ID. Required. - :type agent_session_id: str - :keyword path: The directory path to list, relative to the session home directory. Required. - :paramtype path: str - :return: SessionDirectoryListResult. The SessionDirectoryListResult is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.SessionDirectoryListResult + :param job_id: The ID of the job to delete. Required. + :type job_id: str + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6809,12 +10295,10 @@ def get_session_files( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.SessionDirectoryListResult] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_beta_agents_get_session_files_request( - agent_name=agent_name, - agent_session_id=agent_session_id, - path=path, + _request = build_beta_evaluators_delete_generation_job_request( + job_id=job_id, api_version=self._config.api_version, headers=_headers, params=_params, @@ -6824,20 +10308,14 @@ def get_session_files( } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _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 + if response.status_code not in [204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = _failsafe_deserialize( _models.ApiErrorResponse, @@ -6845,35 +10323,83 @@ def get_session_files( ) raise HttpResponseError(response=response, model=error) - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.SessionDirectoryListResult, response.json()) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, None, {}) # type: ignore - return deserialized # type: ignore + +class BetaInsightsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.AIProjectClient`'s + :attr:`insights` 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: AIProjectClientConfiguration = 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 generate( + self, insight: _models.Insight, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Insight: + """Generate Insights. + + :param insight: Complete evaluation configuration including data source, evaluators, and result + settings. Required. + :type insight: ~azure.ai.projects.models.Insight + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Insight. The Insight is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Insight + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def generate(self, insight: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Insight: + """Generate Insights. + + :param insight: Complete evaluation configuration including data source, evaluators, and result + settings. Required. + :type insight: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: Insight. The Insight is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Insight + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def generate(self, insight: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> _models.Insight: + """Generate Insights. + + :param insight: Complete evaluation configuration including data source, evaluators, and result + settings. Required. + :type insight: 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: Insight. The Insight is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Insight + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace - def delete_session_file( # pylint: disable=inconsistent-return-statements - self, agent_name: str, agent_session_id: str, *, path: str, recursive: Optional[bool] = None, **kwargs: Any - ) -> None: - """Delete a file or directory from the session sandbox. If ``recursive`` is false (default) and - the target is a non-empty directory, the API returns 409 Conflict. + def generate(self, insight: Union[_models.Insight, JSON, IO[bytes]], **kwargs: Any) -> _models.Insight: + """Generate Insights. - :param agent_name: The name of the agent. Required. - :type agent_name: str - :param agent_session_id: The session ID. Required. - :type agent_session_id: str - :keyword path: The file or directory path to delete, relative to the session home directory. - Required. - :paramtype path: str - :keyword recursive: Whether to recursively delete directory contents. Defaults to false. - Default value is None. - :paramtype recursive: bool - :return: None - :rtype: None + :param insight: Complete evaluation configuration including data source, evaluators, and result + settings. Is one of the following types: Insight, JSON, IO[bytes] Required. + :type insight: ~azure.ai.projects.models.Insight or JSON or IO[bytes] + :return: Insight. The Insight is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Insight :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6884,17 +10410,23 @@ def delete_session_file( # pylint: disable=inconsistent-return-statements } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.Insight] = kwargs.pop("cls", None) - _request = build_beta_agents_delete_session_file_request( - agent_name=agent_name, - agent_session_id=agent_session_id, - path=path, - recursive=recursive, + content_type = content_type or "application/json" + _content = None + if isinstance(insight, (IOBase, bytes)): + _content = insight + else: + _content = json.dumps(insight, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_beta_insights_generate_request( + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -6903,14 +10435,20 @@ def delete_session_file( # pylint: disable=inconsistent-return-statements } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 [204]: + if response.status_code not in [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) error = _failsafe_deserialize( _models.ApiErrorResponse, @@ -6918,35 +10456,27 @@ def delete_session_file( # pylint: disable=inconsistent-return-statements ) raise HttpResponseError(response=response, model=error) - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - -class BetaEvaluationTaxonomiesOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Insight, response.json()) - Instead, you should access the following operations through - :class:`~azure.ai.projects.AIProjectClient`'s - :attr:`evaluation_taxonomies` attribute. - """ + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - 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: AIProjectClientConfiguration = 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") + return deserialized # type: ignore @distributed_trace - def get(self, name: str, **kwargs: Any) -> _models.EvaluationTaxonomy: - """Get an evaluation run by name. + def get(self, insight_id: str, *, include_coordinates: Optional[bool] = None, **kwargs: Any) -> _models.Insight: + """Get a specific insight by Id. - :param name: The name of the resource. Required. - :type name: str - :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationTaxonomy + :param insight_id: The unique identifier for the insights report. Required. + :type insight_id: str + :keyword include_coordinates: Whether to include coordinates for visualization in the response. + Defaults to false. Default value is None. + :paramtype include_coordinates: bool + :return: Insight. The Insight is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Insight :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6960,10 +10490,11 @@ def get(self, name: str, **kwargs: Any) -> _models.EvaluationTaxonomy: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.EvaluationTaxonomy] = kwargs.pop("cls", None) + cls: ClsType[_models.Insight] = kwargs.pop("cls", None) - _request = build_beta_evaluation_taxonomies_get_request( - name=name, + _request = build_beta_insights_get_request( + insight_id=insight_id, + include_coordinates=include_coordinates, api_version=self._config.api_version, headers=_headers, params=_params, @@ -6988,12 +10519,16 @@ def get(self, name: str, **kwargs: Any) -> _models.EvaluationTaxonomy: except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.EvaluationTaxonomy, response.json()) + deserialized = _deserialize(_models.Insight, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -7002,22 +10537,37 @@ def get(self, name: str, **kwargs: Any) -> _models.EvaluationTaxonomy: @distributed_trace def list( - self, *, input_name: Optional[str] = None, input_type: Optional[str] = None, **kwargs: Any - ) -> ItemPaged["_models.EvaluationTaxonomy"]: - """List evaluation taxonomies. + self, + *, + type: Optional[Union[str, _models.InsightType]] = None, + eval_id: Optional[str] = None, + run_id: Optional[str] = None, + agent_name: Optional[str] = None, + include_coordinates: Optional[bool] = None, + **kwargs: Any + ) -> ItemPaged["_models.Insight"]: + """List all insights in reverse chronological order (newest first). - :keyword input_name: Filter by the evaluation input name. Default value is None. - :paramtype input_name: str - :keyword input_type: Filter by taxonomy input type. Default value is None. - :paramtype input_type: str - :return: An iterator like instance of EvaluationTaxonomy - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.EvaluationTaxonomy] + :keyword type: Filter by the type of analysis. Known values are: "EvaluationRunClusterInsight", + "AgentClusterInsight", and "EvaluationComparison". Default value is None. + :paramtype type: str or ~azure.ai.projects.models.InsightType + :keyword eval_id: Filter by the evaluation ID. Default value is None. + :paramtype eval_id: str + :keyword run_id: Filter by the evaluation run ID. Default value is None. + :paramtype run_id: str + :keyword agent_name: Filter by the agent name. Default value is None. + :paramtype agent_name: str + :keyword include_coordinates: Whether to include coordinates for visualization in the response. + Defaults to false. Default value is None. + :paramtype include_coordinates: bool + :return: An iterator like instance of Insight + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.Insight] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.EvaluationTaxonomy]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Insight]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -7030,9 +10580,12 @@ def list( def prepare_request(next_link=None): if not next_link: - _request = build_beta_evaluation_taxonomies_list_request( - input_name=input_name, - input_type=input_type, + _request = build_beta_insights_list_request( + type=type, + eval_id=eval_id, + run_id=run_id, + agent_name=agent_name, + include_coordinates=include_coordinates, api_version=self._config.api_version, headers=_headers, params=_params, @@ -7072,7 +10625,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() list_of_elem = _deserialize( - List[_models.EvaluationTaxonomy], + List[_models.Insight], deserialized.get("value", []), ) if cls: @@ -7090,257 +10643,122 @@ def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) return pipeline_response return ItemPaged(get_next, extract_data) - @distributed_trace - def delete(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """Delete an evaluation taxonomy by name. - - :param name: The name of the resource. Required. - :type name: str - :return: None - :rtype: None - :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[None] = kwargs.pop("cls", None) - - _request = build_beta_evaluation_taxonomies_delete_request( - name=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) - - _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 [204]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if cls: - return cls(pipeline_response, None, {}) # type: ignore - - @overload - def create( - self, name: str, taxonomy: _models.EvaluationTaxonomy, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationTaxonomy: - """Create an evaluation taxonomy. - :param name: The name of the evaluation taxonomy. Required. - :type name: str - :param taxonomy: The evaluation taxonomy. Required. - :type taxonomy: ~azure.ai.projects.models.EvaluationTaxonomy - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationTaxonomy - :raises ~azure.core.exceptions.HttpResponseError: - """ +class BetaMemoryStoresOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - @overload - def create( - self, name: str, taxonomy: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationTaxonomy: - """Create an evaluation taxonomy. + Instead, you should access the following operations through + :class:`~azure.ai.projects.AIProjectClient`'s + :attr:`memory_stores` attribute. + """ - :param name: The name of the evaluation taxonomy. Required. - :type name: str - :param taxonomy: The evaluation taxonomy. Required. - :type taxonomy: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationTaxonomy - :raises ~azure.core.exceptions.HttpResponseError: - """ + 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: AIProjectClientConfiguration = 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( - self, name: str, taxonomy: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationTaxonomy: - """Create an evaluation taxonomy. - - :param name: The name of the evaluation taxonomy. Required. - :type name: str - :param taxonomy: The evaluation taxonomy. Required. - :type taxonomy: 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: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationTaxonomy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create( - self, name: str, taxonomy: Union[_models.EvaluationTaxonomy, JSON, IO[bytes]], **kwargs: Any - ) -> _models.EvaluationTaxonomy: - """Create an evaluation taxonomy. - - :param name: The name of the evaluation taxonomy. Required. - :type name: str - :param taxonomy: The evaluation taxonomy. Is one of the following types: EvaluationTaxonomy, - JSON, IO[bytes] Required. - :type taxonomy: ~azure.ai.projects.models.EvaluationTaxonomy or JSON or IO[bytes] - :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationTaxonomy - :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.EvaluationTaxonomy] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(taxonomy, (IOBase, bytes)): - _content = taxonomy - else: - _content = json.dumps(taxonomy, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_beta_evaluation_taxonomies_create_request( - name=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.EvaluationTaxonomy, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def update( - self, name: str, taxonomy: _models.EvaluationTaxonomy, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationTaxonomy: - """Update an evaluation taxonomy. + self, + *, + name: str, + definition: _models.MemoryStoreDefinition, + content_type: str = "application/json", + description: Optional[str] = None, + metadata: Optional[dict[str, str]] = None, + **kwargs: Any + ) -> _models.MemoryStoreDetails: + """Create a memory store. - :param name: The name of the evaluation taxonomy. Required. - :type name: str - :param taxonomy: The evaluation taxonomy. Required. - :type taxonomy: ~azure.ai.projects.models.EvaluationTaxonomy + :keyword name: The name of the memory store. Required. + :paramtype name: str + :keyword definition: The memory store definition. Required. + :paramtype definition: ~azure.ai.projects.models.MemoryStoreDefinition :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationTaxonomy + :keyword description: A human-readable description of the memory store. Default value is None. + :paramtype description: str + :keyword metadata: Arbitrary key-value metadata to associate with the memory store. Default + value is None. + :paramtype metadata: dict[str, str] + :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDetails :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update( - self, name: str, taxonomy: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationTaxonomy: - """Update an evaluation taxonomy. + """ - :param name: The name of the evaluation taxonomy. Required. - :type name: str - :param taxonomy: The evaluation taxonomy. Required. - :type taxonomy: JSON + @overload + def create( + self, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryStoreDetails: + """Create a memory store. + + :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: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationTaxonomy + :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDetails :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def update( - self, name: str, taxonomy: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationTaxonomy: - """Update an evaluation taxonomy. + def create( + self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryStoreDetails: + """Create a memory store. - :param name: The name of the evaluation taxonomy. Required. - :type name: str - :param taxonomy: The evaluation taxonomy. Required. - :type taxonomy: IO[bytes] + :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: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationTaxonomy + :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDetails :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def update( - self, name: str, taxonomy: Union[_models.EvaluationTaxonomy, JSON, IO[bytes]], **kwargs: Any - ) -> _models.EvaluationTaxonomy: - """Update an evaluation taxonomy. + def create( + self, + body: Union[JSON, IO[bytes]] = _Unset, + *, + name: str = _Unset, + definition: _models.MemoryStoreDefinition = _Unset, + description: Optional[str] = None, + metadata: Optional[dict[str, str]] = None, + **kwargs: Any + ) -> _models.MemoryStoreDetails: + """Create a memory store. - :param name: The name of the evaluation taxonomy. Required. - :type name: str - :param taxonomy: The evaluation taxonomy. Is one of the following types: EvaluationTaxonomy, - JSON, IO[bytes] Required. - :type taxonomy: ~azure.ai.projects.models.EvaluationTaxonomy or JSON or IO[bytes] - :return: EvaluationTaxonomy. The EvaluationTaxonomy is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationTaxonomy + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword name: The name of the memory store. Required. + :paramtype name: str + :keyword definition: The memory store definition. Required. + :paramtype definition: ~azure.ai.projects.models.MemoryStoreDefinition + :keyword description: A human-readable description of the memory store. Default value is None. + :paramtype description: str + :keyword metadata: Arbitrary key-value metadata to associate with the memory store. Default + value is None. + :paramtype metadata: dict[str, str] + :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDetails :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -7355,17 +10773,23 @@ def update( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.EvaluationTaxonomy] = kwargs.pop("cls", None) + cls: ClsType[_models.MemoryStoreDetails] = kwargs.pop("cls", None) + if body is _Unset: + if name is _Unset: + raise TypeError("missing required argument: name") + if definition is _Unset: + raise TypeError("missing required argument: definition") + body = {"definition": definition, "description": description, "metadata": metadata, "name": name} + 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(taxonomy, (IOBase, bytes)): - _content = taxonomy + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(taxonomy, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_evaluation_taxonomies_update_request( - name=name, + _request = build_beta_memory_stores_create_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -7392,169 +10816,110 @@ def update( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.EvaluationTaxonomy, response.json()) + deserialized = _deserialize(_models.MemoryStoreDetails, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - -class BetaEvaluatorsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.ai.projects.AIProjectClient`'s - :attr:`evaluators` 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: AIProjectClientConfiguration = 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_versions( + @overload + def update( self, name: str, *, - type: Optional[Union[Literal["builtin"], Literal["custom"], Literal["all"], str]] = None, - limit: Optional[int] = None, + content_type: str = "application/json", + description: Optional[str] = None, + metadata: Optional[dict[str, str]] = None, **kwargs: Any - ) -> ItemPaged["_models.EvaluatorVersion"]: - """List all versions of the given evaluator. + ) -> _models.MemoryStoreDetails: + """Update a memory store. - :param name: The name of the resource. Required. + :param name: The name of the memory store to update. Required. :type name: str - :keyword type: Filter evaluators by type. Possible values: 'all', 'custom', 'builtin'. Is one - of the following types: Literal["builtin"], Literal["custom"], Literal["all"], str Default + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword description: A human-readable description of the memory store. Default value is None. + :paramtype description: str + :keyword metadata: Arbitrary key-value metadata to associate with the memory store. Default value is None. - :paramtype type: str or str or str or str - :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and - 100, and the default is 20. Default value is None. - :paramtype limit: int - :return: An iterator like instance of EvaluatorVersion - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.EvaluatorVersion] + :paramtype metadata: dict[str, str] + :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDetails :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.EvaluatorVersion]] = 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_beta_evaluators_list_versions_request( - name=name, - type=type, - limit=limit, - 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, - headers=_headers, - ) - 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.EvaluatorVersion], - 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 + @overload + def update( + self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryStoreDetails: + """Update a memory store. - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + :param name: The name of the memory store to update. Required. + :type 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: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ - return pipeline_response + @overload + def update( + self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryStoreDetails: + """Update a memory store. - return ItemPaged(get_next, extract_data) + :param name: The name of the memory store to update. Required. + :type 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: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace - def list( + def update( self, + name: str, + body: Union[JSON, IO[bytes]] = _Unset, *, - type: Optional[Union[Literal["builtin"], Literal["custom"], Literal["all"], str]] = None, - limit: Optional[int] = None, + description: Optional[str] = None, + metadata: Optional[dict[str, str]] = None, **kwargs: Any - ) -> ItemPaged["_models.EvaluatorVersion"]: - """List the latest version of each evaluator. + ) -> _models.MemoryStoreDetails: + """Update a memory store. - :keyword type: Filter evaluators by type. Possible values: 'all', 'custom', 'builtin'. Is one - of the following types: Literal["builtin"], Literal["custom"], Literal["all"], str Default + :param name: The name of the memory store to update. Required. + :type name: str + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword description: A human-readable description of the memory store. Default value is None. + :paramtype description: str + :keyword metadata: Arbitrary key-value metadata to associate with the memory store. Default value is None. - :paramtype type: str or str or str or str - :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and - 100, and the default is 20. Default value is None. - :paramtype limit: int - :return: An iterator like instance of EvaluatorVersion - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.EvaluatorVersion] + :paramtype metadata: dict[str, str] + :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDetails :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.EvaluatorVersion]] = kwargs.pop("cls", None) - error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -7563,86 +10928,74 @@ def list( } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} - _request = build_beta_evaluators_list_request( - type=type, - limit=limit, - 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) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MemoryStoreDetails] = kwargs.pop("cls", None) - 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, - headers=_headers, - ) - 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) + if body is _Unset: + body = {"description": description, "metadata": metadata} + 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 - return _request + _request = build_beta_memory_stores_update_request( + name=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) - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize( - List[_models.EvaluatorVersion], - deserialized.get("value", []), - ) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("nextLink") or None, iter(list_of_elem) + _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 + ) - def get_next(next_link=None): - _request = prepare_request(next_link) + response = pipeline_response.http_response - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, ) - response = pipeline_response.http_response + raise HttpResponseError(response=response, model=error) - if response.status_code not in [200]: - 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.MemoryStoreDetails, response.json()) - return pipeline_response + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore - return ItemPaged(get_next, extract_data) + return deserialized # type: ignore @distributed_trace - def get_version(self, name: str, version: str, **kwargs: Any) -> _models.EvaluatorVersion: - """Get the specific version of the EvaluatorVersion. The service returns 404 Not Found error if - the EvaluatorVersion does not exist. + def get(self, name: str, **kwargs: Any) -> _models.MemoryStoreDetails: + """Retrieve a memory store. - :param name: The name of the resource. Required. + :param name: The name of the memory store to retrieve. Required. :type name: str - :param version: The specific version id of the EvaluatorVersion to retrieve. Required. - :type version: str - :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorVersion + :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDetails :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -7656,11 +11009,10 @@ def get_version(self, name: str, version: str, **kwargs: Any) -> _models.Evaluat _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.EvaluatorVersion] = kwargs.pop("cls", None) + cls: ClsType[_models.MemoryStoreDetails] = kwargs.pop("cls", None) - _request = build_beta_evaluators_get_version_request( + _request = build_beta_memory_stores_get_request( name=name, - version=version, api_version=self._config.api_version, headers=_headers, params=_params, @@ -7685,31 +11037,120 @@ def get_version(self, name: str, version: str, **kwargs: Any) -> _models.Evaluat except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.EvaluatorVersion, response.json()) + deserialized = _deserialize(_models.MemoryStoreDetails, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized # type: ignore + return deserialized # type: ignore + + @distributed_trace + def list( + self, + *, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + before: Optional[str] = None, + **kwargs: Any + ) -> ItemPaged["_models.MemoryStoreDetails"]: + """List all memory stores. + + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :return: An iterator like instance of MemoryStoreDetails + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.MemoryStoreDetails] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.MemoryStoreDetails]] = 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(_continuation_token=None): + + _request = build_beta_memory_stores_list_request( + limit=limit, + order=order, + after=_continuation_token, + before=before, + 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) + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.MemoryStoreDetails], + deserialized.get("data", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("last_id") or None, iter(list_of_elem) + + def get_next(_continuation_token=None): + _request = prepare_request(_continuation_token) + + _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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) @distributed_trace - def delete_version( # pylint: disable=inconsistent-return-statements - self, name: str, version: str, **kwargs: Any - ) -> None: - """Delete the specific version of the EvaluatorVersion. The service returns 204 No Content if the - EvaluatorVersion was deleted successfully or if the EvaluatorVersion does not exist. + def delete(self, name: str, **kwargs: Any) -> _models.DeleteMemoryStoreResult: + """Delete a memory store. - :param name: The name of the resource. Required. + :param name: The name of the memory store to delete. Required. :type name: str - :param version: The version of the EvaluatorVersion to delete. Required. - :type version: str - :return: None - :rtype: None + :return: DeleteMemoryStoreResult. The DeleteMemoryStoreResult is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DeleteMemoryStoreResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -7723,11 +11164,10 @@ def delete_version( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models.DeleteMemoryStoreResult] = kwargs.pop("cls", None) - _request = build_beta_evaluators_delete_version_request( + _request = build_beta_memory_stores_delete_request( name=name, - version=version, api_version=self._config.api_version, headers=_headers, params=_params, @@ -7737,92 +11177,88 @@ def delete_version( # pylint: disable=inconsistent-return-statements } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 [204]: + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.DeleteMemoryStoreResult, response.json()) if cls: - return cls(pipeline_response, None, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore @overload - def create_version( + def _search_memories( self, name: str, - evaluator_version: _models.EvaluatorVersion, *, + scope: str, content_type: str = "application/json", + items: Optional[List[dict[str, Any]]] = None, + previous_search_id: Optional[str] = None, + options: Optional[_models.MemorySearchOptions] = None, **kwargs: Any - ) -> _models.EvaluatorVersion: - """Create a new EvaluatorVersion with auto incremented version id. - - :param name: The name of the resource. Required. - :type name: str - :param evaluator_version: Required. - :type evaluator_version: ~azure.ai.projects.models.EvaluatorVersion - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - + ) -> _models.MemoryStoreSearchResult: ... @overload - def create_version( - self, name: str, evaluator_version: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluatorVersion: - """Create a new EvaluatorVersion with auto incremented version id. - - :param name: The name of the resource. Required. - :type name: str - :param evaluator_version: Required. - :type evaluator_version: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - + def _search_memories( + self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryStoreSearchResult: ... @overload - def create_version( - self, name: str, evaluator_version: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluatorVersion: - """Create a new EvaluatorVersion with auto incremented version id. - - :param name: The name of the resource. Required. - :type name: str - :param evaluator_version: Required. - :type evaluator_version: 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: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ + def _search_memories( + self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryStoreSearchResult: ... @distributed_trace - def create_version( - self, name: str, evaluator_version: Union[_models.EvaluatorVersion, JSON, IO[bytes]], **kwargs: Any - ) -> _models.EvaluatorVersion: - """Create a new EvaluatorVersion with auto incremented version id. + def _search_memories( + self, + name: str, + body: Union[JSON, IO[bytes]] = _Unset, + *, + scope: str = _Unset, + items: Optional[List[dict[str, Any]]] = None, + previous_search_id: Optional[str] = None, + options: Optional[_models.MemorySearchOptions] = None, + **kwargs: Any + ) -> _models.MemoryStoreSearchResult: + """Search for relevant memories from a memory store based on conversation context. - :param name: The name of the resource. Required. + :param name: The name of the memory store to search. Required. :type name: str - :param evaluator_version: Is one of the following types: EvaluatorVersion, JSON, IO[bytes] + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword scope: The namespace that logically groups and isolates memories, such as a user ID. Required. - :type evaluator_version: ~azure.ai.projects.models.EvaluatorVersion or JSON or IO[bytes] - :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorVersion + :paramtype scope: str + :keyword items: Items for which to search for relevant memories. Default value is None. + :paramtype items: list[dict[str, any]] + :keyword previous_search_id: The unique ID of the previous search request, enabling incremental + memory search from where the last operation left off. Default value is None. + :paramtype previous_search_id: str + :keyword options: Memory search options. Default value is None. + :paramtype options: ~azure.ai.projects.models.MemorySearchOptions + :return: MemoryStoreSearchResult. The MemoryStoreSearchResult is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreSearchResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -7837,16 +11273,26 @@ def create_version( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.EvaluatorVersion] = kwargs.pop("cls", None) + cls: ClsType[_models.MemoryStoreSearchResult] = kwargs.pop("cls", None) + if body is _Unset: + if scope is _Unset: + raise TypeError("missing required argument: scope") + body = { + "items": items, + "options": options, + "previous_search_id": previous_search_id, + "scope": scope, + } + 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(evaluator_version, (IOBase, bytes)): - _content = evaluator_version + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(evaluator_version, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_evaluators_create_version_request( + _request = build_beta_memory_stores_search_memories_request( name=name, content_type=content_type, api_version=self._config.api_version, @@ -7867,118 +11313,40 @@ def create_version( response = pipeline_response.http_response - if response.status_code not in [201]: + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.EvaluatorVersion, response.json()) + deserialized = _deserialize(_models.MemoryStoreSearchResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @overload - def update_version( - self, - name: str, - version: str, - evaluator_version: _models.EvaluatorVersion, - *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.EvaluatorVersion: - """Update an existing EvaluatorVersion with the given version id. - - :param name: The name of the resource. Required. - :type name: str - :param version: The version of the EvaluatorVersion to update. Required. - :type version: str - :param evaluator_version: Evaluator resource. Required. - :type evaluator_version: ~azure.ai.projects.models.EvaluatorVersion - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update_version( - self, name: str, version: str, evaluator_version: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluatorVersion: - """Update an existing EvaluatorVersion with the given version id. - - :param name: The name of the resource. Required. - :type name: str - :param version: The version of the EvaluatorVersion to update. Required. - :type version: str - :param evaluator_version: Evaluator resource. Required. - :type evaluator_version: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update_version( + def _update_memories_initial( self, name: str, - version: str, - evaluator_version: IO[bytes], + body: Union[JSON, IO[bytes]] = _Unset, *, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.EvaluatorVersion: - """Update an existing EvaluatorVersion with the given version id. - - :param name: The name of the resource. Required. - :type name: str - :param version: The version of the EvaluatorVersion to update. Required. - :type version: str - :param evaluator_version: Evaluator resource. Required. - :type evaluator_version: 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: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def update_version( - self, - name: str, - version: str, - evaluator_version: Union[_models.EvaluatorVersion, JSON, IO[bytes]], + scope: str = _Unset, + items: Optional[List[dict[str, Any]]] = None, + previous_update_id: Optional[str] = None, + update_delay: Optional[int] = None, **kwargs: Any - ) -> _models.EvaluatorVersion: - """Update an existing EvaluatorVersion with the given version id. - - :param name: The name of the resource. Required. - :type name: str - :param version: The version of the EvaluatorVersion to update. Required. - :type version: str - :param evaluator_version: Evaluator resource. Is one of the following types: EvaluatorVersion, - JSON, IO[bytes] Required. - :type evaluator_version: ~azure.ai.projects.models.EvaluatorVersion or JSON or IO[bytes] - :return: EvaluatorVersion. The EvaluatorVersion is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorVersion - :raises ~azure.core.exceptions.HttpResponseError: - """ + ) -> Iterator[bytes]: error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -7991,18 +11359,27 @@ def update_version( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.EvaluatorVersion] = kwargs.pop("cls", None) + cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) + if body is _Unset: + if scope is _Unset: + raise TypeError("missing required argument: scope") + body = { + "items": items, + "previous_update_id": previous_update_id, + "scope": scope, + "update_delay": update_delay, + } + 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(evaluator_version, (IOBase, bytes)): - _content = evaluator_version + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(evaluator_version, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_evaluators_update_version_request( + _request = build_beta_memory_stores_update_memories_request( name=name, - version=version, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -8015,129 +11392,228 @@ def update_version( _request.url = self._client.format_url(_request.url, **path_format_arguments) _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _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]: - if _stream: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.EvaluatorVersion, response.json()) + 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, {}) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore @overload - def create_generation_job( + def _begin_update_memories( self, - job: _models.EvaluatorGenerationJob, + name: str, *, - operation_id: Optional[str] = None, + scope: str, content_type: str = "application/json", + items: Optional[List[dict[str, Any]]] = None, + previous_update_id: Optional[str] = None, + update_delay: Optional[int] = None, **kwargs: Any - ) -> _models.EvaluatorGenerationJob: - """Creates an evaluator generation job. + ) -> LROPoller[_models.MemoryStoreUpdateCompletedResult]: ... + @overload + def _begin_update_memories( + self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.MemoryStoreUpdateCompletedResult]: ... + @overload + def _begin_update_memories( + self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> LROPoller[_models.MemoryStoreUpdateCompletedResult]: ... - Creates an evaluator generation job. The service generates rubric-based evaluator definitions - from the provided source materials asynchronously. + @distributed_trace + def _begin_update_memories( + self, + name: str, + body: Union[JSON, IO[bytes]] = _Unset, + *, + scope: str = _Unset, + items: Optional[List[dict[str, Any]]] = None, + previous_update_id: Optional[str] = None, + update_delay: Optional[int] = None, + **kwargs: Any + ) -> LROPoller[_models.MemoryStoreUpdateCompletedResult]: + """Update memory store with conversation memories. - :param job: The job to create. Required. - :type job: ~azure.ai.projects.models.EvaluatorGenerationJob - :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the - server creates the job unconditionally. Default value is None. - :paramtype operation_id: str + :param name: The name of the memory store to update. Required. + :type name: str + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword scope: The namespace that logically groups and isolates memories, such as a user ID. + Required. + :paramtype scope: str + :keyword items: Conversation items to be stored in memory. Default value is None. + :paramtype items: list[dict[str, any]] + :keyword previous_update_id: The unique ID of the previous update request, enabling incremental + memory updates from where the last operation left off. Default value is None. + :paramtype previous_update_id: str + :keyword update_delay: Timeout period before processing the memory update in seconds. + If a new update request is received during this period, it will cancel the current request and + reset the timeout. + Set to 0 to immediately trigger the update without delay. + Defaults to 300 (5 minutes). Default value is None. + :paramtype update_delay: int + :return: An instance of LROPoller that returns MemoryStoreUpdateCompletedResult. The + MemoryStoreUpdateCompletedResult is compatible with MutableMapping + :rtype: + ~azure.core.polling.LROPoller[~azure.ai.projects.models.MemoryStoreUpdateCompletedResult] + :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.MemoryStoreUpdateCompletedResult] = 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._update_memories_initial( + name=name, + body=body, + scope=scope, + items=items, + previous_update_id=previous_update_id, + update_delay=update_delay, + 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.MemoryStoreUpdateCompletedResult, 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.MemoryStoreUpdateCompletedResult].from_continuation_token( + polling_method=polling_method, + continuation_token=cont_token, + client=self._client, + deserialization_callback=get_long_running_output, + ) + return LROPoller[_models.MemoryStoreUpdateCompletedResult]( + self._client, raw_result, get_long_running_output, polling_method # type: ignore + ) + + @overload + def delete_scope( + self, name: str, *, scope: str, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryStoreDeleteScopeResult: + """Delete all memories associated with a specific scope from a memory store. + + :param name: The name of the memory store. Required. + :type name: str + :keyword scope: The namespace that logically groups and isolates memories to delete, such as a + user ID. Required. + :paramtype scope: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob + :return: MemoryStoreDeleteScopeResult. The MemoryStoreDeleteScopeResult is compatible with + MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDeleteScopeResult :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_generation_job( - self, job: JSON, *, operation_id: Optional[str] = None, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluatorGenerationJob: - """Creates an evaluator generation job. - - Creates an evaluator generation job. The service generates rubric-based evaluator definitions - from the provided source materials asynchronously. + def delete_scope( + self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryStoreDeleteScopeResult: + """Delete all memories associated with a specific scope from a memory store. - :param job: The job to create. Required. - :type job: JSON - :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the - server creates the job unconditionally. Default value is None. - :paramtype operation_id: str + :param name: The name of the memory store. Required. + :type 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: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob + :return: MemoryStoreDeleteScopeResult. The MemoryStoreDeleteScopeResult is compatible with + MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDeleteScopeResult :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_generation_job( - self, - job: IO[bytes], - *, - operation_id: Optional[str] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.EvaluatorGenerationJob: - """Creates an evaluator generation job. - - Creates an evaluator generation job. The service generates rubric-based evaluator definitions - from the provided source materials asynchronously. + def delete_scope( + self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryStoreDeleteScopeResult: + """Delete all memories associated with a specific scope from a memory store. - :param job: The job to create. Required. - :type job: IO[bytes] - :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the - server creates the job unconditionally. Default value is None. - :paramtype operation_id: str + :param name: The name of the memory store. Required. + :type 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: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob + :return: MemoryStoreDeleteScopeResult. The MemoryStoreDeleteScopeResult is compatible with + MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDeleteScopeResult :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def create_generation_job( - self, - job: Union[_models.EvaluatorGenerationJob, JSON, IO[bytes]], - *, - operation_id: Optional[str] = None, - **kwargs: Any - ) -> _models.EvaluatorGenerationJob: - """Creates an evaluator generation job. - - Creates an evaluator generation job. The service generates rubric-based evaluator definitions - from the provided source materials asynchronously. + def delete_scope( + self, name: str, body: Union[JSON, IO[bytes]] = _Unset, *, scope: str = _Unset, **kwargs: Any + ) -> _models.MemoryStoreDeleteScopeResult: + """Delete all memories associated with a specific scope from a memory store. - :param job: The job to create. Is one of the following types: EvaluatorGenerationJob, JSON, - IO[bytes] Required. - :type job: ~azure.ai.projects.models.EvaluatorGenerationJob or JSON or IO[bytes] - :keyword operation_id: Client-generated unique ID for idempotent retries. When absent, the - server creates the job unconditionally. Default value is None. - :paramtype operation_id: str - :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob + :param name: The name of the memory store. Required. + :type name: str + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword scope: The namespace that logically groups and isolates memories to delete, such as a + user ID. Required. + :paramtype scope: str + :return: MemoryStoreDeleteScopeResult. The MemoryStoreDeleteScopeResult is compatible with + MutableMapping + :rtype: ~azure.ai.projects.models.MemoryStoreDeleteScopeResult :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -8152,17 +11628,22 @@ def create_generation_job( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.EvaluatorGenerationJob] = kwargs.pop("cls", None) + cls: ClsType[_models.MemoryStoreDeleteScopeResult] = kwargs.pop("cls", None) + if body is _Unset: + if scope is _Unset: + raise TypeError("missing required argument: scope") + body = {"scope": scope} + 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(job, (IOBase, bytes)): - _content = job + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(job, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_evaluators_create_generation_job_request( - operation_id=operation_id, + _request = build_beta_memory_stores_delete_scope_request( + name=name, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -8182,7 +11663,7 @@ def create_generation_job( response = pipeline_response.http_response - if response.status_code not in [201]: + if response.status_code not in [200]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -8195,30 +11676,110 @@ def create_generation_job( ) raise HttpResponseError(response=response, model=error) - response_headers = {} - response_headers["Operation-Location"] = self._deserialize("str", response.headers.get("Operation-Location")) - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.EvaluatorGenerationJob, response.json()) + deserialized = _deserialize(_models.MemoryStoreDeleteScopeResult, response.json()) if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @distributed_trace - def get_generation_job(self, job_id: str, **kwargs: Any) -> _models.EvaluatorGenerationJob: - """Get info about an evaluator generation job. + @overload + def create_memory( + self, + name: str, + *, + scope: str, + content: str, + kind: Union[str, _models.MemoryItemKind], + content_type: str = "application/json", + **kwargs: Any + ) -> _models.MemoryItem: + """Create a memory item in a memory store. - Gets the details of an evaluator generation job by its ID. + :param name: The name of the memory store. Required. + :type name: str + :keyword scope: The namespace that logically groups and isolates memories, such as a user ID. + Required. + :paramtype scope: str + :keyword content: The content of the memory. Required. + :paramtype content: str + :keyword kind: The kind of the memory item. Known values are: "user_profile", "chat_summary", + and "procedural". Required. + :paramtype kind: str or ~azure.ai.projects.models.MemoryItemKind + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: MemoryItem. The MemoryItem is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryItem + :raises ~azure.core.exceptions.HttpResponseError: + """ - :param job_id: The ID of the job. Required. - :type job_id: str - :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob + @overload + def create_memory( + self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryItem: + """Create a memory item in a memory store. + + :param name: The name of the memory store. Required. + :type 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: MemoryItem. The MemoryItem is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryItem + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create_memory( + self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryItem: + """Create a memory item in a memory store. + + :param name: The name of the memory store. Required. + :type 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: MemoryItem. The MemoryItem is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryItem + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_memory( + self, + name: str, + body: Union[JSON, IO[bytes]] = _Unset, + *, + scope: str = _Unset, + content: str = _Unset, + kind: Union[str, _models.MemoryItemKind] = _Unset, + **kwargs: Any + ) -> _models.MemoryItem: + """Create a memory item in a memory store. + + :param name: The name of the memory store. Required. + :type name: str + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword scope: The namespace that logically groups and isolates memories, such as a user ID. + Required. + :paramtype scope: str + :keyword content: The content of the memory. Required. + :paramtype content: str + :keyword kind: The kind of the memory item. Known values are: "user_profile", "chat_summary", + and "procedural". Required. + :paramtype kind: str or ~azure.ai.projects.models.MemoryItemKind + :return: MemoryItem. The MemoryItem is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryItem :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -8229,14 +11790,33 @@ def get_generation_job(self, job_id: str, **kwargs: Any) -> _models.EvaluatorGen } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.EvaluatorGenerationJob] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MemoryItem] = kwargs.pop("cls", None) - _request = build_beta_evaluators_get_generation_job_request( - job_id=job_id, + if body is _Unset: + if scope is _Unset: + raise TypeError("missing required argument: scope") + if content is _Unset: + raise TypeError("missing required argument: content") + if kind is _Unset: + raise TypeError("missing required argument: kind") + body = {"content": content, "kind": kind, "scope": scope} + 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_beta_memory_stores_create_memory_request( + name=name, + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -8266,126 +11846,92 @@ def get_generation_job(self, job_id: str, **kwargs: Any) -> _models.EvaluatorGen ) raise HttpResponseError(response=response, model=error) - response_headers = {} - response_headers["Retry-After"] = self._deserialize("int", response.headers.get("Retry-After")) - if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.EvaluatorGenerationJob, response.json()) + deserialized = _deserialize(_models.MemoryItem, response.json()) if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @distributed_trace - def list_generation_jobs( - self, - *, - limit: Optional[int] = None, - order: Optional[Union[str, _models.PageOrder]] = None, - before: Optional[str] = None, - category: Optional[Union[str, _models.EvaluatorCategory]] = None, - **kwargs: Any - ) -> ItemPaged["_models.EvaluatorGenerationJob"]: - """Returns a list of evaluator generation jobs. - - Returns a list of evaluator generation jobs. + @overload + def update_memory( + self, name: str, memory_id: str, *, content: str, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryItem: + """Update a memory item in a memory store. - :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and - 100, and the - default is 20. Default value is None. - :paramtype limit: int - :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for - ascending order and``desc`` - for descending order. Known values are: "asc" and "desc". Default value is None. - :paramtype order: str or ~azure.ai.projects.models.PageOrder - :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your - place in the list. - For instance, if you make a list request and receive 100 objects, ending with obj_foo, your - subsequent call can include before=obj_foo in order to fetch the previous page of the list. - Default value is None. - :paramtype before: str - :keyword category: Filter evaluator generation jobs by category. Known values are: "quality", - "safety", and "agents". Default value is None. - :paramtype category: str or ~azure.ai.projects.models.EvaluatorCategory - :return: An iterator like instance of EvaluatorGenerationJob - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.EvaluatorGenerationJob] + :param name: The name of the memory store. Required. + :type name: str + :param memory_id: The ID of the memory item to update. Required. + :type memory_id: str + :keyword content: The updated content of the memory. Required. + :paramtype content: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: MemoryItem. The MemoryItem is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryItem :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.EvaluatorGenerationJob]] = 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(_continuation_token=None): - - _request = build_beta_evaluators_list_generation_jobs_request( - limit=limit, - order=order, - after=_continuation_token, - before=before, - category=category, - 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) - return _request - - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize( - List[_models.EvaluatorGenerationJob], - deserialized.get("data", []), - ) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("last_id") or None, iter(list_of_elem) - - def get_next(_continuation_token=None): - _request = prepare_request(_continuation_token) - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response + @overload + def update_memory( + self, name: str, memory_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryItem: + """Update a memory item in a memory store. - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) + :param name: The name of the memory store. Required. + :type name: str + :param memory_id: The ID of the memory item to update. Required. + :type memory_id: 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: MemoryItem. The MemoryItem is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryItem + :raises ~azure.core.exceptions.HttpResponseError: + """ - return pipeline_response + @overload + def update_memory( + self, name: str, memory_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.MemoryItem: + """Update a memory item in a memory store. - return ItemPaged(get_next, extract_data) + :param name: The name of the memory store. Required. + :type name: str + :param memory_id: The ID of the memory item to update. Required. + :type memory_id: 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: MemoryItem. The MemoryItem is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryItem + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace - def cancel_generation_job(self, job_id: str, **kwargs: Any) -> _models.EvaluatorGenerationJob: - """Cancels an evaluator generation job. - - Cancels an evaluator generation job by its ID. + def update_memory( + self, name: str, memory_id: str, body: Union[JSON, IO[bytes]] = _Unset, *, content: str = _Unset, **kwargs: Any + ) -> _models.MemoryItem: + """Update a memory item in a memory store. - :param job_id: The ID of the job to cancel. Required. - :type job_id: str - :return: EvaluatorGenerationJob. The EvaluatorGenerationJob is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluatorGenerationJob + :param name: The name of the memory store. Required. + :type name: str + :param memory_id: The ID of the memory item to update. Required. + :type memory_id: str + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword content: The updated content of the memory. Required. + :paramtype content: str + :return: MemoryItem. The MemoryItem is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryItem :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -8396,14 +11942,30 @@ def cancel_generation_job(self, job_id: str, **kwargs: Any) -> _models.Evaluator } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.EvaluatorGenerationJob] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.MemoryItem] = kwargs.pop("cls", None) - _request = build_beta_evaluators_cancel_generation_job_request( - job_id=job_id, + if body is _Unset: + if content is _Unset: + raise TypeError("missing required argument: content") + body = {"content": content} + 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_beta_memory_stores_update_memory_request( + name=name, + memory_id=memory_id, + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -8436,7 +11998,7 @@ def cancel_generation_job(self, job_id: str, **kwargs: Any) -> _models.Evaluator if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.EvaluatorGenerationJob, response.json()) + deserialized = _deserialize(_models.MemoryItem, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -8444,16 +12006,15 @@ def cancel_generation_job(self, job_id: str, **kwargs: Any) -> _models.Evaluator return deserialized # type: ignore @distributed_trace - def delete_generation_job( # pylint: disable=inconsistent-return-statements - self, job_id: str, **kwargs: Any - ) -> None: - """Deletes an evaluator generation job by its ID. Deletes the job record only; the generated - evaluator (if any) is preserved. + def get_memory(self, name: str, memory_id: str, **kwargs: Any) -> _models.MemoryItem: + """Retrieve a memory item from a memory store. - :param job_id: The ID of the job to delete. Required. - :type job_id: str - :return: None - :rtype: None + :param name: The name of the memory store. Required. + :type name: str + :param memory_id: The ID of the memory item to retrieve. Required. + :type memory_id: str + :return: MemoryItem. The MemoryItem is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.MemoryItem :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -8467,10 +12028,11 @@ def delete_generation_job( # pylint: disable=inconsistent-return-statements _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[None] = kwargs.pop("cls", None) + cls: ClsType[_models.MemoryItem] = kwargs.pop("cls", None) - _request = build_beta_evaluators_delete_generation_job_request( - job_id=job_id, + _request = build_beta_memory_stores_get_memory_request( + name=name, + memory_id=memory_id, api_version=self._config.api_version, headers=_headers, params=_params, @@ -8480,14 +12042,20 @@ def delete_generation_job( # pylint: disable=inconsistent-return-statements } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _stream = False + _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 [204]: + 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) error = _failsafe_deserialize( _models.ApiErrorResponse, @@ -8495,83 +12063,279 @@ def delete_generation_job( # pylint: disable=inconsistent-return-statements ) raise HttpResponseError(response=response, model=error) + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.MemoryItem, response.json()) + if cls: - return cls(pipeline_response, None, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore + return deserialized # type: ignore -class BetaInsightsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. + @overload + def list_memories( + self, + name: str, + *, + scope: str, + kind: Optional[Union[str, _models.MemoryItemKind]] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + before: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> ItemPaged["_models.MemoryItem"]: + """List all memory items in a memory store. - Instead, you should access the following operations through - :class:`~azure.ai.projects.AIProjectClient`'s - :attr:`insights` attribute. - """ + :param name: The name of the memory store. Required. + :type name: str + :keyword scope: The namespace that logically groups and isolates memories, such as a user ID. + Required. + :paramtype scope: str + :keyword kind: The kind of the memory item. Known values are: "user_profile", "chat_summary", + and "procedural". Default value is None. + :paramtype kind: str or ~azure.ai.projects.models.MemoryItemKind + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An iterator like instance of MemoryItem + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.MemoryItem] + :raises ~azure.core.exceptions.HttpResponseError: + """ - 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: AIProjectClientConfiguration = 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 list_memories( + self, + name: str, + body: JSON, + *, + kind: Optional[Union[str, _models.MemoryItemKind]] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + before: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> ItemPaged["_models.MemoryItem"]: + """List all memory items in a memory store. + + :param name: The name of the memory store. Required. + :type name: str + :param body: Required. + :type body: JSON + :keyword kind: The kind of the memory item. Known values are: "user_profile", "chat_summary", + and "procedural". Default value is None. + :paramtype kind: str or ~azure.ai.projects.models.MemoryItemKind + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: An iterator like instance of MemoryItem + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.MemoryItem] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def list_memories( + self, + name: str, + body: IO[bytes], + *, + kind: Optional[Union[str, _models.MemoryItemKind]] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + before: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any + ) -> ItemPaged["_models.MemoryItem"]: + """List all memory items in a memory store. + + :param name: The name of the memory store. Required. + :type name: str + :param body: Required. + :type body: IO[bytes] + :keyword kind: The kind of the memory item. Known values are: "user_profile", "chat_summary", + and "procedural". Default value is None. + :paramtype kind: str or ~azure.ai.projects.models.MemoryItemKind + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: An iterator like instance of MemoryItem + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.MemoryItem] + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def list_memories( + self, + name: str, + body: Union[JSON, IO[bytes]] = _Unset, + *, + scope: str = _Unset, + kind: Optional[Union[str, _models.MemoryItemKind]] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + before: Optional[str] = None, + **kwargs: Any + ) -> ItemPaged["_models.MemoryItem"]: + """List all memory items in a memory store. + + :param name: The name of the memory store. Required. + :type name: str + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword scope: The namespace that logically groups and isolates memories, such as a user ID. + Required. + :paramtype scope: str + :keyword kind: The kind of the memory item. Known values are: "user_profile", "chat_summary", + and "procedural". Default value is None. + :paramtype kind: str or ~azure.ai.projects.models.MemoryItemKind + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :return: An iterator like instance of MemoryItem + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.MemoryItem] + :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[List[_models.MemoryItem]] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + 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 + + def prepare_request(_continuation_token=None): + if body is _Unset: + if scope is _Unset: + raise TypeError("missing required argument: scope") + body = {"scope": scope} + body = {k: v for k, v in body.items() if v is not None} + + _request = build_beta_memory_stores_list_memories_request( + name=name, + kind=kind, + limit=limit, + order=order, + after=_continuation_token, + before=before, + 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) + return _request - @overload - def generate( - self, insight: _models.Insight, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Insight: - """Generate Insights. + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.MemoryItem], + deserialized.get("data", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("last_id") or None, iter(list_of_elem) - :param insight: Complete evaluation configuration including data source, evaluators, and result - settings. Required. - :type insight: ~azure.ai.projects.models.Insight - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Insight. The Insight is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Insight - :raises ~azure.core.exceptions.HttpResponseError: - """ + def get_next(_continuation_token=None): + _request = prepare_request(_continuation_token) - @overload - def generate(self, insight: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Insight: - """Generate Insights. + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - :param insight: Complete evaluation configuration including data source, evaluators, and result - settings. Required. - :type insight: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Insight. The Insight is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Insight - :raises ~azure.core.exceptions.HttpResponseError: - """ + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) - @overload - def generate(self, insight: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> _models.Insight: - """Generate Insights. + return pipeline_response - :param insight: Complete evaluation configuration including data source, evaluators, and result - settings. Required. - :type insight: 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: Insight. The Insight is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Insight - :raises ~azure.core.exceptions.HttpResponseError: - """ + return ItemPaged(get_next, extract_data) @distributed_trace - def generate(self, insight: Union[_models.Insight, JSON, IO[bytes]], **kwargs: Any) -> _models.Insight: - """Generate Insights. + def delete_memory(self, name: str, memory_id: str, **kwargs: Any) -> _models.DeleteMemoryResponse: + """Delete a memory item from a memory store. - :param insight: Complete evaluation configuration including data source, evaluators, and result - settings. Is one of the following types: Insight, JSON, IO[bytes] Required. - :type insight: ~azure.ai.projects.models.Insight or JSON or IO[bytes] - :return: Insight. The Insight is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Insight + :param name: The name of the memory store. Required. + :type name: str + :param memory_id: The ID of the memory item to delete. Required. + :type memory_id: str + :return: DeleteMemoryResponse. The DeleteMemoryResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DeleteMemoryResponse :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -8582,23 +12346,15 @@ def generate(self, insight: Union[_models.Insight, JSON, IO[bytes]], **kwargs: A } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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.Insight] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(insight, (IOBase, bytes)): - _content = insight - else: - _content = json.dumps(insight, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + cls: ClsType[_models.DeleteMemoryResponse] = kwargs.pop("cls", None) - _request = build_beta_insights_generate_request( - content_type=content_type, + _request = build_beta_memory_stores_delete_memory_request( + name=name, + memory_id=memory_id, api_version=self._config.api_version, - content=_content, headers=_headers, params=_params, ) @@ -8615,7 +12371,7 @@ def generate(self, insight: Union[_models.Insight, JSON, IO[bytes]], **kwargs: A response = pipeline_response.http_response - if response.status_code not in [201]: + if response.status_code not in [200]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -8631,26 +12387,46 @@ def generate(self, insight: Union[_models.Insight, JSON, IO[bytes]], **kwargs: A if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.Insight, response.json()) + deserialized = _deserialize(_models.DeleteMemoryResponse, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + +class BetaModelsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.AIProjectClient`'s + :attr:`models` 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: AIProjectClientConfiguration = 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 get(self, insight_id: str, *, include_coordinates: Optional[bool] = None, **kwargs: Any) -> _models.Insight: - """Get a specific insight by Id. + def list_versions(self, name: str, **kwargs: Any) -> ItemPaged["_models.ModelVersion"]: + """List all versions of the given ModelVersion. - :param insight_id: The unique identifier for the insights report. Required. - :type insight_id: str - :keyword include_coordinates: Whether to include coordinates for visualization in the response. - Defaults to false. Default value is None. - :paramtype include_coordinates: bool - :return: Insight. The Insight is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Insight + :param name: The name of the resource. Required. + :type name: str + :return: An iterator like instance of ModelVersion + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.ModelVersion] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.ModelVersion]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -8659,87 +12435,86 @@ def get(self, insight_id: str, *, include_coordinates: Optional[bool] = None, ** } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + def prepare_request(next_link=None): + if not next_link: - cls: ClsType[_models.Insight] = kwargs.pop("cls", None) + _request = build_beta_models_list_versions_request( + name=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) - _request = build_beta_insights_get_request( - insight_id=insight_id, - include_coordinates=include_coordinates, - 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, + headers=_headers, + ) + 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 - ) + return _request - response = pipeline_response.http_response + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.ModelVersion], + deserialized.get("value", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) - 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) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, + 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 ) - raise HttpResponseError(response=response, model=error) + response = pipeline_response.http_response - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.Insight, response.json()) + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return pipeline_response - return deserialized # type: ignore + return ItemPaged(get_next, extract_data) @distributed_trace - def list( - self, - *, - type: Optional[Union[str, _models.InsightType]] = None, - eval_id: Optional[str] = None, - run_id: Optional[str] = None, - agent_name: Optional[str] = None, - include_coordinates: Optional[bool] = None, - **kwargs: Any - ) -> ItemPaged["_models.Insight"]: - """List all insights in reverse chronological order (newest first). + def list(self, **kwargs: Any) -> ItemPaged["_models.ModelVersion"]: + """List the latest version of each ModelVersion. - :keyword type: Filter by the type of analysis. Known values are: "EvaluationRunClusterInsight", - "AgentClusterInsight", and "EvaluationComparison". Default value is None. - :paramtype type: str or ~azure.ai.projects.models.InsightType - :keyword eval_id: Filter by the evaluation ID. Default value is None. - :paramtype eval_id: str - :keyword run_id: Filter by the evaluation run ID. Default value is None. - :paramtype run_id: str - :keyword agent_name: Filter by the agent name. Default value is None. - :paramtype agent_name: str - :keyword include_coordinates: Whether to include coordinates for visualization in the response. - Defaults to false. Default value is None. - :paramtype include_coordinates: bool - :return: An iterator like instance of Insight - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.Insight] + :return: An iterator like instance of ModelVersion + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.ModelVersion] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.Insight]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.ModelVersion]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -8750,14 +12525,9 @@ def list( error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): - if not next_link: - - _request = build_beta_insights_list_request( - type=type, - eval_id=eval_id, - run_id=run_id, - agent_name=agent_name, - include_coordinates=include_coordinates, + if not next_link: + + _request = build_beta_models_list_request( api_version=self._config.api_version, headers=_headers, params=_params, @@ -8797,7 +12567,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() list_of_elem = _deserialize( - List[_models.Insight], + List[_models.ModelVersion], deserialized.get("value", []), ) if cls: @@ -8815,122 +12585,220 @@ def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) + raise HttpResponseError(response=response) return pipeline_response return ItemPaged(get_next, extract_data) + @distributed_trace + def get(self, name: str, version: str, **kwargs: Any) -> _models.ModelVersion: + """Get the specific version of the ModelVersion. The service returns 404 Not Found error if the + ModelVersion does not exist. -class BetaMemoryStoresOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the ModelVersion to retrieve. Required. + :type version: str + :return: ModelVersion. The ModelVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.ModelVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) - Instead, you should access the following operations through - :class:`~azure.ai.projects.AIProjectClient`'s - :attr:`memory_stores` attribute. - """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - 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: AIProjectClientConfiguration = 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") + cls: ClsType[_models.ModelVersion] = kwargs.pop("cls", None) + + _request = build_beta_models_get_request( + name=name, + version=version, + 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.ModelVersion, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def delete(self, name: str, version: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete the specific version of the ModelVersion. The service returns 200 OK if the ModelVersion + was deleted successfully or if the ModelVersion does not exist. + + :param name: The name of the resource. Required. + :type name: str + :param version: The version of the ModelVersion to delete. Required. + :type version: str + :return: None + :rtype: None + :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[None] = kwargs.pop("cls", None) + + _request = build_beta_models_delete_request( + name=name, + version=version, + 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) + + _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) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore @overload - def create( + def update( self, - *, name: str, - definition: _models.MemoryStoreDefinition, - content_type: str = "application/json", - description: Optional[str] = None, - metadata: Optional[dict[str, str]] = None, + version: str, + body: _models.UpdateModelVersionRequest, + *, + content_type: str = "application/merge-patch+json", **kwargs: Any - ) -> _models.MemoryStoreDetails: - """Create a memory store. + ) -> _models.ModelVersion: + """Update an existing ModelVersion with the given version id. - :keyword name: The name of the memory store. Required. - :paramtype name: str - :keyword definition: The memory store definition. Required. - :paramtype definition: ~azure.ai.projects.models.MemoryStoreDefinition + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the UpdateModelVersionRequest to create or update. + Required. + :type version: str + :param body: The UpdateModelVersionRequest to create or update. Required. + :type body: ~azure.ai.projects.models.UpdateModelVersionRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". + Default value is "application/merge-patch+json". :paramtype content_type: str - :keyword description: A human-readable description of the memory store. Default value is None. - :paramtype description: str - :keyword metadata: Arbitrary key-value metadata to associate with the memory store. Default - value is None. - :paramtype metadata: dict[str, str] - :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :return: ModelVersion. The ModelVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.ModelVersion :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.MemoryStoreDetails: - """Create a memory store. + def update( + self, name: str, version: str, body: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> _models.ModelVersion: + """Update an existing ModelVersion with the given version id. - :param body: Required. + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the UpdateModelVersionRequest to create or update. + Required. + :type version: str + :param body: The UpdateModelVersionRequest to create or update. Required. :type body: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". + Default value is "application/merge-patch+json". :paramtype content_type: str - :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :return: ModelVersion. The ModelVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.ModelVersion :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create( - self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.MemoryStoreDetails: - """Create a memory store. + def update( + self, + name: str, + version: str, + body: IO[bytes], + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> _models.ModelVersion: + """Update an existing ModelVersion with the given version id. - :param body: Required. + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the UpdateModelVersionRequest to create or update. + Required. + :type version: str + :param body: The UpdateModelVersionRequest to create or update. Required. :type body: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". + Default value is "application/merge-patch+json". :paramtype content_type: str - :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :return: ModelVersion. The ModelVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.ModelVersion :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def create( - self, - body: Union[JSON, IO[bytes]] = _Unset, - *, - name: str = _Unset, - definition: _models.MemoryStoreDefinition = _Unset, - description: Optional[str] = None, - metadata: Optional[dict[str, str]] = None, - **kwargs: Any - ) -> _models.MemoryStoreDetails: - """Create a memory store. + def update( + self, name: str, version: str, body: Union[_models.UpdateModelVersionRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.ModelVersion: + """Update an existing ModelVersion with the given version id. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword name: The name of the memory store. Required. - :paramtype name: str - :keyword definition: The memory store definition. Required. - :paramtype definition: ~azure.ai.projects.models.MemoryStoreDefinition - :keyword description: A human-readable description of the memory store. Default value is None. - :paramtype description: str - :keyword metadata: Arbitrary key-value metadata to associate with the memory store. Default - value is None. - :paramtype metadata: dict[str, str] - :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the UpdateModelVersionRequest to create or update. + Required. + :type version: str + :param body: The UpdateModelVersionRequest to create or update. Is one of the following types: + UpdateModelVersionRequest, JSON, IO[bytes] Required. + :type body: ~azure.ai.projects.models.UpdateModelVersionRequest or JSON or IO[bytes] + :return: ModelVersion. The ModelVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.ModelVersion :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -8945,23 +12813,18 @@ def create( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.MemoryStoreDetails] = kwargs.pop("cls", None) + cls: ClsType[_models.ModelVersion] = kwargs.pop("cls", None) - if body is _Unset: - if name is _Unset: - raise TypeError("missing required argument: name") - if definition is _Unset: - raise TypeError("missing required argument: definition") - body = {"definition": definition, "description": description, "metadata": metadata, "name": name} - body = {k: v for k, v in body.items() if v is not None} - content_type = content_type or "application/json" + content_type = content_type or "application/merge-patch+json" _content = None if isinstance(body, (IOBase, bytes)): _content = body else: _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_memory_stores_create_request( + _request = build_beta_models_update_request( + name=name, + version=version, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -8981,23 +12844,19 @@ def create( response = pipeline_response.http_response - if response.status_code not in [200]: + 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) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) + raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.MemoryStoreDetails, response.json()) + deserialized = _deserialize(_models.ModelVersion, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -9005,91 +12864,90 @@ def create( return deserialized # type: ignore @overload - def update( + def create_async( self, name: str, + version: str, + body: _models.ModelVersion, *, content_type: str = "application/json", - description: Optional[str] = None, - metadata: Optional[dict[str, str]] = None, **kwargs: Any - ) -> _models.MemoryStoreDetails: - """Update a memory store. - - :param name: The name of the memory store to update. Required. - :type 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 description: A human-readable description of the memory store. Default value is None. - :paramtype description: str - :keyword metadata: Arbitrary key-value metadata to associate with the memory store. Default - value is None. - :paramtype metadata: dict[str, str] - :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDetails + ) -> _models.CreateAsyncResponse: + """Creates a model version asynchronously with blob content validation. Returns 202 Accepted with + a Location header for polling. + + :param name: Name of the model. Required. + :type name: str + :param version: Version of the model. Required. + :type version: str + :param body: Model version to create. Required. + :type body: ~azure.ai.projects.models.ModelVersion + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: CreateAsyncResponse. The CreateAsyncResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.CreateAsyncResponse :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def update( - self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.MemoryStoreDetails: - """Update a memory store. + def create_async( + self, name: str, version: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CreateAsyncResponse: + """Creates a model version asynchronously with blob content validation. Returns 202 Accepted with + a Location header for polling. - :param name: The name of the memory store to update. Required. + :param name: Name of the model. Required. :type name: str - :param body: Required. + :param version: Version of the model. Required. + :type version: str + :param body: Model version to create. 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: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :return: CreateAsyncResponse. The CreateAsyncResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.CreateAsyncResponse :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def update( - self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.MemoryStoreDetails: - """Update a memory store. + def create_async( + self, name: str, version: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.CreateAsyncResponse: + """Creates a model version asynchronously with blob content validation. Returns 202 Accepted with + a Location header for polling. - :param name: The name of the memory store to update. Required. + :param name: Name of the model. Required. :type name: str - :param body: Required. + :param version: Version of the model. Required. + :type version: str + :param body: Model version to create. 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: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :return: CreateAsyncResponse. The CreateAsyncResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.CreateAsyncResponse :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def update( - self, - name: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - description: Optional[str] = None, - metadata: Optional[dict[str, str]] = None, - **kwargs: Any - ) -> _models.MemoryStoreDetails: - """Update a memory store. + def create_async( + self, name: str, version: str, body: Union[_models.ModelVersion, JSON, IO[bytes]], **kwargs: Any + ) -> _models.CreateAsyncResponse: + """Creates a model version asynchronously with blob content validation. Returns 202 Accepted with + a Location header for polling. - :param name: The name of the memory store to update. Required. + :param name: Name of the model. Required. :type name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword description: A human-readable description of the memory store. Default value is None. - :paramtype description: str - :keyword metadata: Arbitrary key-value metadata to associate with the memory store. Default - value is None. - :paramtype metadata: dict[str, str] - :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :param version: Version of the model. Required. + :type version: str + :param body: Model version to create. Is one of the following types: ModelVersion, JSON, + IO[bytes] Required. + :type body: ~azure.ai.projects.models.ModelVersion or JSON or IO[bytes] + :return: CreateAsyncResponse. The CreateAsyncResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.CreateAsyncResponse :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -9104,11 +12962,8 @@ def update( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.MemoryStoreDetails] = kwargs.pop("cls", None) + cls: ClsType[_models.CreateAsyncResponse] = kwargs.pop("cls", None) - if body is _Unset: - body = {"description": description, "metadata": metadata} - 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)): @@ -9116,8 +12971,9 @@ def update( else: _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_memory_stores_update_request( + _request = build_beta_models_create_async_request( name=name, + version=version, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -9137,37 +12993,113 @@ def update( response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [202]: 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) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.MemoryStoreDetails, response.json()) + deserialized = _deserialize(_models.CreateAsyncResponse, response.json()) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore + @overload + def pending_upload( + self, + name: str, + version: str, + body: _models.ModelPendingUploadRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.ModelPendingUploadResponse: + """Start or retrieve a pending upload for a model version. + + :param name: Name of the model. Required. + :type name: str + :param version: Version of the model. Required. + :type version: str + :param body: Required. + :type body: ~azure.ai.projects.models.ModelPendingUploadRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: ModelPendingUploadResponse. The ModelPendingUploadResponse is compatible with + MutableMapping + :rtype: ~azure.ai.projects.models.ModelPendingUploadResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def pending_upload( + self, name: str, version: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ModelPendingUploadResponse: + """Start or retrieve a pending upload for a model version. + + :param name: Name of the model. Required. + :type name: str + :param version: Version of the model. Required. + :type version: 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: ModelPendingUploadResponse. The ModelPendingUploadResponse is compatible with + MutableMapping + :rtype: ~azure.ai.projects.models.ModelPendingUploadResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def pending_upload( + self, name: str, version: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.ModelPendingUploadResponse: + """Start or retrieve a pending upload for a model version. + + :param name: Name of the model. Required. + :type name: str + :param version: Version of the model. Required. + :type version: 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: ModelPendingUploadResponse. The ModelPendingUploadResponse is compatible with + MutableMapping + :rtype: ~azure.ai.projects.models.ModelPendingUploadResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + @distributed_trace - def get(self, name: str, **kwargs: Any) -> _models.MemoryStoreDetails: - """Retrieve a memory store. + def pending_upload( + self, name: str, version: str, body: Union[_models.ModelPendingUploadRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.ModelPendingUploadResponse: + """Start or retrieve a pending upload for a model version. - :param name: The name of the memory store to retrieve. Required. + :param name: Name of the model. Required. :type name: str - :return: MemoryStoreDetails. The MemoryStoreDetails is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDetails + :param version: Version of the model. Required. + :type version: str + :param body: Is one of the following types: ModelPendingUploadRequest, JSON, IO[bytes] + Required. + :type body: ~azure.ai.projects.models.ModelPendingUploadRequest or JSON or IO[bytes] + :return: ModelPendingUploadResponse. The ModelPendingUploadResponse is compatible with + MutableMapping + :rtype: ~azure.ai.projects.models.ModelPendingUploadResponse :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -9178,14 +13110,25 @@ def get(self, name: str, **kwargs: Any) -> _models.MemoryStoreDetails: } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.MemoryStoreDetails] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.ModelPendingUploadResponse] = kwargs.pop("cls", None) - _request = build_beta_memory_stores_get_request( + 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_beta_models_pending_upload_request( name=name, + version=version, + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -9209,120 +13152,98 @@ def get(self, name: str, **kwargs: Any) -> _models.MemoryStoreDetails: except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) + raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.MemoryStoreDetails, response.json()) + deserialized = _deserialize(_models.ModelPendingUploadResponse, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @distributed_trace - def list( + @overload + def get_credentials( self, + name: str, + version: str, + body: _models.ModelCredentialRequest, *, - limit: Optional[int] = None, - order: Optional[Union[str, _models.PageOrder]] = None, - before: Optional[str] = None, + content_type: str = "application/json", **kwargs: Any - ) -> ItemPaged["_models.MemoryStoreDetails"]: - """List all memory stores. + ) -> _models.DatasetCredential: + """Get credentials for a model version asset. - :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and - 100, and the - default is 20. Default value is None. - :paramtype limit: int - :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for - ascending order and``desc`` - for descending order. Known values are: "asc" and "desc". Default value is None. - :paramtype order: str or ~azure.ai.projects.models.PageOrder - :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your - place in the list. - For instance, if you make a list request and receive 100 objects, ending with obj_foo, your - subsequent call can include before=obj_foo in order to fetch the previous page of the list. - Default value is None. - :paramtype before: str - :return: An iterator like instance of MemoryStoreDetails - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.MemoryStoreDetails] + :param name: Name of the model. Required. + :type name: str + :param version: Version of the model. Required. + :type version: str + :param body: Required. + :type body: ~azure.ai.projects.models.ModelCredentialRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: DatasetCredential. The DatasetCredential is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetCredential :raises ~azure.core.exceptions.HttpResponseError: """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[List[_models.MemoryStoreDetails]] = 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(_continuation_token=None): - - _request = build_beta_memory_stores_list_request( - limit=limit, - order=order, - after=_continuation_token, - before=before, - 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) - return _request - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize( - List[_models.MemoryStoreDetails], - deserialized.get("data", []), - ) - if cls: - list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("last_id") or None, iter(list_of_elem) - - def get_next(_continuation_token=None): - _request = prepare_request(_continuation_token) - - _stream = False - pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) - response = pipeline_response.http_response + @overload + def get_credentials( + self, name: str, version: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.DatasetCredential: + """Get credentials for a model version asset. - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) + :param name: Name of the model. Required. + :type name: str + :param version: Version of the model. Required. + :type version: 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: DatasetCredential. The DatasetCredential is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetCredential + :raises ~azure.core.exceptions.HttpResponseError: + """ - return pipeline_response + @overload + def get_credentials( + self, name: str, version: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.DatasetCredential: + """Get credentials for a model version asset. - return ItemPaged(get_next, extract_data) + :param name: Name of the model. Required. + :type name: str + :param version: Version of the model. Required. + :type version: 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: DatasetCredential. The DatasetCredential is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetCredential + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace - def delete(self, name: str, **kwargs: Any) -> _models.DeleteMemoryStoreResult: - """Delete a memory store. + def get_credentials( + self, name: str, version: str, body: Union[_models.ModelCredentialRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.DatasetCredential: + """Get credentials for a model version asset. - :param name: The name of the memory store to delete. Required. + :param name: Name of the model. Required. :type name: str - :return: DeleteMemoryStoreResult. The DeleteMemoryStoreResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.DeleteMemoryStoreResult + :param version: Version of the model. Required. + :type version: str + :param body: Is one of the following types: ModelCredentialRequest, JSON, IO[bytes] Required. + :type body: ~azure.ai.projects.models.ModelCredentialRequest or JSON or IO[bytes] + :return: DatasetCredential. The DatasetCredential is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetCredential :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -9333,14 +13254,25 @@ def delete(self, name: str, **kwargs: Any) -> _models.DeleteMemoryStoreResult: } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.DeleteMemoryStoreResult] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.DatasetCredential] = kwargs.pop("cls", None) - _request = build_beta_memory_stores_delete_request( + 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_beta_models_get_credentials_request( name=name, + version=version, + content_type=content_type, api_version=self._config.api_version, + content=_content, headers=_headers, params=_params, ) @@ -9364,73 +13296,44 @@ def delete(self, name: str, **kwargs: Any) -> _models.DeleteMemoryStoreResult: except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, - ) - raise HttpResponseError(response=response, model=error) + raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.DeleteMemoryStoreResult, response.json()) + deserialized = _deserialize(_models.DatasetCredential, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @overload - def _search_memories( - self, - name: str, - *, - scope: str, - content_type: str = "application/json", - items: Optional[List[dict[str, Any]]] = None, - previous_search_id: Optional[str] = None, - options: Optional[_models.MemorySearchOptions] = None, - **kwargs: Any - ) -> _models.MemoryStoreSearchResult: ... - @overload - def _search_memories( - self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.MemoryStoreSearchResult: ... - @overload - def _search_memories( - self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.MemoryStoreSearchResult: ... + +class BetaRedTeamsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.AIProjectClient`'s + :attr:`red_teams` 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: AIProjectClientConfiguration = 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 _search_memories( - self, - name: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - scope: str = _Unset, - items: Optional[List[dict[str, Any]]] = None, - previous_search_id: Optional[str] = None, - options: Optional[_models.MemorySearchOptions] = None, - **kwargs: Any - ) -> _models.MemoryStoreSearchResult: - """Search for relevant memories from a memory store based on conversation context. + def get(self, name: str, **kwargs: Any) -> _models.RedTeam: + """Get a redteam by name. - :param name: The name of the memory store to search. Required. + :param name: Identifier of the red team run. Required. :type name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword scope: The namespace that logically groups and isolates memories, such as a user ID. - Required. - :paramtype scope: str - :keyword items: Items for which to search for relevant memories. Default value is None. - :paramtype items: list[dict[str, any]] - :keyword previous_search_id: The unique ID of the previous search request, enabling incremental - memory search from where the last operation left off. Default value is None. - :paramtype previous_search_id: str - :keyword options: Memory search options. Default value is None. - :paramtype options: ~azure.ai.projects.models.MemorySearchOptions - :return: MemoryStoreSearchResult. The MemoryStoreSearchResult is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreSearchResult + :return: RedTeam. The RedTeam is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.RedTeam :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -9441,34 +13344,14 @@ def _search_memories( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _headers = 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.MemoryStoreSearchResult] = kwargs.pop("cls", None) - - if body is _Unset: - if scope is _Unset: - raise TypeError("missing required argument: scope") - body = { - "items": items, - "options": options, - "previous_search_id": previous_search_id, - "scope": scope, - } - 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 + cls: ClsType[_models.RedTeam] = kwargs.pop("cls", None) - _request = build_beta_memory_stores_search_memories_request( + _request = build_beta_red_teams_get_request( name=name, - content_type=content_type, api_version=self._config.api_version, - content=_content, headers=_headers, params=_params, ) @@ -9492,33 +13375,161 @@ def _search_memories( except (StreamConsumedError, StreamClosedError): pass map_error(status_code=response.status_code, response=response, error_map=error_map) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedTeam, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list(self, **kwargs: Any) -> ItemPaged["_models.RedTeam"]: + """List a redteam by name. + + :return: An iterator like instance of RedTeam + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.RedTeam] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.RedTeam]] = 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_beta_red_teams_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, + headers=_headers, + ) + 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.RedTeam], + deserialized.get("value", []), ) - raise HttpResponseError(response=response, model=error) + 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) + + @overload + def create( + self, red_team: _models.RedTeam, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RedTeam: + """Creates a redteam run. + + :param red_team: Redteam to be run. Required. + :type red_team: ~azure.ai.projects.models.RedTeam + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RedTeam. The RedTeam is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.RedTeam + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create(self, red_team: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.RedTeam: + """Creates a redteam run. + + :param red_team: Redteam to be run. Required. + :type red_team: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: RedTeam. The RedTeam is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.RedTeam + :raises ~azure.core.exceptions.HttpResponseError: + """ - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.MemoryStoreSearchResult, response.json()) + @overload + def create(self, red_team: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> _models.RedTeam: + """Creates a redteam run. - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + :param red_team: Redteam to be run. Required. + :type red_team: 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: RedTeam. The RedTeam is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.RedTeam + :raises ~azure.core.exceptions.HttpResponseError: + """ - return deserialized # type: ignore + @distributed_trace + def create(self, red_team: Union[_models.RedTeam, JSON, IO[bytes]], **kwargs: Any) -> _models.RedTeam: + """Creates a redteam run. - def _update_memories_initial( - self, - name: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - scope: str = _Unset, - items: Optional[List[dict[str, Any]]] = None, - previous_update_id: Optional[str] = None, - update_delay: Optional[int] = None, - **kwargs: Any - ) -> Iterator[bytes]: + :param red_team: Redteam to be run. Is one of the following types: RedTeam, JSON, IO[bytes] + Required. + :type red_team: ~azure.ai.projects.models.RedTeam or JSON or IO[bytes] + :return: RedTeam. The RedTeam is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.RedTeam + :raises ~azure.core.exceptions.HttpResponseError: + """ error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -9531,27 +13542,16 @@ def _update_memories_initial( _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) + cls: ClsType[_models.RedTeam] = kwargs.pop("cls", None) - if body is _Unset: - if scope is _Unset: - raise TypeError("missing required argument: scope") - body = { - "items": items, - "previous_update_id": previous_update_id, - "scope": scope, - "update_delay": update_delay, - } - 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 + if isinstance(red_team, (IOBase, bytes)): + _content = red_team else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(red_team, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_memory_stores_update_memories_request( - name=name, + _request = build_beta_red_teams_create_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -9564,18 +13564,19 @@ def _update_memories_initial( _request.url = self._client.format_url(_request.url, **path_format_arguments) _decompress = kwargs.pop("decompress", True) - _stream = 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 [202]: - try: - response.read() # Load the body in memory and close the socket - except (StreamConsumedError, StreamClosedError): - pass + if response.status_code not in [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) error = _failsafe_deserialize( _models.ApiErrorResponse, @@ -9583,209 +13584,132 @@ def _update_memories_initial( ) raise HttpResponseError(response=response, model=error) - 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 _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.RedTeam, response.json()) if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @overload - def _begin_update_memories( - self, - name: str, - *, - scope: str, - content_type: str = "application/json", - items: Optional[List[dict[str, Any]]] = None, - previous_update_id: Optional[str] = None, - update_delay: Optional[int] = None, - **kwargs: Any - ) -> LROPoller[_models.MemoryStoreUpdateCompletedResult]: ... - @overload - def _begin_update_memories( - self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[_models.MemoryStoreUpdateCompletedResult]: ... - @overload - def _begin_update_memories( - self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> LROPoller[_models.MemoryStoreUpdateCompletedResult]: ... - - @distributed_trace - def _begin_update_memories( - self, - name: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - scope: str = _Unset, - items: Optional[List[dict[str, Any]]] = None, - previous_update_id: Optional[str] = None, - update_delay: Optional[int] = None, - **kwargs: Any - ) -> LROPoller[_models.MemoryStoreUpdateCompletedResult]: - """Update memory store with conversation memories. - - :param name: The name of the memory store to update. Required. - :type name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword scope: The namespace that logically groups and isolates memories, such as a user ID. - Required. - :paramtype scope: str - :keyword items: Conversation items to be stored in memory. Default value is None. - :paramtype items: list[dict[str, any]] - :keyword previous_update_id: The unique ID of the previous update request, enabling incremental - memory updates from where the last operation left off. Default value is None. - :paramtype previous_update_id: str - :keyword update_delay: Timeout period before processing the memory update in seconds. - If a new update request is received during this period, it will cancel the current request and - reset the timeout. - Set to 0 to immediately trigger the update without delay. - Defaults to 300 (5 minutes). Default value is None. - :paramtype update_delay: int - :return: An instance of LROPoller that returns MemoryStoreUpdateCompletedResult. The - MemoryStoreUpdateCompletedResult is compatible with MutableMapping - :rtype: - ~azure.core.polling.LROPoller[~azure.ai.projects.models.MemoryStoreUpdateCompletedResult] - :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.MemoryStoreUpdateCompletedResult] = 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._update_memories_initial( - name=name, - body=body, - scope=scope, - items=items, - previous_update_id=previous_update_id, - update_delay=update_delay, - 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.MemoryStoreUpdateCompletedResult, response.json().get("result", {})) - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - return deserialized +class BetaRoutinesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } + Instead, you should access the following operations through + :class:`~azure.ai.projects.AIProjectClient`'s + :attr:`routines` attribute. + """ - 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.MemoryStoreUpdateCompletedResult].from_continuation_token( - polling_method=polling_method, - continuation_token=cont_token, - client=self._client, - deserialization_callback=get_long_running_output, - ) - return LROPoller[_models.MemoryStoreUpdateCompletedResult]( - self._client, raw_result, get_long_running_output, polling_method # type: ignore - ) + 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: AIProjectClientConfiguration = 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 delete_scope( - self, name: str, *, scope: str, content_type: str = "application/json", **kwargs: Any - ) -> _models.MemoryStoreDeleteScopeResult: - """Delete all memories associated with a specific scope from a memory store. - - :param name: The name of the memory store. Required. - :type name: str - :keyword scope: The namespace that logically groups and isolates memories to delete, such as a - user ID. Required. - :paramtype scope: str + def create_or_update( + self, + routine_name: str, + *, + triggers: dict[str, _models.RoutineTrigger], + action: _models.RoutineAction, + content_type: str = "application/json", + description: Optional[str] = None, + enabled: Optional[bool] = None, + **kwargs: Any + ) -> _models.Routine: + """Create or update a routine. + + :param routine_name: The unique name of the routine. Required. + :type routine_name: str + :keyword triggers: The triggers configured for the routine. In v1, exactly one trigger entry is + supported. Required. + :paramtype triggers: dict[str, ~azure.ai.projects.models.RoutineTrigger] + :keyword action: The action executed when the routine fires. Required. + :paramtype action: ~azure.ai.projects.models.RoutineAction :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: MemoryStoreDeleteScopeResult. The MemoryStoreDeleteScopeResult is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDeleteScopeResult + :keyword description: A human-readable description of the routine. Default value is None. + :paramtype description: str + :keyword enabled: Whether the routine is enabled. Default value is None. + :paramtype enabled: bool + :return: Routine. The Routine is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Routine :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def delete_scope( - self, name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.MemoryStoreDeleteScopeResult: - """Delete all memories associated with a specific scope from a memory store. + def create_or_update( + self, routine_name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Routine: + """Create or update a routine. - :param name: The name of the memory store. Required. - :type name: str + :param routine_name: The unique name of the routine. Required. + :type routine_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: MemoryStoreDeleteScopeResult. The MemoryStoreDeleteScopeResult is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDeleteScopeResult + :return: Routine. The Routine is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Routine :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def delete_scope( - self, name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.MemoryStoreDeleteScopeResult: - """Delete all memories associated with a specific scope from a memory store. + def create_or_update( + self, routine_name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Routine: + """Create or update a routine. - :param name: The name of the memory store. Required. - :type name: str + :param routine_name: The unique name of the routine. Required. + :type routine_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: MemoryStoreDeleteScopeResult. The MemoryStoreDeleteScopeResult is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDeleteScopeResult + :return: Routine. The Routine is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Routine :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def delete_scope( - self, name: str, body: Union[JSON, IO[bytes]] = _Unset, *, scope: str = _Unset, **kwargs: Any - ) -> _models.MemoryStoreDeleteScopeResult: - """Delete all memories associated with a specific scope from a memory store. + def create_or_update( + self, + routine_name: str, + body: Union[JSON, IO[bytes]] = _Unset, + *, + triggers: dict[str, _models.RoutineTrigger] = _Unset, + action: _models.RoutineAction = _Unset, + description: Optional[str] = None, + enabled: Optional[bool] = None, + **kwargs: Any + ) -> _models.Routine: + """Create or update a routine. - :param name: The name of the memory store. Required. - :type name: str + :param routine_name: The unique name of the routine. Required. + :type routine_name: str :param body: Is either a JSON type or a IO[bytes] type. Required. :type body: JSON or IO[bytes] - :keyword scope: The namespace that logically groups and isolates memories to delete, such as a - user ID. Required. - :paramtype scope: str - :return: MemoryStoreDeleteScopeResult. The MemoryStoreDeleteScopeResult is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.MemoryStoreDeleteScopeResult + :keyword triggers: The triggers configured for the routine. In v1, exactly one trigger entry is + supported. Required. + :paramtype triggers: dict[str, ~azure.ai.projects.models.RoutineTrigger] + :keyword action: The action executed when the routine fires. Required. + :paramtype action: ~azure.ai.projects.models.RoutineAction + :keyword description: A human-readable description of the routine. Default value is None. + :paramtype description: str + :keyword enabled: Whether the routine is enabled. Default value is None. + :paramtype enabled: bool + :return: Routine. The Routine is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Routine :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -9800,12 +13724,14 @@ def delete_scope( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.MemoryStoreDeleteScopeResult] = kwargs.pop("cls", None) + cls: ClsType[_models.Routine] = kwargs.pop("cls", None) if body is _Unset: - if scope is _Unset: - raise TypeError("missing required argument: scope") - body = {"scope": scope} + if triggers is _Unset: + raise TypeError("missing required argument: triggers") + if action is _Unset: + raise TypeError("missing required argument: action") + body = {"action": action, "description": description, "enabled": enabled, "triggers": triggers} body = {k: v for k, v in body.items() if v is not None} content_type = content_type or "application/json" _content = None @@ -9814,8 +13740,8 @@ def delete_scope( else: _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_memory_stores_delete_scope_request( - name=name, + _request = build_beta_routines_create_or_update_request( + routine_name=routine_name, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -9833,57 +13759,324 @@ def delete_scope( _request, stream=_stream, **kwargs ) - response = pipeline_response.http_response + 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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Routine, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def get(self, routine_name: str, **kwargs: Any) -> _models.Routine: + """Retrieve a routine. + + :param routine_name: The unique name of the routine. Required. + :type routine_name: str + :return: Routine. The Routine is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Routine + :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.Routine] = kwargs.pop("cls", None) + + _request = build_beta_routines_get_request( + routine_name=routine_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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Routine, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def enable(self, routine_name: str, **kwargs: Any) -> _models.Routine: + """Enable a routine. + + :param routine_name: The unique name of the routine. Required. + :type routine_name: str + :return: Routine. The Routine is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Routine + :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.Routine] = kwargs.pop("cls", None) + + _request = build_beta_routines_enable_request( + routine_name=routine_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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Routine, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def disable(self, routine_name: str, **kwargs: Any) -> _models.Routine: + """Disable a routine. + + :param routine_name: The unique name of the routine. Required. + :type routine_name: str + :return: Routine. The Routine is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Routine + :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.Routine] = kwargs.pop("cls", None) + + _request = build_beta_routines_disable_request( + routine_name=routine_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) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) + + if _stream: + deserialized = response.iter_bytes() if _decompress else response.iter_raw() + else: + deserialized = _deserialize(_models.Routine, response.json()) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def list( + self, + *, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + before: Optional[str] = None, + **kwargs: Any + ) -> ItemPaged["_models.Routine"]: + """List routines. + + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :return: An iterator like instance of Routine + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.Routine] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[_models.Routine]] = 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(_continuation_token=None): - 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) - error = _failsafe_deserialize( - _models.ApiErrorResponse, - response, + _request = build_beta_routines_list_request( + limit=limit, + order=order, + after=_continuation_token, + before=before, + api_version=self._config.api_version, + headers=_headers, + params=_params, ) - raise HttpResponseError(response=response, model=error) - - if _stream: - deserialized = response.iter_bytes() if _decompress else response.iter_raw() - else: - deserialized = _deserialize(_models.MemoryStoreDeleteScopeResult, response.json()) + 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 - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize( + List[_models.Routine], + deserialized.get("data", []), + ) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("last_id") or None, iter(list_of_elem) - return deserialized # type: ignore + def get_next(_continuation_token=None): + _request = prepare_request(_continuation_token) + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response -class BetaRedTeamsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) - Instead, you should access the following operations through - :class:`~azure.ai.projects.AIProjectClient`'s - :attr:`red_teams` attribute. - """ + return pipeline_response - 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: AIProjectClientConfiguration = 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") + return ItemPaged(get_next, extract_data) @distributed_trace - def get(self, name: str, **kwargs: Any) -> _models.RedTeam: - """Get a redteam by name. + def delete(self, routine_name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete a routine. - :param name: Identifier of the red team run. Required. - :type name: str - :return: RedTeam. The RedTeam is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.RedTeam + :param routine_name: The unique name of the routine. Required. + :type routine_name: str + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -9897,10 +14090,10 @@ def get(self, name: str, **kwargs: Any) -> _models.RedTeam: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.RedTeam] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_beta_red_teams_get_request( - name=name, + _request = build_beta_routines_delete_request( + routine_name=routine_name, api_version=self._config.api_version, headers=_headers, params=_params, @@ -9910,45 +14103,64 @@ def get(self, name: str, **kwargs: Any) -> _models.RedTeam: } _request.url = self._client.format_url(_request.url, **path_format_arguments) - _decompress = kwargs.pop("decompress", True) - _stream = kwargs.pop("stream", False) + _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 + if response.status_code not in [204]: 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.RedTeam, response.json()) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def list(self, **kwargs: Any) -> ItemPaged["_models.RedTeam"]: - """List a redteam by name. - - :return: An iterator like instance of RedTeam - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.RedTeam] + def list_runs( + self, + routine_name: str, + *, + filter: Optional[str] = None, + limit: Optional[int] = None, + order: Optional[Union[str, _models.PageOrder]] = None, + before: Optional[str] = None, + **kwargs: Any + ) -> ItemPaged["_models.RoutineRun"]: + """List prior runs for a routine. + + :param routine_name: The unique name of the routine. Required. + :type routine_name: str + :keyword filter: An optional MLflow search-runs filter expression applied within the routine's + experiment. Default value is None. + :paramtype filter: str + :keyword limit: A limit on the number of objects to be returned. Limit can range between 1 and + 100, and the + default is 20. Default value is None. + :paramtype limit: int + :keyword order: Sort order by the ``created_at`` timestamp of the objects. ``asc`` for + ascending order and``desc`` + for descending order. Known values are: "asc" and "desc". Default value is None. + :paramtype order: str or ~azure.ai.projects.models.PageOrder + :keyword before: A cursor for use in pagination. ``before`` is an object ID that defines your + place in the list. + For instance, if you make a list request and receive 100 objects, ending with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the previous page of the list. + Default value is None. + :paramtype before: str + :return: An iterator like instance of RoutineRun + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.RoutineRun] :raises ~azure.core.exceptions.HttpResponseError: """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[List[_models.RedTeam]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.RoutineRun]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -9958,58 +14170,37 @@ def list(self, **kwargs: Any) -> ItemPaged["_models.RedTeam"]: } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: - - _request = build_beta_red_teams_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, - headers=_headers, - ) - 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) + def prepare_request(_continuation_token=None): + _request = build_beta_routines_list_runs_request( + routine_name=routine_name, + filter=filter, + limit=limit, + order=order, + after=_continuation_token, + before=before, + 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) return _request def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() list_of_elem = _deserialize( - List[_models.RedTeam], - deserialized.get("value", []), + List[_models.RoutineRun], + deserialized.get("data", []), ) if cls: list_of_elem = cls(list_of_elem) # type: ignore - return deserialized.get("nextLink") or None, iter(list_of_elem) + return deserialized.get("last_id") or None, iter(list_of_elem) - def get_next(next_link=None): - _request = prepare_request(next_link) + def get_next(_continuation_token=None): + _request = prepare_request(_continuation_token) _stream = False pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access @@ -10019,65 +14210,96 @@ def get_next(next_link=None): if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + error = _failsafe_deserialize( + _models.ApiErrorResponse, + response, + ) + raise HttpResponseError(response=response, model=error) return pipeline_response return ItemPaged(get_next, extract_data) @overload - def create( - self, red_team: _models.RedTeam, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.RedTeam: - """Creates a redteam run. + def dispatch_async( + self, + routine_name: str, + *, + content_type: str = "application/json", + payload: Optional[_models.RoutineDispatchPayload] = None, + **kwargs: Any + ) -> _models.DispatchRoutineResponse: + """Queue an asynchronous routine dispatch. - :param red_team: Redteam to be run. Required. - :type red_team: ~azure.ai.projects.models.RedTeam + :param routine_name: The unique name of the routine. Required. + :type routine_name: str :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: RedTeam. The RedTeam is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.RedTeam + :keyword payload: A direct action-input override sent downstream when testing a routine. + Default value is None. + :paramtype payload: ~azure.ai.projects.models.RoutineDispatchPayload + :return: DispatchRoutineResponse. The DispatchRoutineResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DispatchRoutineResponse :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create(self, red_team: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.RedTeam: - """Creates a redteam run. + def dispatch_async( + self, routine_name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.DispatchRoutineResponse: + """Queue an asynchronous routine dispatch. - :param red_team: Redteam to be run. Required. - :type red_team: JSON + :param routine_name: The unique name of the routine. Required. + :type routine_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: RedTeam. The RedTeam is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.RedTeam + :return: DispatchRoutineResponse. The DispatchRoutineResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DispatchRoutineResponse :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create(self, red_team: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> _models.RedTeam: - """Creates a redteam run. + def dispatch_async( + self, routine_name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.DispatchRoutineResponse: + """Queue an asynchronous routine dispatch. - :param red_team: Redteam to be run. Required. - :type red_team: IO[bytes] + :param routine_name: The unique name of the routine. Required. + :type routine_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: RedTeam. The RedTeam is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.RedTeam + :return: DispatchRoutineResponse. The DispatchRoutineResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DispatchRoutineResponse :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def create(self, red_team: Union[_models.RedTeam, JSON, IO[bytes]], **kwargs: Any) -> _models.RedTeam: - """Creates a redteam run. + def dispatch_async( + self, + routine_name: str, + body: Union[JSON, IO[bytes]] = _Unset, + *, + payload: Optional[_models.RoutineDispatchPayload] = None, + **kwargs: Any + ) -> _models.DispatchRoutineResponse: + """Queue an asynchronous routine dispatch. - :param red_team: Redteam to be run. Is one of the following types: RedTeam, JSON, IO[bytes] - Required. - :type red_team: ~azure.ai.projects.models.RedTeam or JSON or IO[bytes] - :return: RedTeam. The RedTeam is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.RedTeam + :param routine_name: The unique name of the routine. Required. + :type routine_name: str + :param body: Is either a JSON type or a IO[bytes] type. Required. + :type body: JSON or IO[bytes] + :keyword payload: A direct action-input override sent downstream when testing a routine. + Default value is None. + :paramtype payload: ~azure.ai.projects.models.RoutineDispatchPayload + :return: DispatchRoutineResponse. The DispatchRoutineResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DispatchRoutineResponse :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -10092,16 +14314,20 @@ def create(self, red_team: Union[_models.RedTeam, JSON, IO[bytes]], **kwargs: An _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.RedTeam] = kwargs.pop("cls", None) + cls: ClsType[_models.DispatchRoutineResponse] = kwargs.pop("cls", None) + if body is _Unset: + body = {"payload": payload} + 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(red_team, (IOBase, bytes)): - _content = red_team + if isinstance(body, (IOBase, bytes)): + _content = body else: - _content = json.dumps(red_team, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_beta_red_teams_create_request( + _request = build_beta_routines_dispatch_async_request( + routine_name=routine_name, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -10121,7 +14347,7 @@ def create(self, red_team: Union[_models.RedTeam, JSON, IO[bytes]], **kwargs: An response = pipeline_response.http_response - if response.status_code not in [201]: + if response.status_code not in [200]: if _stream: try: response.read() # Load the body in memory and close the socket @@ -10137,7 +14363,7 @@ def create(self, red_team: Union[_models.RedTeam, JSON, IO[bytes]], **kwargs: An if _stream: deserialized = response.iter_bytes() if _decompress else response.iter_raw() else: - deserialized = _deserialize(_models.RedTeam, response.json()) + deserialized = _deserialize(_models.DispatchRoutineResponse, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch.py index 784a8ba6b182..88ce76ca765a 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch.py @@ -24,8 +24,10 @@ BetaEvaluationTaxonomiesOperations, BetaEvaluatorsOperations, BetaInsightsOperations, + BetaModelsOperations, BetaOperations as GeneratedBetaOperations, BetaRedTeamsOperations, + BetaRoutinesOperations, BetaSchedulesOperations, BetaSkillsOperations, BetaToolboxesOperations, @@ -105,8 +107,12 @@ class BetaOperations(GeneratedBetaOperations): """:class:`~azure.ai.projects.operations.BetaInsightsOperations` operations""" memory_stores: BetaMemoryStoresOperations """:class:`~azure.ai.projects.operations.BetaMemoryStoresOperations` operations""" + models: BetaModelsOperations + """:class:`~azure.ai.projects.operations.BetaModelsOperations` operations""" red_teams: BetaRedTeamsOperations """:class:`~azure.ai.projects.operations.BetaRedTeamsOperations` operations""" + routines: BetaRoutinesOperations + """:class:`~azure.ai.projects.operations.BetaRoutinesOperations` operations""" schedules: BetaSchedulesOperations """:class:`~azure.ai.projects.operations.BetaSchedulesOperations` operations""" toolboxes: BetaToolboxesOperations @@ -141,8 +147,10 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: "BetaEvaluatorsOperations", "BetaInsightsOperations", "BetaMemoryStoresOperations", + "BetaModelsOperations", "BetaOperations", "BetaRedTeamsOperations", + "BetaRoutinesOperations", "BetaSchedulesOperations", "BetaSkillsOperations", "BetaToolboxesOperations", diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_agents.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_agents.py index 02274e66fac2..83e848bd3db1 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_agents.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/_patch_agents.py @@ -42,6 +42,7 @@ _AgentDefinitionOptInKeys.HOSTED_AGENTS_V1_PREVIEW.value, _AgentDefinitionOptInKeys.WORKFLOW_AGENTS_V1_PREVIEW.value, _AgentDefinitionOptInKeys.AGENT_ENDPOINT_V1_PREVIEW.value, + _AgentDefinitionOptInKeys.EXTERNAL_AGENTS_V1_PREVIEW.value, ] ) diff --git a/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_create_hosted_agent_from_code.py b/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_create_hosted_agent_from_code.py index afc332e7236e..1db86d1dee18 100644 --- a/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_create_hosted_agent_from_code.py +++ b/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_create_hosted_agent_from_code.py @@ -90,7 +90,7 @@ code=(zip_filename, code_zip_bytes, "application/zip"), ) - created = project_client.beta.agents.create_agent_version_from_code( + created = project_client.beta.agents.create_version_from_code( agent_name=agent_name, content=content, code_zip_sha256=code_zip_sha256, @@ -114,7 +114,7 @@ version_zip_path = Path(tempfile.gettempdir()) / f"{agent_name}-{created.version}.zip" sha = hashlib.sha256() with open(version_zip_path, "wb") as f: - for chunk in project_client.beta.agents.download_agent_version_code( + for chunk in project_client.beta.agents.download_agent_code( agent_name=agent_name, agent_version=created.version, ): diff --git a/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_create_hosted_agent_from_code_async.py b/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_create_hosted_agent_from_code_async.py index 85b1368f48c1..630bb7925a08 100644 --- a/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_create_hosted_agent_from_code_async.py +++ b/sdk/ai/azure-ai-projects/samples/hosted_agents/sample_create_hosted_agent_from_code_async.py @@ -94,7 +94,7 @@ async def main() -> None: code=(zip_filename, code_zip_bytes, "application/zip"), ) - created = await project_client.beta.agents.create_agent_version_from_code( + created = await project_client.beta.agents.create_version_from_code( agent_name=agent_name, content=content, code_zip_sha256=code_zip_sha256, @@ -119,7 +119,7 @@ async def main() -> None: # Download the zip for the version we just created, streaming to a temp file. version_zip_path = Path(tempfile.gettempdir()) / f"{agent_name}-{created.version}.zip" sha = hashlib.sha256() - version_stream = await project_client.beta.agents.download_agent_version_code( + version_stream = await project_client.beta.agents.download_agent_code( agent_name=agent_name, agent_version=created.version, ) diff --git a/sdk/ai/azure-ai-projects/tests/foundry_features_header/foundry_features_header_test_base.py b/sdk/ai/azure-ai-projects/tests/foundry_features_header/foundry_features_header_test_base.py index c0c242ee5723..4a67e77b11c6 100644 --- a/sdk/ai/azure-ai-projects/tests/foundry_features_header/foundry_features_header_test_base.py +++ b/sdk/ai/azure-ai-projects/tests/foundry_features_header/foundry_features_header_test_base.py @@ -44,7 +44,9 @@ "toolboxes": "Toolboxes=V1Preview", "skills": "Skills=V1Preview", "datasets": "DataGenerationJobs=V1Preview", - "agents": "HostedAgents=V1Preview,AgentEndpoints=V1Preview,CodeAgents=V1Preview", + "models": "Models=V1Preview", + "routines": "Routines=V1Preview", + "agents": "HostedAgents=V1Preview,AgentEndpoints=V1Preview,CodeAgents=V1Preview,ExternalAgents=V1Preview,AgentsOptimization=V1Preview", } # Shared test cases for non-beta methods that optionally send the Foundry-Features header. @@ -59,7 +61,7 @@ # The test id is derived automatically from method_name. pytest.param( "agents.create_version", - "HostedAgents=V1Preview,WorkflowAgents=V1Preview,AgentEndpoints=V1Preview", + "HostedAgents=V1Preview,WorkflowAgents=V1Preview,AgentEndpoints=V1Preview,ExternalAgents=V1Preview", ), pytest.param( "evaluation_rules.create_or_update", diff --git a/sdk/ai/azure-ai-projects/tsp-location.yaml b/sdk/ai/azure-ai-projects/tsp-location.yaml index f7ab1acc313e..cd6315ba5f67 100644 --- a/sdk/ai/azure-ai-projects/tsp-location.yaml +++ b/sdk/ai/azure-ai-projects/tsp-location.yaml @@ -1,4 +1,4 @@ directory: specification/ai-foundry/data-plane/Foundry -commit: 8dba3c8402a82cf0c2bf8a905b0e932bec57727a +commit: e382f141f7772b1fcf0e0b1cad53395a3b47784c repo: Azure/azure-rest-api-specs additionalDirectories: