diff --git a/sdk/ai/azure-ai-projects/_meta.json b/sdk/ai/azure-ai-projects/_meta.json new file mode 100644 index 000000000000..8c4cd80da04e --- /dev/null +++ b/sdk/ai/azure-ai-projects/_meta.json @@ -0,0 +1,6 @@ +{ + "commit": "24ce4ac67ab3aa64c19de3fede264310426131ee", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "typespec_src": "specification/ai/Azure.AI.Projects", + "@azure-tools/typespec-python": "0.44.1" +} \ No newline at end of file diff --git a/sdk/ai/azure-ai-projects/apiview-properties.json b/sdk/ai/azure-ai-projects/apiview-properties.json index edfd93b298e0..2d85fdfedb62 100644 --- a/sdk/ai/azure-ai-projects/apiview-properties.json +++ b/sdk/ai/azure-ai-projects/apiview-properties.json @@ -1,274 +1,92 @@ { "CrossLanguagePackageId": "Azure.AI.Projects", "CrossLanguageDefinitionId": { - "azure.ai.projects.models.Agent": "Azure.AI.Projects.Agents.Agent", - "azure.ai.projects.models.AgentDeletionStatus": "Azure.AI.Projects.Agents.AgentDeletionStatus", - "azure.ai.projects.models.AgentsApiResponseFormat": "Azure.AI.Projects.Agents.AgentsApiResponseFormat", - "azure.ai.projects.models.AgentsNamedToolChoice": "Azure.AI.Projects.Agents.AgentsNamedToolChoice", - "azure.ai.projects.models.AgentThread": "Azure.AI.Projects.Agents.AgentThread", - "azure.ai.projects.models.AgentThreadCreationOptions": "Azure.AI.Projects.Agents.AgentThreadCreationOptions", - "azure.ai.projects.models.AISearchIndexResource": "Azure.AI.Projects.Agents.AISearchIndexResource", - "azure.ai.projects.models.TargetModelConfig": "Azure.AI.Projects.TargetModelConfig", - "azure.ai.projects.models.AOAIModelConfig": "Azure.AI.Projects.AOAIModelConfig", - "azure.ai.projects.models.InputData": "Azure.AI.Projects.InputData", - "azure.ai.projects.models.ApplicationInsightsConfiguration": "Azure.AI.Projects.ApplicationInsightsConfiguration", - "azure.ai.projects.models.AzureAISearchResource": "Azure.AI.Projects.Agents.AzureAISearchResource", - "azure.ai.projects.models.ToolDefinition": "Azure.AI.Projects.Agents.ToolDefinition", - "azure.ai.projects.models.AzureAISearchToolDefinition": "Azure.AI.Projects.Agents.AzureAISearchToolDefinition", - "azure.ai.projects.models.AzureFunctionBinding": "Azure.AI.Projects.Agents.AzureFunctionBinding", - "azure.ai.projects.models.AzureFunctionDefinition": "Azure.AI.Projects.Agents.AzureFunctionDefinition", - "azure.ai.projects.models.AzureFunctionStorageQueue": "Azure.AI.Projects.Agents.AzureFunctionStorageQueue", - "azure.ai.projects.models.AzureFunctionToolDefinition": "Azure.AI.Projects.Agents.AzureFunctionToolDefinition", - "azure.ai.projects.models.BingCustomSearchToolDefinition": "Azure.AI.Projects.Agents.BingCustomSearchToolDefinition", - "azure.ai.projects.models.BingGroundingToolDefinition": "Azure.AI.Projects.Agents.BingGroundingToolDefinition", - "azure.ai.projects.models.CodeInterpreterToolDefinition": "Azure.AI.Projects.Agents.CodeInterpreterToolDefinition", - "azure.ai.projects.models.CodeInterpreterToolResource": "Azure.AI.Projects.Agents.CodeInterpreterToolResource", - "azure.ai.projects.models.ConnectedAgentDetails": "Azure.AI.Projects.Agents.ConnectedAgentDetails", - "azure.ai.projects.models.ConnectedAgentToolDefinition": "Azure.AI.Projects.Agents.ConnectedAgentToolDefinition", - "azure.ai.projects.models.Trigger": "Azure.AI.Projects.Trigger", - "azure.ai.projects.models.CronTrigger": "Azure.AI.Projects.CronTrigger", - "azure.ai.projects.models.Dataset": "Azure.AI.Projects.Dataset", + "azure.ai.projects.models.AgentEvaluation": "Azure.AI.Projects.AgentEvaluation", + "azure.ai.projects.models.AgentEvaluationRedactionConfiguration": "Azure.AI.Projects.AgentEvaluationRedactionConfiguration", + "azure.ai.projects.models.AgentEvaluationRequest": "Azure.AI.Projects.AgentEvaluationRequest", + "azure.ai.projects.models.AgentEvaluationResult": "Azure.AI.Projects.AgentEvaluationResult", + "azure.ai.projects.models.AgentEvaluationSamplingConfiguration": "Azure.AI.Projects.AgentEvaluationSamplingConfiguration", + "azure.ai.projects.models.BaseCredentials": "Azure.AI.Projects.BaseCredentials", + "azure.ai.projects.models.ApiKeyCredentials": "Azure.AI.Projects.ApiKeyCredentials", + "azure.ai.projects.models.AssetCredentialResponse": "Azure.AI.Projects.AssetCredentialResponse", + "azure.ai.projects.models.Index": "Azure.AI.Projects.Index", + "azure.ai.projects.models.AzureAISearchIndex": "Azure.AI.Projects.AzureAISearchIndex", + "azure.ai.projects.models.TargetConfig": "Azure.AI.Projects.TargetConfig", + "azure.ai.projects.models.AzureOpenAIModelConfiguration": "Azure.AI.Projects.AzureOpenAIModelConfiguration", + "azure.ai.projects.models.BlobReference": "Azure.AI.Projects.BlobReference", + "azure.ai.projects.models.Connection": "Azure.AI.Projects.Connection", + "azure.ai.projects.models.CosmosDBIndex": "Azure.AI.Projects.CosmosDBIndex", + "azure.ai.projects.models.CustomCredential": "Azure.AI.Projects.CustomCredential", + "azure.ai.projects.models.DatasetVersion": "Azure.AI.Projects.DatasetVersion", + "azure.ai.projects.models.Deployment": "Azure.AI.Projects.Deployment", + "azure.ai.projects.models.EmbeddingConfiguration": "Azure.AI.Projects.EmbeddingConfiguration", + "azure.ai.projects.models.EntraIDCredentials": "Azure.AI.Projects.EntraIDCredentials", "azure.ai.projects.models.Evaluation": "Azure.AI.Projects.Evaluation", - "azure.ai.projects.models.EvaluationSchedule": "Azure.AI.Projects.EvaluationSchedule", - "azure.ai.projects.models.EvaluationTarget": "Azure.AI.Projects.EvaluationTarget", "azure.ai.projects.models.EvaluatorConfiguration": "Azure.AI.Projects.EvaluatorConfiguration", - "azure.ai.projects.models.FileDeletionStatus": "Azure.AI.Projects.Agents.FileDeletionStatus", - "azure.ai.projects.models.FileListResponse": "Azure.AI.Projects.Agents.FileListResponse", - "azure.ai.projects.models.FileSearchRankingOptions": "Azure.AI.Projects.Agents.FileSearchRankingOptions", - "azure.ai.projects.models.FileSearchToolCallContent": "Azure.AI.Projects.Agents.FileSearchToolCallContent", - "azure.ai.projects.models.FileSearchToolDefinition": "Azure.AI.Projects.Agents.FileSearchToolDefinition", - "azure.ai.projects.models.FileSearchToolDefinitionDetails": "Azure.AI.Projects.Agents.FileSearchToolDefinitionDetails", - "azure.ai.projects.models.FileSearchToolResource": "Azure.AI.Projects.Agents.FileSearchToolResource", - "azure.ai.projects.models.FunctionDefinition": "Azure.AI.Projects.Agents.FunctionDefinition", - "azure.ai.projects.models.FunctionName": "Azure.AI.Projects.Agents.FunctionName", - "azure.ai.projects.models.FunctionToolDefinition": "Azure.AI.Projects.Agents.FunctionToolDefinition", - "azure.ai.projects.models.IncompleteRunDetails": "Azure.AI.Projects.Agents.IncompleteRunDetails", - "azure.ai.projects.models.MAASModelConfig": "Azure.AI.Projects.MAASModelConfig", - "azure.ai.projects.models.MessageAttachment": "Azure.AI.Projects.Agents.MessageAttachment", - "azure.ai.projects.models.MessageContent": "Azure.AI.Projects.Agents.MessageContent", - "azure.ai.projects.models.MessageDelta": "Azure.AI.Projects.Agents.MessageDelta", - "azure.ai.projects.models.MessageDeltaChunk": "Azure.AI.Projects.Agents.MessageDeltaChunk", - "azure.ai.projects.models.MessageDeltaContent": "Azure.AI.Projects.Agents.MessageDeltaContent", - "azure.ai.projects.models.MessageDeltaImageFileContent": "Azure.AI.Projects.Agents.MessageDeltaImageFileContent", - "azure.ai.projects.models.MessageDeltaImageFileContentObject": "Azure.AI.Projects.Agents.MessageDeltaImageFileContentObject", - "azure.ai.projects.models.MessageDeltaTextAnnotation": "Azure.AI.Projects.Agents.MessageDeltaTextAnnotation", - "azure.ai.projects.models.MessageDeltaTextContent": "Azure.AI.Projects.Agents.MessageDeltaTextContent", - "azure.ai.projects.models.MessageDeltaTextContentObject": "Azure.AI.Projects.Agents.MessageDeltaTextContentObject", - "azure.ai.projects.models.MessageDeltaTextFileCitationAnnotation": "Azure.AI.Projects.Agents.MessageDeltaTextFileCitationAnnotation", - "azure.ai.projects.models.MessageDeltaTextFileCitationAnnotationObject": "Azure.AI.Projects.Agents.MessageDeltaTextFileCitationAnnotationObject", - "azure.ai.projects.models.MessageDeltaTextFilePathAnnotation": "Azure.AI.Projects.Agents.MessageDeltaTextFilePathAnnotation", - "azure.ai.projects.models.MessageDeltaTextFilePathAnnotationObject": "Azure.AI.Projects.Agents.MessageDeltaTextFilePathAnnotationObject", - "azure.ai.projects.models.MessageDeltaTextUrlCitationAnnotation": "Azure.AI.Projects.Agents.MessageDeltaTextUrlCitationAnnotation", - "azure.ai.projects.models.MessageDeltaTextUrlCitationDetails": "Azure.AI.Projects.Agents.MessageDeltaTextUrlCitationDetails", - "azure.ai.projects.models.MessageImageFileContent": "Azure.AI.Projects.Agents.MessageImageFileContent", - "azure.ai.projects.models.MessageImageFileDetails": "Azure.AI.Projects.Agents.MessageImageFileDetails", - "azure.ai.projects.models.MessageImageFileParam": "Azure.AI.Projects.Agents.MessageImageFileParam", - "azure.ai.projects.models.MessageImageUrlParam": "Azure.AI.Projects.Agents.MessageImageUrlParam", - "azure.ai.projects.models.MessageIncompleteDetails": "Azure.AI.Projects.Agents.MessageIncompleteDetails", - "azure.ai.projects.models.MessageInputContentBlock": "Azure.AI.Projects.Agents.MessageInputContentBlock", - "azure.ai.projects.models.MessageInputImageFileBlock": "Azure.AI.Projects.Agents.MessageInputImageFileBlock", - "azure.ai.projects.models.MessageInputImageUrlBlock": "Azure.AI.Projects.Agents.MessageInputImageUrlBlock", - "azure.ai.projects.models.MessageInputTextBlock": "Azure.AI.Projects.Agents.MessageInputTextBlock", - "azure.ai.projects.models.MessageTextAnnotation": "Azure.AI.Projects.Agents.MessageTextAnnotation", - "azure.ai.projects.models.MessageTextContent": "Azure.AI.Projects.Agents.MessageTextContent", - "azure.ai.projects.models.MessageTextDetails": "Azure.AI.Projects.Agents.MessageTextDetails", - "azure.ai.projects.models.MessageTextFileCitationAnnotation": "Azure.AI.Projects.Agents.MessageTextFileCitationAnnotation", - "azure.ai.projects.models.MessageTextFileCitationDetails": "Azure.AI.Projects.Agents.MessageTextFileCitationDetails", - "azure.ai.projects.models.MessageTextFilePathAnnotation": "Azure.AI.Projects.Agents.MessageTextFilePathAnnotation", - "azure.ai.projects.models.MessageTextFilePathDetails": "Azure.AI.Projects.Agents.MessageTextFilePathDetails", - "azure.ai.projects.models.MessageTextUrlCitationAnnotation": "Azure.AI.Projects.Agents.MessageTextUrlCitationAnnotation", - "azure.ai.projects.models.MessageTextUrlCitationDetails": "Azure.AI.Projects.Agents.MessageTextUrlCitationDetails", - "azure.ai.projects.models.MicrosoftFabricToolDefinition": "Azure.AI.Projects.Agents.MicrosoftFabricToolDefinition", - "azure.ai.projects.models.OpenAIFile": "Azure.AI.Projects.Agents.OpenAIFile", - "azure.ai.projects.models.OpenAIPageableListOfAgent": "Azure.AI.Projects.Agents.OpenAIPageableListOf", - "azure.ai.projects.models.OpenAIPageableListOfAgentThread": "Azure.AI.Projects.Agents.OpenAIPageableListOf", - "azure.ai.projects.models.OpenAIPageableListOfRunStep": "Azure.AI.Projects.Agents.OpenAIPageableListOf", - "azure.ai.projects.models.OpenAIPageableListOfThreadMessage": "Azure.AI.Projects.Agents.OpenAIPageableListOf", - "azure.ai.projects.models.OpenAIPageableListOfThreadRun": "Azure.AI.Projects.Agents.OpenAIPageableListOf", - "azure.ai.projects.models.OpenAIPageableListOfVectorStore": "Azure.AI.Projects.Agents.OpenAIPageableListOf", - "azure.ai.projects.models.OpenAIPageableListOfVectorStoreFile": "Azure.AI.Projects.Agents.OpenAIPageableListOf", - "azure.ai.projects.models.OpenApiAuthDetails": "Azure.AI.Projects.Agents.OpenApiAuthDetails", - "azure.ai.projects.models.OpenApiAnonymousAuthDetails": "Azure.AI.Projects.Agents.OpenApiAnonymousAuthDetails", - "azure.ai.projects.models.OpenApiConnectionAuthDetails": "Azure.AI.Projects.Agents.OpenApiConnectionAuthDetails", - "azure.ai.projects.models.OpenApiConnectionSecurityScheme": "Azure.AI.Projects.Agents.OpenApiConnectionSecurityScheme", - "azure.ai.projects.models.OpenApiFunctionDefinition": "Azure.AI.Projects.Agents.OpenApiFunctionDefinition", - "azure.ai.projects.models.OpenApiManagedAuthDetails": "Azure.AI.Projects.Agents.OpenApiManagedAuthDetails", - "azure.ai.projects.models.OpenApiManagedSecurityScheme": "Azure.AI.Projects.Agents.OpenApiManagedSecurityScheme", - "azure.ai.projects.models.OpenApiToolDefinition": "Azure.AI.Projects.Agents.OpenApiToolDefinition", - "azure.ai.projects.models.RecurrenceSchedule": "Azure.AI.Projects.RecurrenceSchedule", - "azure.ai.projects.models.RecurrenceTrigger": "Azure.AI.Projects.RecurrenceTrigger", - "azure.ai.projects.models.RequiredAction": "Azure.AI.Projects.Agents.RequiredAction", - "azure.ai.projects.models.RequiredToolCall": "Azure.AI.Projects.Agents.RequiredToolCall", - "azure.ai.projects.models.RequiredFunctionToolCall": "Azure.AI.Projects.Agents.RequiredFunctionToolCall", - "azure.ai.projects.models.RequiredFunctionToolCallDetails": "Azure.AI.Projects.Agents.RequiredFunctionToolCallDetails", - "azure.ai.projects.models.ResponseFormatJsonSchema": "Azure.AI.Projects.Agents.ResponseFormatJsonSchema", - "azure.ai.projects.models.ResponseFormatJsonSchemaType": "Azure.AI.Projects.Agents.ResponseFormatJsonSchemaType", - "azure.ai.projects.models.RunCompletionUsage": "Azure.AI.Projects.Agents.RunCompletionUsage", - "azure.ai.projects.models.RunError": "Azure.AI.Projects.Agents.RunError", - "azure.ai.projects.models.RunStep": "Azure.AI.Projects.Agents.RunStep", - "azure.ai.projects.models.RunStepToolCall": "Azure.AI.Projects.Agents.RunStepToolCall", - "azure.ai.projects.models.RunStepAzureAISearchToolCall": "Azure.AI.Projects.Agents.RunStepAzureAISearchToolCall", - "azure.ai.projects.models.RunStepBingGroundingToolCall": "Azure.AI.Projects.Agents.RunStepBingGroundingToolCall", - "azure.ai.projects.models.RunStepCodeInterpreterToolCallOutput": "Azure.AI.Projects.Agents.RunStepCodeInterpreterToolCallOutput", - "azure.ai.projects.models.RunStepCodeInterpreterImageOutput": "Azure.AI.Projects.Agents.RunStepCodeInterpreterImageOutput", - "azure.ai.projects.models.RunStepCodeInterpreterImageReference": "Azure.AI.Projects.Agents.RunStepCodeInterpreterImageReference", - "azure.ai.projects.models.RunStepCodeInterpreterLogOutput": "Azure.AI.Projects.Agents.RunStepCodeInterpreterLogOutput", - "azure.ai.projects.models.RunStepCodeInterpreterToolCall": "Azure.AI.Projects.Agents.RunStepCodeInterpreterToolCall", - "azure.ai.projects.models.RunStepCodeInterpreterToolCallDetails": "Azure.AI.Projects.Agents.RunStepCodeInterpreterToolCallDetails", - "azure.ai.projects.models.RunStepCompletionUsage": "Azure.AI.Projects.Agents.RunStepCompletionUsage", - "azure.ai.projects.models.RunStepCustomSearchToolCall": "Azure.AI.Projects.Agents.RunStepCustomSearchToolCall", - "azure.ai.projects.models.RunStepDelta": "Azure.AI.Projects.Agents.RunStepDelta", - "azure.ai.projects.models.RunStepDeltaChunk": "Azure.AI.Projects.Agents.RunStepDeltaChunk", - "azure.ai.projects.models.RunStepDeltaCodeInterpreterDetailItemObject": "Azure.AI.Projects.Agents.RunStepDeltaCodeInterpreterDetailItemObject", - "azure.ai.projects.models.RunStepDeltaCodeInterpreterOutput": "Azure.AI.Projects.Agents.RunStepDeltaCodeInterpreterOutput", - "azure.ai.projects.models.RunStepDeltaCodeInterpreterImageOutput": "Azure.AI.Projects.Agents.RunStepDeltaCodeInterpreterImageOutput", - "azure.ai.projects.models.RunStepDeltaCodeInterpreterImageOutputObject": "Azure.AI.Projects.Agents.RunStepDeltaCodeInterpreterImageOutputObject", - "azure.ai.projects.models.RunStepDeltaCodeInterpreterLogOutput": "Azure.AI.Projects.Agents.RunStepDeltaCodeInterpreterLogOutput", - "azure.ai.projects.models.RunStepDeltaToolCall": "Azure.AI.Projects.Agents.RunStepDeltaToolCall", - "azure.ai.projects.models.RunStepDeltaCodeInterpreterToolCall": "Azure.AI.Projects.Agents.RunStepDeltaCodeInterpreterToolCall", - "azure.ai.projects.models.RunStepDeltaDetail": "Azure.AI.Projects.Agents.RunStepDeltaDetail", - "azure.ai.projects.models.RunStepDeltaFileSearchToolCall": "Azure.AI.Projects.Agents.RunStepDeltaFileSearchToolCall", - "azure.ai.projects.models.RunStepDeltaFunction": "Azure.AI.Projects.Agents.RunStepDeltaFunction", - "azure.ai.projects.models.RunStepDeltaFunctionToolCall": "Azure.AI.Projects.Agents.RunStepDeltaFunctionToolCall", - "azure.ai.projects.models.RunStepDeltaMessageCreation": "Azure.AI.Projects.Agents.RunStepDeltaMessageCreation", - "azure.ai.projects.models.RunStepDeltaMessageCreationObject": "Azure.AI.Projects.Agents.RunStepDeltaMessageCreationObject", - "azure.ai.projects.models.RunStepDeltaToolCallObject": "Azure.AI.Projects.Agents.RunStepDeltaToolCallObject", - "azure.ai.projects.models.RunStepDetails": "Azure.AI.Projects.Agents.RunStepDetails", - "azure.ai.projects.models.RunStepError": "Azure.AI.Projects.Agents.RunStepError", - "azure.ai.projects.models.RunStepFileSearchToolCall": "Azure.AI.Projects.Agents.RunStepFileSearchToolCall", - "azure.ai.projects.models.RunStepFileSearchToolCallResult": "Azure.AI.Projects.Agents.RunStepFileSearchToolCallResult", - "azure.ai.projects.models.RunStepFileSearchToolCallResults": "Azure.AI.Projects.Agents.RunStepFileSearchToolCallResults", - "azure.ai.projects.models.RunStepFunctionToolCall": "Azure.AI.Projects.Agents.RunStepFunctionToolCall", - "azure.ai.projects.models.RunStepFunctionToolCallDetails": "Azure.AI.Projects.Agents.RunStepFunctionToolCallDetails", - "azure.ai.projects.models.RunStepMessageCreationDetails": "Azure.AI.Projects.Agents.RunStepMessageCreationDetails", - "azure.ai.projects.models.RunStepMessageCreationReference": "Azure.AI.Projects.Agents.RunStepMessageCreationReference", - "azure.ai.projects.models.RunStepMicrosoftFabricToolCall": "Azure.AI.Projects.Agents.RunStepMicrosoftFabricToolCall", - "azure.ai.projects.models.RunStepOpenAPIToolCall": "Azure.AI.Projects.Agents.RunStepOpenAPIToolCall", - "azure.ai.projects.models.RunStepSharepointToolCall": "Azure.AI.Projects.Agents.RunStepSharepointToolCall", - "azure.ai.projects.models.RunStepToolCallDetails": "Azure.AI.Projects.Agents.RunStepToolCallDetails", - "azure.ai.projects.models.SearchConfiguration": "Azure.AI.Projects.Agents.SearchConfiguration", - "azure.ai.projects.models.SearchConfigurationList": "Azure.AI.Projects.Agents.SearchConfigurationList", - "azure.ai.projects.models.SharepointToolDefinition": "Azure.AI.Projects.Agents.SharepointToolDefinition", - "azure.ai.projects.models.SubmitToolOutputsAction": "Azure.AI.Projects.Agents.SubmitToolOutputsAction", - "azure.ai.projects.models.SubmitToolOutputsDetails": "Azure.AI.Projects.Agents.SubmitToolOutputsDetails", - "azure.ai.projects.models.SystemData": "Azure.AI.Projects.SystemData", - "azure.ai.projects.models.ThreadDeletionStatus": "Azure.AI.Projects.Agents.ThreadDeletionStatus", - "azure.ai.projects.models.ThreadMessage": "Azure.AI.Projects.Agents.ThreadMessage", - "azure.ai.projects.models.ThreadMessageOptions": "Azure.AI.Projects.Agents.ThreadMessageOptions", - "azure.ai.projects.models.ThreadRun": "Azure.AI.Projects.Agents.ThreadRun", - "azure.ai.projects.models.ToolConnection": "Azure.AI.Projects.Agents.ToolConnection", - "azure.ai.projects.models.ToolConnectionList": "Azure.AI.Projects.Agents.ToolConnectionList", - "azure.ai.projects.models.ToolOutput": "Azure.AI.Projects.Agents.ToolOutput", - "azure.ai.projects.models.ToolResources": "Azure.AI.Projects.Agents.ToolResources", - "azure.ai.projects.models.TruncationObject": "Azure.AI.Projects.Agents.TruncationObject", - "azure.ai.projects.models.UpdateCodeInterpreterToolResourceOptions": "Azure.AI.Projects.Agents.UpdateCodeInterpreterToolResourceOptions", - "azure.ai.projects.models.UpdateFileSearchToolResourceOptions": "Azure.AI.Projects.Agents.UpdateFileSearchToolResourceOptions", - "azure.ai.projects.models.UpdateToolResourcesOptions": "Azure.AI.Projects.Agents.UpdateToolResourcesOptions", - "azure.ai.projects.models.VectorStore": "Azure.AI.Projects.Agents.VectorStore", - "azure.ai.projects.models.VectorStoreChunkingStrategyRequest": "Azure.AI.Projects.Agents.VectorStoreChunkingStrategyRequest", - "azure.ai.projects.models.VectorStoreAutoChunkingStrategyRequest": "Azure.AI.Projects.Agents.VectorStoreAutoChunkingStrategyRequest", - "azure.ai.projects.models.VectorStoreChunkingStrategyResponse": "Azure.AI.Projects.Agents.VectorStoreChunkingStrategyResponse", - "azure.ai.projects.models.VectorStoreAutoChunkingStrategyResponse": "Azure.AI.Projects.Agents.VectorStoreAutoChunkingStrategyResponse", - "azure.ai.projects.models.VectorStoreConfiguration": "Azure.AI.Projects.Agents.VectorStoreConfiguration", - "azure.ai.projects.models.VectorStoreConfigurations": "Azure.AI.Projects.Agents.VectorStoreConfigurations", - "azure.ai.projects.models.VectorStoreDataSource": "Azure.AI.Projects.Agents.VectorStoreDataSource", - "azure.ai.projects.models.VectorStoreDeletionStatus": "Azure.AI.Projects.Agents.VectorStoreDeletionStatus", - "azure.ai.projects.models.VectorStoreExpirationPolicy": "Azure.AI.Projects.Agents.VectorStoreExpirationPolicy", - "azure.ai.projects.models.VectorStoreFile": "Azure.AI.Projects.Agents.VectorStoreFile", - "azure.ai.projects.models.VectorStoreFileBatch": "Azure.AI.Projects.Agents.VectorStoreFileBatch", - "azure.ai.projects.models.VectorStoreFileCount": "Azure.AI.Projects.Agents.VectorStoreFileCount", - "azure.ai.projects.models.VectorStoreFileDeletionStatus": "Azure.AI.Projects.Agents.VectorStoreFileDeletionStatus", - "azure.ai.projects.models.VectorStoreFileError": "Azure.AI.Projects.Agents.VectorStoreFileError", - "azure.ai.projects.models.VectorStoreStaticChunkingStrategyOptions": "Azure.AI.Projects.Agents.VectorStoreStaticChunkingStrategyOptions", - "azure.ai.projects.models.VectorStoreStaticChunkingStrategyRequest": "Azure.AI.Projects.Agents.VectorStoreStaticChunkingStrategyRequest", - "azure.ai.projects.models.VectorStoreStaticChunkingStrategyResponse": "Azure.AI.Projects.Agents.VectorStoreStaticChunkingStrategyResponse", - "azure.ai.projects.models.OpenApiAuthType": "Azure.AI.Projects.Agents.OpenApiAuthType", - "azure.ai.projects.models.VectorStoreDataSourceAssetType": "Azure.AI.Projects.Agents.VectorStoreDataSourceAssetType", - "azure.ai.projects.models.AzureAISearchQueryType": "Azure.AI.Projects.Agents.AzureAISearchQueryType", - "azure.ai.projects.models.AgentsApiResponseFormatMode": "Azure.AI.Projects.Agents.AgentsApiResponseFormatMode", - "azure.ai.projects.models.ResponseFormat": "Azure.AI.Projects.Agents.ResponseFormat", - "azure.ai.projects.models.ListSortOrder": "Azure.AI.Projects.Agents.ListSortOrder", - "azure.ai.projects.models.MessageRole": "Azure.AI.Projects.Agents.MessageRole", - "azure.ai.projects.models.MessageBlockType": "Azure.AI.Projects.Agents.MessageBlockType", - "azure.ai.projects.models.ImageDetailLevel": "Azure.AI.Projects.Agents.ImageDetailLevel", - "azure.ai.projects.models.MessageStatus": "Azure.AI.Projects.Agents.MessageStatus", - "azure.ai.projects.models.MessageIncompleteDetailsReason": "Azure.AI.Projects.Agents.MessageIncompleteDetailsReason", - "azure.ai.projects.models.RunStatus": "Azure.AI.Projects.Agents.RunStatus", - "azure.ai.projects.models.IncompleteDetailsReason": "Azure.AI.Projects.Agents.IncompleteDetailsReason", - "azure.ai.projects.models.TruncationStrategy": "Azure.AI.Projects.Agents.TruncationStrategy", - "azure.ai.projects.models.AgentsApiToolChoiceOptionMode": "Azure.AI.Projects.Agents.AgentsApiToolChoiceOptionMode", - "azure.ai.projects.models.AgentsNamedToolChoiceType": "Azure.AI.Projects.Agents.AgentsNamedToolChoiceType", - "azure.ai.projects.models.RunAdditionalFieldList": "Azure.AI.Projects.Agents.RunAdditionalFieldList", - "azure.ai.projects.models.RunStepType": "Azure.AI.Projects.Agents.RunStepType", - "azure.ai.projects.models.RunStepStatus": "Azure.AI.Projects.Agents.RunStepStatus", - "azure.ai.projects.models.RunStepErrorCode": "Azure.AI.Projects.Agents.RunStepErrorCode", - "azure.ai.projects.models.FilePurpose": "Azure.AI.Projects.Agents.FilePurpose", - "azure.ai.projects.models.FileState": "Azure.AI.Projects.Agents.FileState", - "azure.ai.projects.models.VectorStoreStatus": "Azure.AI.Projects.Agents.VectorStoreStatus", - "azure.ai.projects.models.VectorStoreExpirationPolicyAnchor": "Azure.AI.Projects.Agents.VectorStoreExpirationPolicyAnchor", - "azure.ai.projects.models.VectorStoreChunkingStrategyRequestType": "Azure.AI.Projects.Agents.VectorStoreChunkingStrategyRequestType", - "azure.ai.projects.models.VectorStoreFileStatus": "Azure.AI.Projects.Agents.VectorStoreFileStatus", - "azure.ai.projects.models.VectorStoreFileErrorCode": "Azure.AI.Projects.Agents.VectorStoreFileErrorCode", - "azure.ai.projects.models.VectorStoreChunkingStrategyResponseType": "Azure.AI.Projects.Agents.VectorStoreChunkingStrategyResponseType", - "azure.ai.projects.models.VectorStoreFileStatusFilter": "Azure.AI.Projects.Agents.VectorStoreFileStatusFilter", - "azure.ai.projects.models.VectorStoreFileBatchStatus": "Azure.AI.Projects.Agents.VectorStoreFileBatchStatus", - "azure.ai.projects.models.AuthenticationType": "Azure.AI.Projects.AuthenticationType", + "azure.ai.projects.models.FileDatasetVersion": "Azure.AI.Projects.FileDatasetVersion", + "azure.ai.projects.models.FolderDatasetVersion": "Azure.AI.Projects.FolderDatasetVersion", + "azure.ai.projects.models.InputData": "Azure.AI.Projects.InputData", + "azure.ai.projects.models.InputDataset": "Azure.AI.Projects.InputDataset", + "azure.ai.projects.models.ManagedAzureAISearchIndex": "Azure.AI.Projects.ManagedAzureAISearchIndex", + "azure.ai.projects.models.ModelDeployment": "Azure.AI.Projects.ModelDeployment", + "azure.ai.projects.models.NoAuthenticationCredentials": "Azure.AI.Projects.NoAuthenticationCredentials", + "azure.ai.projects.models.PendingUploadRequest": "Azure.AI.Projects.PendingUploadRequest", + "azure.ai.projects.models.PendingUploadResponse": "Azure.AI.Projects.PendingUploadResponse", + "azure.ai.projects.models.RedTeam": "Azure.AI.Projects.RedTeam", + "azure.ai.projects.models.SasCredential": "Azure.AI.Projects.SasCredential", + "azure.ai.projects.models.SASCredentials": "Azure.AI.Projects.SASCredentials", + "azure.ai.projects.models.Sku": "Azure.AI.Projects.Sku", "azure.ai.projects.models.ConnectionType": "Azure.AI.Projects.ConnectionType", - "azure.ai.projects.models.Frequency": "Azure.AI.Projects.Frequency", - "azure.ai.projects.models.WeekDays": "Azure.AI.Projects.WeekDays", - "azure.ai.projects.models.ThreadStreamEvent": "Azure.AI.Projects.Agents.ThreadStreamEvent", - "azure.ai.projects.models.RunStreamEvent": "Azure.AI.Projects.Agents.RunStreamEvent", - "azure.ai.projects.models.RunStepStreamEvent": "Azure.AI.Projects.Agents.RunStepStreamEvent", - "azure.ai.projects.models.MessageStreamEvent": "Azure.AI.Projects.Agents.MessageStreamEvent", - "azure.ai.projects.models.ErrorEvent": "Azure.AI.Projects.Agents.ErrorEvent", - "azure.ai.projects.models.DoneEvent": "Azure.AI.Projects.Agents.DoneEvent", - "azure.ai.projects.models.AgentStreamEvent": "Azure.AI.Projects.Agents.AgentStreamEvent", - "azure.ai.projects.AIProjectClient.agents.create_agent": "Azure.AI.Projects.Agents.createAgent", - "azure.ai.projects.AIProjectClient.agents.list_agents": "Azure.AI.Projects.Agents.listAgents", - "azure.ai.projects.AIProjectClient.agents.get_agent": "Azure.AI.Projects.Agents.getAgent", - "azure.ai.projects.AIProjectClient.agents.update_agent": "Azure.AI.Projects.Agents.updateAgent", - "azure.ai.projects.AIProjectClient.agents.delete_agent": "Azure.AI.Projects.Agents.deleteAgent", - "azure.ai.projects.AIProjectClient.agents.create_thread": "Azure.AI.Projects.Agents.createThread", - "azure.ai.projects.AIProjectClient.agents.get_thread": "Azure.AI.Projects.Agents.getThread", - "azure.ai.projects.AIProjectClient.agents.update_thread": "Azure.AI.Projects.Agents.updateThread", - "azure.ai.projects.AIProjectClient.agents.delete_thread": "Azure.AI.Projects.Agents.deleteThread", - "azure.ai.projects.AIProjectClient.agents.list_threads": "Azure.AI.Projects.Agents.listThreads", - "azure.ai.projects.AIProjectClient.agents.create_message": "Azure.AI.Projects.Agents.createMessage", - "azure.ai.projects.AIProjectClient.agents.list_messages": "Azure.AI.Projects.Agents.listMessages", - "azure.ai.projects.AIProjectClient.agents.get_message": "Azure.AI.Projects.Agents.getMessage", - "azure.ai.projects.AIProjectClient.agents.update_message": "Azure.AI.Projects.Agents.updateMessage", - "azure.ai.projects.AIProjectClient.agents.create_run": "Azure.AI.Projects.Agents.createRun", - "azure.ai.projects.AIProjectClient.agents.list_runs": "Azure.AI.Projects.Agents.listRuns", - "azure.ai.projects.AIProjectClient.agents.get_run": "Azure.AI.Projects.Agents.getRun", - "azure.ai.projects.AIProjectClient.agents.update_run": "Azure.AI.Projects.Agents.updateRun", - "azure.ai.projects.AIProjectClient.agents.submit_tool_outputs_to_run": "Azure.AI.Projects.Agents.submitToolOutputsToRun", - "azure.ai.projects.AIProjectClient.agents.cancel_run": "Azure.AI.Projects.Agents.cancelRun", - "azure.ai.projects.AIProjectClient.agents.create_thread_and_run": "Azure.AI.Projects.Agents.createThreadAndRun", - "azure.ai.projects.AIProjectClient.agents.get_run_step": "Azure.AI.Projects.Agents.getRunStep", - "azure.ai.projects.AIProjectClient.agents.list_run_steps": "Azure.AI.Projects.Agents.listRunSteps", - "azure.ai.projects.AIProjectClient.agents.list_files": "Azure.AI.Projects.Agents.listFiles", - "azure.ai.projects.AIProjectClient.agents.delete_file": "Azure.AI.Projects.Agents.deleteFile", - "azure.ai.projects.AIProjectClient.agents.get_file": "Azure.AI.Projects.Agents.getFile", - "azure.ai.projects.AIProjectClient.agents.list_vector_stores": "Azure.AI.Projects.Agents.listVectorStores", - "azure.ai.projects.AIProjectClient.agents.create_vector_store": "Azure.AI.Projects.Agents.createVectorStore", - "azure.ai.projects.AIProjectClient.agents.get_vector_store": "Azure.AI.Projects.Agents.getVectorStore", - "azure.ai.projects.AIProjectClient.agents.modify_vector_store": "Azure.AI.Projects.Agents.modifyVectorStore", - "azure.ai.projects.AIProjectClient.agents.delete_vector_store": "Azure.AI.Projects.Agents.deleteVectorStore", - "azure.ai.projects.AIProjectClient.agents.list_vector_store_files": "Azure.AI.Projects.Agents.listVectorStoreFiles", - "azure.ai.projects.AIProjectClient.agents.create_vector_store_file": "Azure.AI.Projects.Agents.createVectorStoreFile", - "azure.ai.projects.AIProjectClient.agents.get_vector_store_file": "Azure.AI.Projects.Agents.getVectorStoreFile", - "azure.ai.projects.AIProjectClient.agents.delete_vector_store_file": "Azure.AI.Projects.Agents.deleteVectorStoreFile", - "azure.ai.projects.AIProjectClient.agents.create_vector_store_file_batch": "Azure.AI.Projects.Agents.createVectorStoreFileBatch", - "azure.ai.projects.AIProjectClient.agents.get_vector_store_file_batch": "Azure.AI.Projects.Agents.getVectorStoreFileBatch", - "azure.ai.projects.AIProjectClient.agents.cancel_vector_store_file_batch": "Azure.AI.Projects.Agents.cancelVectorStoreFileBatch", - "azure.ai.projects.AIProjectClient.agents.list_vector_store_file_batch_files": "Azure.AI.Projects.Agents.listVectorStoreFileBatchFiles", - "azure.ai.projects.AIProjectClient.evaluations.get": "Azure.AI.Projects.Evaluations.get", - "azure.ai.projects.AIProjectClient.evaluations.create": "Azure.AI.Projects.Evaluations.create", - "azure.ai.projects.AIProjectClient.evaluations.list": "Azure.AI.Projects.Evaluations.list", - "azure.ai.projects.AIProjectClient.evaluations.update": "Azure.AI.Projects.Evaluations.update", - "azure.ai.projects.AIProjectClient.evaluations.get_schedule": "Azure.AI.Projects.Evaluations.getSchedule", - "azure.ai.projects.AIProjectClient.evaluations.create_or_replace_schedule": "Azure.AI.Projects.Evaluations.createOrReplaceSchedule", - "azure.ai.projects.AIProjectClient.evaluations.list_schedule": "Azure.AI.Projects.Evaluations.listSchedule", - "azure.ai.projects.AIProjectClient.evaluations.disable_schedule": "Azure.AI.Projects.Evaluations.disableSchedule" + "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.IndexType": "Azure.AI.Projects.IndexType", + "azure.ai.projects.models.DeploymentType": "Azure.AI.Projects.DeploymentType", + "azure.ai.projects.models.AttackStrategy": "Azure.AI.Projects.AttackStrategy", + "azure.ai.projects.models.RiskCategory": "Azure.AI.Projects.RiskCategory", + "azure.ai.projects.operations.ConnectionsOperations.list": "Azure.AI.Projects.Connections.list", + "azure.ai.projects.aio.operations.ConnectionsOperations.list": "Azure.AI.Projects.Connections.list", + "azure.ai.projects.operations.EvaluationsOperations.get": "Azure.AI.Projects.Evaluations.get", + "azure.ai.projects.aio.operations.EvaluationsOperations.get": "Azure.AI.Projects.Evaluations.get", + "azure.ai.projects.operations.EvaluationsOperations.list": "Azure.AI.Projects.Evaluations.list", + "azure.ai.projects.aio.operations.EvaluationsOperations.list": "Azure.AI.Projects.Evaluations.list", + "azure.ai.projects.operations.EvaluationsOperations.create_run": "Azure.AI.Projects.Evaluations.createRun", + "azure.ai.projects.aio.operations.EvaluationsOperations.create_run": "Azure.AI.Projects.Evaluations.createRun", + "azure.ai.projects.operations.EvaluationsOperations.create_agent_evaluation": "Azure.AI.Projects.Evaluations.createAgentEvaluation", + "azure.ai.projects.aio.operations.EvaluationsOperations.create_agent_evaluation": "Azure.AI.Projects.Evaluations.createAgentEvaluation", + "azure.ai.projects.operations.DatasetsOperations.list_versions": "Azure.AI.Projects.ServicePatterns.Datasets.listVersions", + "azure.ai.projects.aio.operations.DatasetsOperations.list_versions": "Azure.AI.Projects.ServicePatterns.Datasets.listVersions", + "azure.ai.projects.operations.DatasetsOperations.list": "Azure.AI.Projects.ServicePatterns.Datasets.listLatest", + "azure.ai.projects.aio.operations.DatasetsOperations.list": "Azure.AI.Projects.ServicePatterns.Datasets.listLatest", + "azure.ai.projects.operations.DatasetsOperations.get": "Azure.AI.Projects.ServicePatterns.Datasets.getVersion", + "azure.ai.projects.aio.operations.DatasetsOperations.get": "Azure.AI.Projects.ServicePatterns.Datasets.getVersion", + "azure.ai.projects.operations.DatasetsOperations.delete": "Azure.AI.Projects.ServicePatterns.Datasets.deleteVersion", + "azure.ai.projects.aio.operations.DatasetsOperations.delete": "Azure.AI.Projects.ServicePatterns.Datasets.deleteVersion", + "azure.ai.projects.operations.DatasetsOperations.create_or_update": "Azure.AI.Projects.ServicePatterns.Datasets.createOrUpdateVersion", + "azure.ai.projects.aio.operations.DatasetsOperations.create_or_update": "Azure.AI.Projects.ServicePatterns.Datasets.createOrUpdateVersion", + "azure.ai.projects.operations.DatasetsOperations.pending_upload": "Azure.AI.Projects.Datasets.startPendingUploadVersion", + "azure.ai.projects.aio.operations.DatasetsOperations.pending_upload": "Azure.AI.Projects.Datasets.startPendingUploadVersion", + "azure.ai.projects.operations.DatasetsOperations.get_credentials": "Azure.AI.Projects.Datasets.getCredentials", + "azure.ai.projects.aio.operations.DatasetsOperations.get_credentials": "Azure.AI.Projects.Datasets.getCredentials", + "azure.ai.projects.operations.IndexesOperations.list_versions": "Azure.AI.Projects.ServicePatterns.Indexes.listVersions", + "azure.ai.projects.aio.operations.IndexesOperations.list_versions": "Azure.AI.Projects.ServicePatterns.Indexes.listVersions", + "azure.ai.projects.operations.IndexesOperations.list": "Azure.AI.Projects.ServicePatterns.Indexes.listLatest", + "azure.ai.projects.aio.operations.IndexesOperations.list": "Azure.AI.Projects.ServicePatterns.Indexes.listLatest", + "azure.ai.projects.operations.IndexesOperations.get": "Azure.AI.Projects.ServicePatterns.Indexes.getVersion", + "azure.ai.projects.aio.operations.IndexesOperations.get": "Azure.AI.Projects.ServicePatterns.Indexes.getVersion", + "azure.ai.projects.operations.IndexesOperations.delete": "Azure.AI.Projects.ServicePatterns.Indexes.deleteVersion", + "azure.ai.projects.aio.operations.IndexesOperations.delete": "Azure.AI.Projects.ServicePatterns.Indexes.deleteVersion", + "azure.ai.projects.operations.IndexesOperations.create_or_update": "Azure.AI.Projects.ServicePatterns.Indexes.createOrUpdateVersion", + "azure.ai.projects.aio.operations.IndexesOperations.create_or_update": "Azure.AI.Projects.ServicePatterns.Indexes.createOrUpdateVersion", + "azure.ai.projects.operations.DeploymentsOperations.get": "Azure.AI.Projects.Deployments.get", + "azure.ai.projects.aio.operations.DeploymentsOperations.get": "Azure.AI.Projects.Deployments.get", + "azure.ai.projects.operations.DeploymentsOperations.list": "Azure.AI.Projects.Deployments.list", + "azure.ai.projects.aio.operations.DeploymentsOperations.list": "Azure.AI.Projects.Deployments.list", + "azure.ai.projects.operations.RedTeamsOperations.get": "Azure.AI.Projects.RedTeams.get", + "azure.ai.projects.aio.operations.RedTeamsOperations.get": "Azure.AI.Projects.RedTeams.get", + "azure.ai.projects.operations.RedTeamsOperations.list": "Azure.AI.Projects.RedTeams.list", + "azure.ai.projects.aio.operations.RedTeamsOperations.list": "Azure.AI.Projects.RedTeams.list", + "azure.ai.projects.operations.RedTeamsOperations.create_run": "Azure.AI.Projects.RedTeams.createRun", + "azure.ai.projects.aio.operations.RedTeamsOperations.create_run": "Azure.AI.Projects.RedTeams.createRun" } } \ No newline at end of file diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/_client.py b/sdk/ai/azure-ai-projects/azure/ai/projects/_client.py index c92b31409e35..71ab105215bb 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/_client.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/_client.py @@ -1,4 +1,3 @@ -# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -16,62 +15,58 @@ from azure.core.rest import HttpRequest, HttpResponse from ._configuration import AIProjectClientConfiguration -from ._serialization import Deserializer, Serializer -from .operations import AgentsOperations, ConnectionsOperations, EvaluationsOperations, TelemetryOperations +from ._utils.serialization import Deserializer, Serializer +from .operations import ( + ConnectionsOperations, + DatasetsOperations, + DeploymentsOperations, + EvaluationsOperations, + IndexesOperations, + RedTeamsOperations, + ServicePatternsOperations, +) if TYPE_CHECKING: from azure.core.credentials import TokenCredential -class AIProjectClient: +class AIProjectClient: # pylint: disable=too-many-instance-attributes """AIProjectClient. - :ivar agents: AgentsOperations operations - :vartype agents: azure.ai.projects.operations.AgentsOperations + :ivar service_patterns: ServicePatternsOperations operations + :vartype service_patterns: azure.ai.projects.operations.ServicePatternsOperations :ivar connections: ConnectionsOperations operations :vartype connections: azure.ai.projects.operations.ConnectionsOperations - :ivar telemetry: TelemetryOperations operations - :vartype telemetry: azure.ai.projects.operations.TelemetryOperations :ivar evaluations: EvaluationsOperations operations :vartype evaluations: azure.ai.projects.operations.EvaluationsOperations - :param endpoint: The Azure AI Foundry project endpoint, in the form - ``https://.api.azureml.ms`` or - ``https://..api.azureml.ms``, where is the - Azure region where the project is deployed (e.g. westus) and is the GUID of - the Enterprise private link. Required. + :ivar datasets: DatasetsOperations operations + :vartype datasets: azure.ai.projects.operations.DatasetsOperations + :ivar indexes: IndexesOperations operations + :vartype indexes: azure.ai.projects.operations.IndexesOperations + :ivar deployments: DeploymentsOperations operations + :vartype deployments: azure.ai.projects.operations.DeploymentsOperations + :ivar red_teams: RedTeamsOperations operations + :vartype red_teams: azure.ai.projects.operations.RedTeamsOperations + :param endpoint: Project endpoint. In the form + "https://.services.ai.azure.com/api/projects/_project" + if your Foundry Hub has only one Project, or to use the default Project in your Hub. Or in the + form + "https://.services.ai.azure.com/api/projects/" + if you want to explicitly + specify the Foundry Project name. Required. :type endpoint: str - :param subscription_id: The Azure subscription ID. Required. - :type subscription_id: str - :param resource_group_name: The name of the Azure Resource Group. Required. - :type resource_group_name: str - :param project_name: The Azure AI Foundry project name. Required. - :type project_name: str :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials.TokenCredential :keyword api_version: The API version to use for this operation. Default value is - "2024-07-01-preview". Note that overriding this default value may result in unsupported + "2025-05-15-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, - endpoint: str, - subscription_id: str, - resource_group_name: str, - project_name: str, - credential: "TokenCredential", - **kwargs: Any - ) -> None: - _endpoint = "{endpoint}/agents/v1.0/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{projectName}" - self._config = AIProjectClientConfiguration( - endpoint=endpoint, - subscription_id=subscription_id, - resource_group_name=resource_group_name, - project_name=project_name, - credential=credential, - **kwargs - ) + def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: + _endpoint = "{endpoint}" + self._config = AIProjectClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -94,10 +89,15 @@ def __init__( self._serialize = Serializer() self._deserialize = Deserializer() self._serialize.client_side_validation = False - self.agents = AgentsOperations(self._client, self._config, self._serialize, self._deserialize) + self.service_patterns = ServicePatternsOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.connections = ConnectionsOperations(self._client, self._config, self._serialize, self._deserialize) - self.telemetry = TelemetryOperations(self._client, self._config, self._serialize, self._deserialize) self.evaluations = EvaluationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.datasets = DatasetsOperations(self._client, self._config, self._serialize, self._deserialize) + self.indexes = IndexesOperations(self._client, self._config, self._serialize, self._deserialize) + self.deployments = DeploymentsOperations(self._client, self._config, self._serialize, self._deserialize) + self.red_teams = RedTeamsOperations(self._client, self._config, self._serialize, self._deserialize) def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. @@ -119,12 +119,7 @@ def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: request_copy = deepcopy(request) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/_configuration.py b/sdk/ai/azure-ai-projects/azure/ai/projects/_configuration.py index 3bbeed37a0c7..3fdc95fa879d 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/_configuration.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/_configuration.py @@ -22,55 +22,34 @@ class AIProjectClientConfiguration: # pylint: disable=too-many-instance-attribu Note that all parameters used to create this instance are saved as instance attributes. - :param endpoint: The Azure AI Foundry project endpoint, in the form - ``https://.api.azureml.ms`` or - ``https://..api.azureml.ms``, where is the - Azure region where the project is deployed (e.g. westus) and is the GUID of - the Enterprise private link. Required. + :param endpoint: Project endpoint. In the form + "https://.services.ai.azure.com/api/projects/_project" + if your Foundry Hub has only one Project, or to use the default Project in your Hub. Or in the + form + "https://.services.ai.azure.com/api/projects/" + if you want to explicitly + specify the Foundry Project name. Required. :type endpoint: str - :param subscription_id: The Azure subscription ID. Required. - :type subscription_id: str - :param resource_group_name: The name of the Azure Resource Group. Required. - :type resource_group_name: str - :param project_name: The Azure AI Foundry project name. Required. - :type project_name: str :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials.TokenCredential :keyword api_version: The API version to use for this operation. Default value is - "2024-07-01-preview". Note that overriding this default value may result in unsupported + "2025-05-15-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, - endpoint: str, - subscription_id: str, - resource_group_name: str, - project_name: str, - credential: "TokenCredential", - **kwargs: Any - ) -> None: - api_version: str = kwargs.pop("api_version", "2024-07-01-preview") + def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2025-05-15-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - if resource_group_name is None: - raise ValueError("Parameter 'resource_group_name' must not be None.") - if project_name is None: - raise ValueError("Parameter 'project_name' must not be None.") if credential is None: raise ValueError("Parameter 'credential' must not be None.") self.endpoint = endpoint - self.subscription_id = subscription_id - self.resource_group_name = resource_group_name - self.project_name = project_name self.credential = credential self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://cognitiveservices.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "ai-projects/{}".format(VERSION)) self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/_patch.py b/sdk/ai/azure-ai-projects/azure/ai/projects/_patch.py index 06ceb9c67f05..8bcb627aa475 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/_patch.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/_patch.py @@ -1,300 +1,15 @@ -# pylint: disable=line-too-long,useless-suppression -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -import uuid -from os import PathLike -from pathlib import Path -from typing import Any, Dict, List, Tuple, Union, Optional -from typing_extensions import Self +from typing import List -from azure.core import PipelineClient -from azure.core.credentials import TokenCredential -from azure.core.pipeline import policies - -from ._client import AIProjectClient as ClientGenerated -from ._configuration import AIProjectClientConfiguration -from ._serialization import Deserializer, Serializer -from .operations import AgentsOperations, ConnectionsOperations, EvaluationsOperations, TelemetryOperations -from .operations._patch import InferenceOperations - - -class AIProjectClient( - ClientGenerated -): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes - def __init__( # pylint: disable=super-init-not-called,too-many-statements - self, - endpoint: str, - subscription_id: str, - resource_group_name: str, - project_name: str, - credential: "TokenCredential", - **kwargs: Any, - ) -> None: - # TODO: Validate input formats with regex match (e.g. subscription ID) - if not endpoint: - raise ValueError("endpoint is required") - if not subscription_id: - raise ValueError("subscription_id ID is required") - if not resource_group_name: - raise ValueError("resource_group_name is required") - if not project_name: - raise ValueError("project_name is required") - if not credential: - raise ValueError("credential is required") - if "api_version" in kwargs: - raise ValueError("No support for overriding the API version") - if "credential_scopes" in kwargs: - raise ValueError("No support for overriding the credential scopes") - - kwargs0 = kwargs.copy() - kwargs1 = kwargs.copy() - kwargs2 = kwargs.copy() - kwargs3 = kwargs.copy() - - self._user_agent: Optional[str] = kwargs.get("user_agent", None) - - # For getting AppInsights connection string from the AppInsights resource. - # The AppInsights resource URL is not known at this point. We need to get it from the - # AzureML "Workspace - Get" REST API call. It will have the form: - # https://management.azure.com/subscriptions/{appinsights_subscription_id}/resourceGroups/{appinsights_resource_group_name}/providers/microsoft.insights/components/{appinsights_resource_name} - _endpoint0 = "https://management.azure.com" - self._config0: AIProjectClientConfiguration = AIProjectClientConfiguration( - endpoint=endpoint, - subscription_id=subscription_id, - resource_group_name=resource_group_name, - project_name=project_name, - credential=credential, - api_version="2020-02-02", - credential_scopes=["https://management.azure.com/.default"], - **kwargs0, - ) - - _policies0 = kwargs0.pop("policies", None) - if _policies0 is None: - _policies0 = [ - policies.RequestIdPolicy(**kwargs0), - self._config0.headers_policy, - self._config0.user_agent_policy, - self._config0.proxy_policy, - policies.ContentDecodePolicy(**kwargs0), - self._config0.redirect_policy, - self._config0.retry_policy, - self._config0.authentication_policy, - self._config0.custom_hook_policy, - self._config0.logging_policy, - policies.DistributedTracingPolicy(**kwargs0), - policies.SensitiveHeaderCleanupPolicy(**kwargs0) if self._config0.redirect_policy else None, - self._config0.http_logging_policy, - ] - self._client0: PipelineClient = PipelineClient(base_url=_endpoint0, policies=_policies0, **kwargs0) - - # For Endpoints operations (listing connections, getting connection properties, getting project properties) - _endpoint1 = ( - "https://management.azure.com/" - + f"subscriptions/{subscription_id}/" - + f"resourceGroups/{resource_group_name}/" - + "providers/Microsoft.MachineLearningServices/" - + f"workspaces/{project_name}" - ) - self._config1: AIProjectClientConfiguration = AIProjectClientConfiguration( - endpoint=endpoint, - subscription_id=subscription_id, - resource_group_name=resource_group_name, - project_name=project_name, - credential=credential, - api_version="2024-07-01-preview", - credential_scopes=["https://management.azure.com/.default"], - **kwargs1, - ) - _policies1 = kwargs1.pop("policies", None) - if _policies1 is None: - _policies1 = [ - policies.RequestIdPolicy(**kwargs1), - self._config1.headers_policy, - self._config1.user_agent_policy, - self._config1.proxy_policy, - policies.ContentDecodePolicy(**kwargs1), - self._config1.redirect_policy, - self._config1.retry_policy, - self._config1.authentication_policy, - self._config1.custom_hook_policy, - self._config1.logging_policy, - policies.DistributedTracingPolicy(**kwargs1), - policies.SensitiveHeaderCleanupPolicy(**kwargs1) if self._config1.redirect_policy else None, - self._config1.http_logging_policy, - ] - self._client1: PipelineClient = PipelineClient(base_url=_endpoint1, policies=_policies1, **kwargs1) - - # For Agents operations - _endpoint2 = f"{endpoint}/agents/v1.0/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}/providers/Microsoft.MachineLearningServices/workspaces/{project_name}" # pylint: disable=line-too-long - self._config2 = AIProjectClientConfiguration( - endpoint=endpoint, - subscription_id=subscription_id, - resource_group_name=resource_group_name, - project_name=project_name, - credential=credential, - api_version="2024-12-01-preview", - credential_scopes=["https://ml.azure.com/.default"], - **kwargs2, - ) - _policies2 = kwargs2.pop("policies", None) - if _policies2 is None: - _policies2 = [ - policies.RequestIdPolicy(**kwargs2), - self._config2.headers_policy, - self._config2.user_agent_policy, - self._config2.proxy_policy, - policies.ContentDecodePolicy(**kwargs2), - self._config2.redirect_policy, - self._config2.retry_policy, - self._config2.authentication_policy, - self._config2.custom_hook_policy, - self._config2.logging_policy, - policies.DistributedTracingPolicy(**kwargs2), - policies.SensitiveHeaderCleanupPolicy(**kwargs2) if self._config2.redirect_policy else None, - self._config2.http_logging_policy, - ] - self._client2: PipelineClient = PipelineClient(base_url=_endpoint2, policies=_policies2, **kwargs2) - - # For Cloud Evaluations operations - # cSpell:disable-next-line - _endpoint3 = f"{endpoint}/raisvc/v1.0/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}/providers/Microsoft.MachineLearningServices/workspaces/{project_name}" # pylint: disable=line-too-long - self._config3 = AIProjectClientConfiguration( - endpoint=endpoint, - subscription_id=subscription_id, - resource_group_name=resource_group_name, - project_name=project_name, - credential=credential, - api_version="2024-07-01-preview", # TODO: Update me - credential_scopes=["https://ml.azure.com/.default"], # TODO: Update once service changes are ready - **kwargs3, - ) - _policies3 = kwargs3.pop("policies", None) - if _policies3 is None: - _policies3 = [ - policies.RequestIdPolicy(**kwargs3), - self._config3.headers_policy, - self._config3.user_agent_policy, - self._config3.proxy_policy, - policies.ContentDecodePolicy(**kwargs3), - self._config3.redirect_policy, - self._config3.retry_policy, - self._config3.authentication_policy, - self._config3.custom_hook_policy, - self._config3.logging_policy, - policies.DistributedTracingPolicy(**kwargs3), - policies.SensitiveHeaderCleanupPolicy(**kwargs3) if self._config3.redirect_policy else None, - self._config3.http_logging_policy, - ] - self._client3: PipelineClient = PipelineClient(base_url=_endpoint3, policies=_policies3, **kwargs3) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - self.telemetry = TelemetryOperations( - self._client0, self._config0, self._serialize, self._deserialize, outer_instance=self - ) - self.connections = ConnectionsOperations(self._client1, self._config1, self._serialize, self._deserialize) - self.agents = AgentsOperations(self._client2, self._config2, self._serialize, self._deserialize) - self.evaluations = EvaluationsOperations(self._client3, self._config3, self._serialize, self._deserialize) - self.inference = InferenceOperations(self) - - def close(self) -> None: - self._client0.close() - self._client1.close() - self._client2.close() - self._client3.close() - - def __enter__(self) -> Self: - self._client0.__enter__() - self._client1.__enter__() - self._client2.__enter__() - self._client3.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._client0.__exit__(*exc_details) - self._client1.__exit__(*exc_details) - self._client2.__exit__(*exc_details) - self._client3.__exit__(*exc_details) - - @classmethod - def from_connection_string(cls, conn_str: str, credential: "TokenCredential", **kwargs) -> Self: - """ - Create an AIProjectClient from a connection string. - - :param str conn_str: The connection string, copied from your AI Foundry project. - :param TokenCredential credential: Credential used to authenticate requests to the service. - :return: An AIProjectClient instance. - :rtype: AIProjectClient - """ - if not conn_str: - raise ValueError("Connection string is required") - parts = conn_str.split(";") - if len(parts) != 4: - raise ValueError("Invalid connection string format") - endpoint = "https://" + parts[0] - subscription_id = parts[1] - resource_group_name = parts[2] - project_name = parts[3] - return cls(endpoint, subscription_id, resource_group_name, project_name, credential, **kwargs) - - def upload_file(self, file_path: Union[Path, str, PathLike]) -> Tuple[str, str]: - """Upload a file to the Azure AI Foundry project. - This method required *azure-ai-ml* to be installed. - - :param file_path: The path to the file to upload. - :type file_path: Union[str, Path, PathLike] - :return: The tuple, containing asset id and asset URI of uploaded file. - :rtype: Tuple[str] - """ - try: - from azure.ai.ml import MLClient # type: ignore - from azure.ai.ml.constants import AssetTypes # type: ignore - from azure.ai.ml.entities import Data # type: ignore - except ImportError as e: - raise ImportError( - "azure-ai-ml must be installed to use this function. Please install it using `pip install azure-ai-ml`" - ) from e - - data = Data( - path=str(file_path), - type=AssetTypes.URI_FILE, - name=str(uuid.uuid4()), # generating random name - is_anonymous=True, - version="1", - ) - - ml_client = MLClient( - self._config3.credential, - self._config3.subscription_id, - self._config3.resource_group_name, - self._config3.project_name, - ) - - data_asset = ml_client.data.create_or_update(data) - - return data_asset.id, data_asset.path - - @property - def scope(self) -> Dict[str, str]: - return { - "subscription_id": self._config3.subscription_id, - "resource_group_name": self._config3.resource_group_name, - "project_name": self._config3.project_name, - } - - -__all__: List[str] = [ - "AIProjectClient", -] # Add all objects you want publicly available to users at this package level +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/_types.py b/sdk/ai/azure-ai-projects/azure/ai/projects/_types.py deleted file mode 100644 index ff7e15ec008a..000000000000 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/_types.py +++ /dev/null @@ -1,22 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import List, TYPE_CHECKING, Union - -if TYPE_CHECKING: - from . import models as _models -AgentsApiResponseFormatOption = Union[ - str, - str, - "_models.AgentsApiResponseFormatMode", - "_models.AgentsApiResponseFormat", - "_models.ResponseFormatJsonSchemaType", -] -MessageInputContent = Union[str, List["_models.MessageInputContentBlock"]] -MessageAttachmentToolDefinition = Union["_models.CodeInterpreterToolDefinition", "_models.FileSearchToolDefinition"] -AgentsApiToolChoiceOption = Union[str, str, "_models.AgentsApiToolChoiceOptionMode", "_models.AgentsNamedToolChoice"] diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/agents/__init__.py b/sdk/ai/azure-ai-projects/azure/ai/projects/_utils/__init__.py similarity index 79% rename from sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/agents/__init__.py rename to sdk/ai/azure-ai-projects/azure/ai/projects/_utils/__init__.py index 34fb7e5f7cd8..8026245c2abc 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/agents/__init__.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/_utils/__init__.py @@ -1,13 +1,6 @@ -# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- - -from ._ai_agents_instrumentor import AIAgentsInstrumentor - -__all__ = [ - "AIAgentsInstrumentor", -] diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/_model_base.py b/sdk/ai/azure-ai-projects/azure/ai/projects/_utils/model_base.py similarity index 100% rename from sdk/ai/azure-ai-projects/azure/ai/projects/_model_base.py rename to sdk/ai/azure-ai-projects/azure/ai/projects/_utils/model_base.py diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/_serialization.py b/sdk/ai/azure-ai-projects/azure/ai/projects/_utils/serialization.py similarity index 100% rename from sdk/ai/azure-ai-projects/azure/ai/projects/_serialization.py rename to sdk/ai/azure-ai-projects/azure/ai/projects/_utils/serialization.py diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/_validation.py b/sdk/ai/azure-ai-projects/azure/ai/projects/_validation.py new file mode 100644 index 000000000000..752b2822f9d3 --- /dev/null +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/_validation.py @@ -0,0 +1,50 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import functools + + +def api_version_validation(**kwargs): + params_added_on = kwargs.pop("params_added_on", {}) + method_added_on = kwargs.pop("method_added_on", "") + + def decorator(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + try: + # this assumes the client has an _api_version attribute + client = args[0] + client_api_version = client._config.api_version # pylint: disable=protected-access + except AttributeError: + return func(*args, **kwargs) + + if method_added_on > client_api_version: + raise ValueError( + f"'{func.__name__}' is not available in API version " + f"{client_api_version}. Pass service API version {method_added_on} or newer to your client." + ) + + unsupported = { + parameter: api_version + for api_version, parameters in params_added_on.items() + for parameter in parameters + if parameter in kwargs and api_version > client_api_version + } + if unsupported: + raise ValueError( + "".join( + [ + f"'{param}' is not available in API version {client_api_version}. " + f"Use service API version {version} or newer.\n" + for param, version in unsupported.items() + ] + ) + ) + return func(*args, **kwargs) + + return wrapper + + return decorator diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/_vendor.py b/sdk/ai/azure-ai-projects/azure/ai/projects/_vendor.py deleted file mode 100644 index e6f010934827..000000000000 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/_vendor.py +++ /dev/null @@ -1,50 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -import json -from typing import Any, Dict, IO, List, Mapping, Optional, Tuple, Union - -from ._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]] - -FileType = Union[ - # file (or bytes) - FileContent, - # (filename, file (or bytes)) - Tuple[Optional[str], FileContent], - # (filename, file (or bytes), content_type) - Tuple[Optional[str], FileContent, Optional[str]], -] - - -def serialize_multipart_data_entry(data_entry: Any) -> Any: - if isinstance(data_entry, (list, tuple, dict, Model)): - return json.dumps(data_entry, cls=SdkJSONEncoder, exclude_readonly=True) - return data_entry - - -def prepare_multipart_form_data( - body: Mapping[str, Any], multipart_fields: List[str], data_fields: List[str] -) -> Tuple[List[FileType], Dict[str, Any]]: - files: List[FileType] = [] - data: Dict[str, Any] = {} - for multipart_field in multipart_fields: - multipart_entry = body.get(multipart_field) - if isinstance(multipart_entry, list): - files.extend([(multipart_field, e) for e in multipart_entry]) - elif multipart_entry: - files.append((multipart_field, multipart_entry)) - - for data_field in data_fields: - data_entry = body.get(data_field) - if data_entry: - data[data_field] = serialize_multipart_data_entry(data_entry) - - return files, data diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/_version.py b/sdk/ai/azure-ai-projects/azure/ai/projects/_version.py index 9ab0a006e0d0..be71c81bd282 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/_version.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.0.0b10" +VERSION = "1.0.0b1" diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/_client.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/_client.py index 34abeedc6ed0..f43f7427592e 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/_client.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/_client.py @@ -1,4 +1,3 @@ -# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -15,63 +14,59 @@ from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest -from .._serialization import Deserializer, Serializer +from .._utils.serialization import Deserializer, Serializer from ._configuration import AIProjectClientConfiguration -from .operations import AgentsOperations, ConnectionsOperations, EvaluationsOperations, TelemetryOperations +from .operations import ( + ConnectionsOperations, + DatasetsOperations, + DeploymentsOperations, + EvaluationsOperations, + IndexesOperations, + RedTeamsOperations, + ServicePatternsOperations, +) if TYPE_CHECKING: from azure.core.credentials_async import AsyncTokenCredential -class AIProjectClient: +class AIProjectClient: # pylint: disable=too-many-instance-attributes """AIProjectClient. - :ivar agents: AgentsOperations operations - :vartype agents: azure.ai.projects.aio.operations.AgentsOperations + :ivar service_patterns: ServicePatternsOperations operations + :vartype service_patterns: azure.ai.projects.aio.operations.ServicePatternsOperations :ivar connections: ConnectionsOperations operations :vartype connections: azure.ai.projects.aio.operations.ConnectionsOperations - :ivar telemetry: TelemetryOperations operations - :vartype telemetry: azure.ai.projects.aio.operations.TelemetryOperations :ivar evaluations: EvaluationsOperations operations :vartype evaluations: azure.ai.projects.aio.operations.EvaluationsOperations - :param endpoint: The Azure AI Foundry project endpoint, in the form - ``https://.api.azureml.ms`` or - ``https://..api.azureml.ms``, where is the - Azure region where the project is deployed (e.g. westus) and is the GUID of - the Enterprise private link. Required. + :ivar datasets: DatasetsOperations operations + :vartype datasets: azure.ai.projects.aio.operations.DatasetsOperations + :ivar indexes: IndexesOperations operations + :vartype indexes: azure.ai.projects.aio.operations.IndexesOperations + :ivar deployments: DeploymentsOperations operations + :vartype deployments: azure.ai.projects.aio.operations.DeploymentsOperations + :ivar red_teams: RedTeamsOperations operations + :vartype red_teams: azure.ai.projects.aio.operations.RedTeamsOperations + :param endpoint: Project endpoint. In the form + "https://.services.ai.azure.com/api/projects/_project" + if your Foundry Hub has only one Project, or to use the default Project in your Hub. Or in the + form + "https://.services.ai.azure.com/api/projects/" + if you want to explicitly + specify the Foundry Project name. Required. :type endpoint: str - :param subscription_id: The Azure subscription ID. Required. - :type subscription_id: str - :param resource_group_name: The name of the Azure Resource Group. Required. - :type resource_group_name: str - :param project_name: The Azure AI Foundry project name. Required. - :type project_name: str :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :keyword api_version: The API version to use for this operation. Default value is - "2024-07-01-preview". Note that overriding this default value may result in unsupported + "2025-05-15-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, - endpoint: str, - subscription_id: str, - resource_group_name: str, - project_name: str, - credential: "AsyncTokenCredential", - **kwargs: Any - ) -> None: - _endpoint = "{endpoint}/agents/v1.0/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.MachineLearningServices/workspaces/{projectName}" - self._config = AIProjectClientConfiguration( - endpoint=endpoint, - subscription_id=subscription_id, - resource_group_name=resource_group_name, - project_name=project_name, - credential=credential, - **kwargs - ) + def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + _endpoint = "{endpoint}" + self._config = AIProjectClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -94,10 +89,15 @@ def __init__( self._serialize = Serializer() self._deserialize = Deserializer() self._serialize.client_side_validation = False - self.agents = AgentsOperations(self._client, self._config, self._serialize, self._deserialize) + self.service_patterns = ServicePatternsOperations( + self._client, self._config, self._serialize, self._deserialize + ) self.connections = ConnectionsOperations(self._client, self._config, self._serialize, self._deserialize) - self.telemetry = TelemetryOperations(self._client, self._config, self._serialize, self._deserialize) self.evaluations = EvaluationsOperations(self._client, self._config, self._serialize, self._deserialize) + self.datasets = DatasetsOperations(self._client, self._config, self._serialize, self._deserialize) + self.indexes = IndexesOperations(self._client, self._config, self._serialize, self._deserialize) + self.deployments = DeploymentsOperations(self._client, self._config, self._serialize, self._deserialize) + self.red_teams = RedTeamsOperations(self._client, self._config, self._serialize, self._deserialize) def send_request( self, request: HttpRequest, *, stream: bool = False, **kwargs: Any @@ -121,12 +121,7 @@ def send_request( request_copy = deepcopy(request) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/_configuration.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/_configuration.py index 48b480a960b7..51608a5856bb 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/_configuration.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/_configuration.py @@ -22,55 +22,34 @@ class AIProjectClientConfiguration: # pylint: disable=too-many-instance-attribu Note that all parameters used to create this instance are saved as instance attributes. - :param endpoint: The Azure AI Foundry project endpoint, in the form - ``https://.api.azureml.ms`` or - ``https://..api.azureml.ms``, where is the - Azure region where the project is deployed (e.g. westus) and is the GUID of - the Enterprise private link. Required. + :param endpoint: Project endpoint. In the form + "https://.services.ai.azure.com/api/projects/_project" + if your Foundry Hub has only one Project, or to use the default Project in your Hub. Or in the + form + "https://.services.ai.azure.com/api/projects/" + if you want to explicitly + specify the Foundry Project name. Required. :type endpoint: str - :param subscription_id: The Azure subscription ID. Required. - :type subscription_id: str - :param resource_group_name: The name of the Azure Resource Group. Required. - :type resource_group_name: str - :param project_name: The Azure AI Foundry project name. Required. - :type project_name: str :param credential: Credential used to authenticate requests to the service. Required. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :keyword api_version: The API version to use for this operation. Default value is - "2024-07-01-preview". Note that overriding this default value may result in unsupported + "2025-05-15-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( - self, - endpoint: str, - subscription_id: str, - resource_group_name: str, - project_name: str, - credential: "AsyncTokenCredential", - **kwargs: Any - ) -> None: - api_version: str = kwargs.pop("api_version", "2024-07-01-preview") + def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2025-05-15-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - if resource_group_name is None: - raise ValueError("Parameter 'resource_group_name' must not be None.") - if project_name is None: - raise ValueError("Parameter 'project_name' must not be None.") if credential is None: raise ValueError("Parameter 'credential' must not be None.") self.endpoint = endpoint - self.subscription_id = subscription_id - self.resource_group_name = resource_group_name - self.project_name = project_name self.credential = credential self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) + self.credential_scopes = kwargs.pop("credential_scopes", ["https://cognitiveservices.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "ai-projects/{}".format(VERSION)) self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/_patch.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/_patch.py index 6e36aa81fed5..8bcb627aa475 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/_patch.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/_patch.py @@ -1,315 +1,15 @@ -# pylint: disable=line-too-long,useless-suppression -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -import uuid -from os import PathLike -from pathlib import Path -from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union -from typing_extensions import Self +from typing import List -from azure.core import AsyncPipelineClient -from azure.core.pipeline import policies - -from .._serialization import Deserializer, Serializer -from ._client import AIProjectClient as ClientGenerated -from ._configuration import AIProjectClientConfiguration -from .operations import ( - AgentsOperations, - ConnectionsOperations, - EvaluationsOperations, - TelemetryOperations, -) -from .operations._patch import _SyncCredentialWrapper, InferenceOperations - -if TYPE_CHECKING: - from azure.core.credentials import AccessToken - from azure.core.credentials_async import AsyncTokenCredential - - -class AIProjectClient( - ClientGenerated -): # pylint: disable=client-accepts-api-version-keyword,too-many-instance-attributes - def __init__( # pylint: disable=super-init-not-called,too-many-statements - self, - endpoint: str, - subscription_id: str, - resource_group_name: str, - project_name: str, - credential: "AsyncTokenCredential", - **kwargs: Any, - ) -> None: - # TODO: Validate input formats with regex match (e.g. subscription ID) - if not endpoint: - raise ValueError("endpoint is required") - if not subscription_id: - raise ValueError("subscription_id ID is required") - if not resource_group_name: - raise ValueError("resource_group_name is required") - if not project_name: - raise ValueError("project_name is required") - if not credential: - raise ValueError("credential is required") - if "api_version" in kwargs: - raise ValueError("No support for overriding the API version") - if "credential_scopes" in kwargs: - raise ValueError("No support for overriding the credential scopes") - - kwargs0 = kwargs.copy() - kwargs1 = kwargs.copy() - kwargs2 = kwargs.copy() - kwargs3 = kwargs.copy() - - self._user_agent: Optional[str] = kwargs.get("user_agent", None) - - # For getting AppInsights connection string from the AppInsights resource. - # The AppInsights resource URL is not known at this point. We need to get it from the - # AzureML "Workspace - Get" REST API call. It will have the form: - # https://management.azure.com/subscriptions/{appinsights_subscription_id}/resourceGroups/{appinsights_resource_group_name}/providers/microsoft.insights/components/{appinsights_resource_name} # pylint: disable=line-too-long - _endpoint0 = "https://management.azure.com" # pylint: disable=line-too-long - self._config0: AIProjectClientConfiguration = AIProjectClientConfiguration( - endpoint=endpoint, - subscription_id=subscription_id, - resource_group_name=resource_group_name, - project_name=project_name, - credential=credential, - api_version="2020-02-02", - credential_scopes=["https://management.azure.com/.default"], - **kwargs0, - ) - - _policies0 = kwargs0.pop("policies", None) - if _policies0 is None: - _policies0 = [ - policies.RequestIdPolicy(**kwargs0), - self._config0.headers_policy, - self._config0.user_agent_policy, - self._config0.proxy_policy, - policies.ContentDecodePolicy(**kwargs0), - self._config0.redirect_policy, - self._config0.retry_policy, - self._config0.authentication_policy, - self._config0.custom_hook_policy, - self._config0.logging_policy, - policies.DistributedTracingPolicy(**kwargs0), - (policies.SensitiveHeaderCleanupPolicy(**kwargs0) if self._config0.redirect_policy else None), - self._config0.http_logging_policy, - ] - self._client0: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint0, policies=_policies0, **kwargs0) - - # For Endpoints operations (enumerating connections, getting SAS tokens) - _endpoint1 = f"https://management.azure.com/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}/providers/Microsoft.MachineLearningServices/workspaces/{project_name}" - self._config1: AIProjectClientConfiguration = AIProjectClientConfiguration( - endpoint=endpoint, - subscription_id=subscription_id, - resource_group_name=resource_group_name, - project_name=project_name, - credential=credential, - api_version="2024-07-01-preview", - credential_scopes=["https://management.azure.com/.default"], - **kwargs1, - ) - _policies1 = kwargs1.pop("policies", None) - if _policies1 is None: - _policies1 = [ - policies.RequestIdPolicy(**kwargs1), - self._config1.headers_policy, - self._config1.user_agent_policy, - self._config1.proxy_policy, - policies.ContentDecodePolicy(**kwargs1), - self._config1.redirect_policy, - self._config1.retry_policy, - self._config1.authentication_policy, - self._config1.custom_hook_policy, - self._config1.logging_policy, - policies.DistributedTracingPolicy(**kwargs1), - (policies.SensitiveHeaderCleanupPolicy(**kwargs1) if self._config1.redirect_policy else None), - self._config1.http_logging_policy, - ] - self._client1: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint1, policies=_policies1, **kwargs1) - - # For Agents operations - _endpoint2 = f"{endpoint}/agents/v1.0/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}/providers/Microsoft.MachineLearningServices/workspaces/{project_name}" # pylint: disable=line-too-long - self._config2: AIProjectClientConfiguration = AIProjectClientConfiguration( - endpoint=endpoint, - subscription_id=subscription_id, - resource_group_name=resource_group_name, - project_name=project_name, - credential=credential, - api_version="2024-12-01-preview", - credential_scopes=["https://ml.azure.com/.default"], - **kwargs2, - ) - _policies2 = kwargs2.pop("policies", None) - if _policies2 is None: - _policies2 = [ - policies.RequestIdPolicy(**kwargs2), - self._config2.headers_policy, - self._config2.user_agent_policy, - self._config2.proxy_policy, - policies.ContentDecodePolicy(**kwargs2), - self._config2.redirect_policy, - self._config2.retry_policy, - self._config2.authentication_policy, - self._config2.custom_hook_policy, - self._config2.logging_policy, - policies.DistributedTracingPolicy(**kwargs2), - (policies.SensitiveHeaderCleanupPolicy(**kwargs2) if self._config2.redirect_policy else None), - self._config2.http_logging_policy, - ] - self._client2: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint2, policies=_policies2, **kwargs2) - - # For Cloud Evaluations operations - # cSpell:disable-next-line - _endpoint3 = f"{endpoint}/raisvc/v1.0/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}/providers/Microsoft.MachineLearningServices/workspaces/{project_name}" # pylint: disable=line-too-long - self._config3: AIProjectClientConfiguration = AIProjectClientConfiguration( - endpoint=endpoint, - subscription_id=subscription_id, - resource_group_name=resource_group_name, - project_name=project_name, - credential=credential, - api_version="2024-07-01-preview", # TODO: Update me - credential_scopes=["https://ml.azure.com/.default"], # TODO: Update once service changes are ready - **kwargs3, - ) - _policies3 = kwargs3.pop("policies", None) - if _policies3 is None: - _policies3 = [ - policies.RequestIdPolicy(**kwargs3), - self._config3.headers_policy, - self._config3.user_agent_policy, - self._config3.proxy_policy, - policies.ContentDecodePolicy(**kwargs3), - self._config3.redirect_policy, - self._config3.retry_policy, - self._config3.authentication_policy, - self._config3.custom_hook_policy, - self._config3.logging_policy, - policies.DistributedTracingPolicy(**kwargs3), - (policies.SensitiveHeaderCleanupPolicy(**kwargs3) if self._config3.redirect_policy else None), - self._config3.http_logging_policy, - ] - self._client3: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint3, policies=_policies3, **kwargs3) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - self.telemetry = TelemetryOperations( - self._client0, - self._config0, - self._serialize, - self._deserialize, - outer_instance=self, - ) - self._credential = credential - self.connections = ConnectionsOperations(self._client1, self._config1, self._serialize, self._deserialize) - self.agents = AgentsOperations(self._client2, self._config2, self._serialize, self._deserialize) - self.evaluations = EvaluationsOperations(self._client3, self._config3, self._serialize, self._deserialize) - self.inference = InferenceOperations(self) - - async def close(self) -> None: - await self._client0.close() - await self._client1.close() - await self._client2.close() - await self._client3.close() - - async def __aenter__(self) -> Self: - await self._client0.__aenter__() - await self._client1.__aenter__() - await self._client2.__aenter__() - await self._client3.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._client0.__aexit__(*exc_details) - await self._client1.__aexit__(*exc_details) - await self._client2.__aexit__(*exc_details) - await self._client3.__aexit__(*exc_details) - - @classmethod - def from_connection_string(cls, conn_str: str, credential: "AsyncTokenCredential", **kwargs) -> Self: - """ - Create an asynchronous AIProjectClient from a connection string. - - :param str conn_str: The connection string, copied from your AI Foundry project. - :param AsyncTokenCredential credential: Credential used to authenticate requests to the service. - :return: An AIProjectClient instance. - :rtype: AIProjectClient - """ - if not conn_str: - raise ValueError("Connection string is required") - parts = conn_str.split(";") - if len(parts) != 4: - raise ValueError("Invalid connection string format") - endpoint = "https://" + parts[0] - subscription_id = parts[1] - resource_group_name = parts[2] - project_name = parts[3] - return cls( - endpoint, - subscription_id, - resource_group_name, - project_name, - credential, - **kwargs, - ) - - def upload_file(self, file_path: Union[Path, str, PathLike]) -> Tuple[str, str]: - """Upload a file to the Azure AI Foundry project. - This method required *azure-ai-ml* to be installed. - - :param file_path: The path to the file to upload. - :type file_path: Union[str, Path, PathLike] - :return: The tuple, containing asset id and asset URI of uploaded file. - :rtype: Tuple[str, str] - """ - try: - from azure.ai.ml import MLClient # type: ignore - from azure.ai.ml.constants import AssetTypes # type: ignore - from azure.ai.ml.entities import Data # type: ignore - except ImportError as e: - raise ImportError( - "azure-ai-ml must be installed to use this function. Please install it using `pip install azure-ai-ml`" - ) from e - - data = Data( - path=str(file_path), - type=AssetTypes.URI_FILE, - name=str(uuid.uuid4()), # generating random name - is_anonymous=True, - version="1", - ) - # We have to wrap async method get_token of - - ml_client = MLClient( - _SyncCredentialWrapper(self._config3.credential), - self._config3.subscription_id, - self._config3.resource_group_name, - self._config3.project_name, - ) - - data_asset = ml_client.data.create_or_update(data) - - return data_asset.id, data_asset.path - - @property - def scope(self) -> Dict[str, str]: - return { - "subscription_id": self._config3.subscription_id, - "resource_group_name": self._config3.resource_group_name, - "project_name": self._config3.project_name, - } - - -__all__: List[str] = [ - "AIProjectClient", -] # Add all objects you want publicly available to users at this package level +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/__init__.py b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/__init__.py index 64c4031e2bb6..c8b497b4854b 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/__init__.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/aio/operations/__init__.py @@ -12,20 +12,26 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._operations import AgentsOperations # type: ignore +from ._operations import ServicePatternsOperations # type: ignore from ._operations import ConnectionsOperations # type: ignore -from ._operations import TelemetryOperations # type: ignore from ._operations import EvaluationsOperations # type: ignore +from ._operations import DatasetsOperations # type: ignore +from ._operations import IndexesOperations # type: ignore +from ._operations import DeploymentsOperations # type: ignore +from ._operations import RedTeamsOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AgentsOperations", + "ServicePatternsOperations", "ConnectionsOperations", - "TelemetryOperations", "EvaluationsOperations", + "DatasetsOperations", + "IndexesOperations", + "DeploymentsOperations", + "RedTeamsOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() 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 5a567bf38b88..dfaf8d0898b1 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 @@ -1,4 +1,4 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -9,20 +9,7 @@ from collections.abc import MutableMapping from io import IOBase import json -from typing import ( - Any, - AsyncIterable, - AsyncIterator, - Callable, - Dict, - IO, - List, - Optional, - TYPE_CHECKING, - TypeVar, - Union, - overload, -) +from typing import Any, AsyncIterable, Callable, Dict, IO, List, Optional, TypeVar, Union, overload import urllib.parse from azure.core import AsyncPipelineClient @@ -43,84 +30,51 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ... import _model_base, models as _models -from ..._model_base import SdkJSONEncoder, _deserialize -from ..._serialization import Deserializer, Serializer -from ..._vendor import prepare_multipart_form_data +from ... import models as _models +from ..._utils.model_base import SdkJSONEncoder, _deserialize +from ..._utils.serialization import Deserializer, Serializer +from ..._validation import api_version_validation from ...operations._operations import ( - build_agents_cancel_run_request, - build_agents_cancel_vector_store_file_batch_request, - build_agents_create_agent_request, - build_agents_create_message_request, - build_agents_create_run_request, - build_agents_create_thread_and_run_request, - build_agents_create_thread_request, - build_agents_create_vector_store_file_batch_request, - build_agents_create_vector_store_file_request, - build_agents_create_vector_store_request, - build_agents_delete_agent_request, - build_agents_delete_file_request, - build_agents_delete_thread_request, - build_agents_delete_vector_store_file_request, - build_agents_delete_vector_store_request, - build_agents_get_agent_request, - build_agents_get_file_content_request, - build_agents_get_file_request, - build_agents_get_message_request, - build_agents_get_run_request, - build_agents_get_run_step_request, - build_agents_get_thread_request, - build_agents_get_vector_store_file_batch_request, - build_agents_get_vector_store_file_request, - build_agents_get_vector_store_request, - build_agents_list_agents_request, - build_agents_list_files_request, - build_agents_list_messages_request, - build_agents_list_run_steps_request, - build_agents_list_runs_request, - build_agents_list_threads_request, - build_agents_list_vector_store_file_batch_files_request, - build_agents_list_vector_store_files_request, - build_agents_list_vector_stores_request, - build_agents_modify_vector_store_request, - build_agents_submit_tool_outputs_to_run_request, - build_agents_update_agent_request, - build_agents_update_message_request, - build_agents_update_run_request, - build_agents_update_thread_request, - build_agents_upload_file_request, - build_connections_get_connection_request, - build_connections_get_connection_with_secrets_request, - build_connections_get_workspace_request, - build_connections_list_connections_request, - build_evaluations_create_or_replace_schedule_request, - build_evaluations_create_request, - build_evaluations_disable_schedule_request, + build_connections_get_request, + build_connections_get_with_credentials_request, + build_connections_list_request, + build_datasets_create_or_update_request, + build_datasets_delete_request, + build_datasets_get_credentials_request, + build_datasets_get_request, + build_datasets_list_request, + build_datasets_list_versions_request, + build_datasets_pending_upload_request, + build_deployments_get_request, + build_deployments_list_request, + build_evaluations_create_agent_evaluation_request, + build_evaluations_create_run_request, build_evaluations_get_request, - build_evaluations_get_schedule_request, build_evaluations_list_request, - build_evaluations_list_schedule_request, - build_evaluations_update_request, - build_telemetry_get_app_insights_request, + build_indexes_create_or_update_request, + build_indexes_delete_request, + build_indexes_get_request, + build_indexes_list_request, + build_indexes_list_versions_request, + build_red_teams_create_run_request, + build_red_teams_get_request, + build_red_teams_list_request, ) from .._configuration import AIProjectClientConfiguration -if TYPE_CHECKING: - from ... import _types -JSON = MutableMapping[str, Any] -_Unset: Any = object() T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] -class AgentsOperations: # pylint: disable=too-many-public-methods +class ServicePatternsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.ai.projects.aio.AIProjectClient`'s - :attr:`agents` attribute. + :attr:`service_patterns` attribute. """ def __init__(self, *args, **kwargs) -> None: @@ -130,160 +84,32 @@ 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 create_agent( - self, - *, - model: str, - content_type: str = "application/json", - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.ToolResources] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.Agent: - """Creates a new agent. - - :keyword model: The ID of the model to use. Required. - :paramtype model: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword name: The name of the new agent. Default value is None. - :paramtype name: str - :keyword description: The description of the new agent. Default value is None. - :paramtype description: str - :keyword instructions: The system instructions for the new agent to use. Default value is None. - :paramtype instructions: str - :keyword tools: The collection of tools to enable for the new agent. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword tool_resources: A set of resources that are used by the agent's tools. The resources - are specific to the type of tool. For example, the ``code_interpreter`` - tool requires a list of file IDs, while the ``file_search`` tool requires a list of vector - store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output more random, - while lower values like 0.2 will make it more focused and deterministic. Default value is - None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword response_format: The response format of the tool calls used by this agent. Is one of - the following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat, ResponseFormatJsonSchemaType Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat or - ~azure.ai.projects.models.ResponseFormatJsonSchemaType - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_agent(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Agent: - """Creates a new agent. - :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: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ +class ConnectionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - @overload - async def create_agent( - self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Agent: - """Creates a new agent. + Instead, you should access the following operations through + :class:`~azure.ai.projects.aio.AIProjectClient`'s + :attr:`connections` attribute. + """ - :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: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :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") @distributed_trace_async - async def create_agent( - self, - body: Union[JSON, IO[bytes]] = _Unset, - *, - model: str = _Unset, - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.ToolResources] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.Agent: - """Creates a new agent. - - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword model: The ID of the model to use. Required. - :paramtype model: str - :keyword name: The name of the new agent. Default value is None. - :paramtype name: str - :keyword description: The description of the new agent. Default value is None. - :paramtype description: str - :keyword instructions: The system instructions for the new agent to use. Default value is None. - :paramtype instructions: str - :keyword tools: The collection of tools to enable for the new agent. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword tool_resources: A set of resources that are used by the agent's tools. The resources - are specific to the type of tool. For example, the ``code_interpreter`` - tool requires a list of file IDs, while the ``file_search`` tool requires a list of vector - store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output more random, - while lower values like 0.2 will make it more focused and deterministic. Default value is - None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword response_format: The response format of the tool calls used by this agent. Is one of - the following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat, ResponseFormatJsonSchemaType Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat or - ~azure.ai.projects.models.ResponseFormatJsonSchemaType - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent + async def _get(self, name: str, **kwargs: Any) -> _models.Connection: + """Get a connection by name, without populating connection credentials. + + :param name: The name of the resource. 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 = { @@ -294,49 +120,19 @@ async def create_agent( } 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.Agent] = kwargs.pop("cls", None) - - if body is _Unset: - if model is _Unset: - raise TypeError("missing required argument: model") - body = { - "description": description, - "instructions": instructions, - "metadata": metadata, - "model": model, - "name": name, - "response_format": response_format, - "temperature": temperature, - "tool_resources": tool_resources, - "tools": tools, - "top_p": top_p, - } - 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.Connection] = kwargs.pop("cls", None) - _request = build_agents_create_agent_request( - content_type=content_type, + _request = build_connections_get_request( + name=name, 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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -356,47 +152,29 @@ async def create_agent( 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() else: - deserialized = _deserialize(_models.Agent, response.json()) + deserialized = _deserialize(_models.Connection, 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 list_agents( - self, - *, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any - ) -> _models.OpenAIPageableListOfAgent: - """Gets a list of agents that were previously created. - - :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.ListSortOrder - :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: OpenAIPageableListOfAgent. The OpenAIPageableListOfAgent is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIPageableListOfAgent + async def _get_with_credentials(self, name: str, **kwargs: Any) -> _models.Connection: + """Get a connection by name, with its connection credentials. + + :param name: The name of the resource. 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 = { @@ -410,24 +188,16 @@ async def list_agents( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.OpenAIPageableListOfAgent] = kwargs.pop("cls", None) + cls: ClsType[_models.Connection] = kwargs.pop("cls", None) - _request = build_agents_list_agents_request( - limit=limit, - order=order, - after=after, - before=before, + _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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -447,26 +217,54 @@ async def list_agents( 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() else: - deserialized = _deserialize(_models.OpenAIPageableListOfAgent, response.json()) + deserialized = _deserialize(_models.Connection, 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_agent(self, agent_id: str, **kwargs: Any) -> _models.Agent: - """Retrieves an existing agent. - - :param agent_id: Identifier of the agent. Required. - :type agent_id: str - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent + @distributed_trace + def list( + self, + *, + connection_type: Optional[Union[str, _models.ConnectionType]] = None, + default_connection: Optional[bool] = None, + top: Optional[int] = None, + skip: Optional[int] = None, + **kwargs: Any + ) -> AsyncIterable["_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", and "CustomKeys". 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 + :keyword top: The number of result items to return. Default value is None. + :paramtype top: int + :keyword skip: The number of result items to skip. Default value is None. + :paramtype skip: int + :return: An iterator like instance of Connection + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.Connection] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + maxpagesize = kwargs.pop("maxpagesize", None) + cls: ClsType[List[_models.Connection]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -475,223 +273,102 @@ async def get_agent(self, agent_id: str, **kwargs: Any) -> _models.Agent: } 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.Agent] = kwargs.pop("cls", None) + _request = build_connections_list_request( + connection_type=connection_type, + default_connection=default_connection, + top=top, + skip=skip, + maxpagesize=maxpagesize, + 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_agents_get_agent_request( - agent_id=agent_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _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) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + return _request - response = pipeline_response.http_response + async 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, AsyncList(list_of_elem) - 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) + async def get_next(next_link=None): + _request = prepare_request(next_link) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.Agent, response.json()) + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + 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 deserialized # type: ignore + return pipeline_response - @overload - async def update_agent( - self, - agent_id: str, - *, - content_type: str = "application/json", - model: Optional[str] = None, - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.ToolResources] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.Agent: - """Modifies an existing agent. + return AsyncItemPaged(get_next, extract_data) - :param agent_id: The ID of the agent to modify. Required. - :type agent_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword model: The ID of the model to use. Default value is None. - :paramtype model: str - :keyword name: The modified name for the agent to use. Default value is None. - :paramtype name: str - :keyword description: The modified description for the agent to use. Default value is None. - :paramtype description: str - :keyword instructions: The modified system instructions for the new agent to use. Default value - is None. - :paramtype instructions: str - :keyword tools: The modified collection of tools to enable for the agent. Default value is - None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword tool_resources: A set of resources that are used by the agent's tools. The resources - are specific to the type of tool. For example, - the ``code_interpreter`` tool requires a list of file IDs, while the ``file_search`` tool - requires a list of vector store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output more random, - while lower values like 0.2 will make it more focused and deterministic. Default value is - None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword response_format: The response format of the tool calls used by this agent. Is one of - the following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat, ResponseFormatJsonSchemaType Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat or - ~azure.ai.projects.models.ResponseFormatJsonSchemaType - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - @overload - async def update_agent( - self, agent_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Agent: - """Modifies an existing agent. - - :param agent_id: The ID of the agent to modify. Required. - :type agent_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: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ +class EvaluationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - @overload - async def update_agent( - self, agent_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Agent: - """Modifies an existing agent. - - :param agent_id: The ID of the agent to modify. Required. - :type agent_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: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ + Instead, you should access the following operations through + :class:`~azure.ai.projects.aio.AIProjectClient`'s + :attr:`evaluations` 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 update_agent( - self, - agent_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - model: Optional[str] = None, - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.ToolResources] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.Agent: - """Modifies an existing agent. - - :param agent_id: The ID of the agent to modify. Required. - :type agent_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword model: The ID of the model to use. Default value is None. - :paramtype model: str - :keyword name: The modified name for the agent to use. Default value is None. - :paramtype name: str - :keyword description: The modified description for the agent to use. Default value is None. - :paramtype description: str - :keyword instructions: The modified system instructions for the new agent to use. Default value - is None. - :paramtype instructions: str - :keyword tools: The modified collection of tools to enable for the agent. Default value is - None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword tool_resources: A set of resources that are used by the agent's tools. The resources - are specific to the type of tool. For example, - the ``code_interpreter`` tool requires a list of file IDs, while the ``file_search`` tool - requires a list of vector store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output more random, - while lower values like 0.2 will make it more focused and deterministic. Default value is - None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword response_format: The response format of the tool calls used by this agent. Is one of - the following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat, ResponseFormatJsonSchemaType Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat or - ~azure.ai.projects.models.ResponseFormatJsonSchemaType - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent + @api_version_validation( + method_added_on="2025-05-15-preview", + params_added_on={"2025-05-15-preview": ["api_version", "name", "client_request_id", "accept"]}, + ) + async def get(self, name: str, **kwargs: Any) -> _models.Evaluation: + """Get an evaluation run by name. + + :param name: Identifier of the evaluation. Required. + :type name: str + :return: Evaluation. The Evaluation is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Evaluation :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -702,48 +379,19 @@ async def update_agent( } 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.Agent] = kwargs.pop("cls", None) - - if body is _Unset: - body = { - "description": description, - "instructions": instructions, - "metadata": metadata, - "model": model, - "name": name, - "response_format": response_format, - "temperature": temperature, - "tool_resources": tool_resources, - "tools": tools, - "top_p": top_p, - } - 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.Evaluation] = kwargs.pop("cls", None) - _request = build_agents_update_agent_request( - agent_id=agent_id, - content_type=content_type, + _request = build_evaluations_get_request( + name=name, 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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -763,26 +411,47 @@ async def update_agent( 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() else: - deserialized = _deserialize(_models.Agent, response.json()) + deserialized = _deserialize(_models.Evaluation, 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 delete_agent(self, agent_id: str, **kwargs: Any) -> _models.AgentDeletionStatus: - """Deletes an agent. - - :param agent_id: Identifier of the agent. Required. - :type agent_id: str - :return: AgentDeletionStatus. The AgentDeletionStatus is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentDeletionStatus - :raises ~azure.core.exceptions.HttpResponseError: - """ + @distributed_trace + @api_version_validation( + method_added_on="2025-05-15-preview", + params_added_on={ + "2025-05-15-preview": ["api_version", "top", "skip", "maxpagesize", "client_request_id", "accept"] + }, + ) + def list( + self, *, top: Optional[int] = None, skip: Optional[int] = None, **kwargs: Any + ) -> AsyncIterable["_models.Evaluation"]: + """List evaluation runs. + + :keyword top: The number of result items to return. Default value is None. + :paramtype top: int + :keyword skip: The number of result items to skip. Default value is None. + :paramtype skip: int + :return: An iterator like instance of Evaluation + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.Evaluation] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + maxpagesize = kwargs.pop("maxpagesize", None) + cls: ClsType[List[_models.Evaluation]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -791,149 +460,133 @@ async def delete_agent(self, agent_id: str, **kwargs: Any) -> _models.AgentDelet } 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.AgentDeletionStatus] = kwargs.pop("cls", None) + _request = build_evaluations_list_request( + top=top, + skip=skip, + maxpagesize=maxpagesize, + 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_agents_delete_agent_request( - agent_id=agent_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _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) - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + return _request - response = pipeline_response.http_response + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.Evaluation], deserialized.get("value", [])) + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) - 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) + async def get_next(next_link=None): + _request = prepare_request(next_link) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.AgentDeletionStatus, response.json()) + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + 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 deserialized # type: ignore + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) @overload - async def create_thread( - self, - *, - content_type: str = "application/json", - messages: Optional[List[_models.ThreadMessageOptions]] = None, - tool_resources: Optional[_models.ToolResources] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.AgentThread: - """Creates a new thread. Threads contain messages and can be run by agents. + async def create_run( + self, evaluation: _models.Evaluation, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Evaluation: + """Creates an evaluation run. + :param evaluation: Evaluation to be run. Required. + :type evaluation: ~azure.ai.projects.models.Evaluation :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword messages: The initial messages to associate with the new thread. Default value is - None. - :paramtype messages: list[~azure.ai.projects.models.ThreadMessageOptions] - :keyword tool_resources: A set of resources that are made available to the agent's tools in - this thread. The resources are specific to the - type of tool. For example, the ``code_interpreter`` tool requires a list of file IDs, while - the ``file_search`` tool requires - a list of vector store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: AgentThread. The AgentThread is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentThread + :return: Evaluation. The Evaluation is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Evaluation :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_thread( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AgentThread: - """Creates a new thread. Threads contain messages and can be run by agents. + async def create_run( + self, evaluation: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Evaluation: + """Creates an evaluation run. - :param body: Required. - :type body: JSON + :param evaluation: Evaluation to be run. Required. + :type evaluation: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: AgentThread. The AgentThread is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentThread + :return: Evaluation. The Evaluation is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Evaluation :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_thread( - self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AgentThread: - """Creates a new thread. Threads contain messages and can be run by agents. + async def create_run( + self, evaluation: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Evaluation: + """Creates an evaluation run. - :param body: Required. - :type body: IO[bytes] + :param evaluation: Evaluation to be run. Required. + :type evaluation: 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: AgentThread. The AgentThread is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentThread + :return: Evaluation. The Evaluation is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Evaluation :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def create_thread( - self, - body: Union[JSON, IO[bytes]] = _Unset, - *, - messages: Optional[List[_models.ThreadMessageOptions]] = None, - tool_resources: Optional[_models.ToolResources] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.AgentThread: - """Creates a new thread. Threads contain messages and can be run by agents. + @api_version_validation( + method_added_on="2025-05-15-preview", + params_added_on={"2025-05-15-preview": ["api_version", "content_type", "accept"]}, + ) + async def create_run( + self, evaluation: Union[_models.Evaluation, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Evaluation: + """Creates an evaluation run. - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword messages: The initial messages to associate with the new thread. Default value is - None. - :paramtype messages: list[~azure.ai.projects.models.ThreadMessageOptions] - :keyword tool_resources: A set of resources that are made available to the agent's tools in - this thread. The resources are specific to the - type of tool. For example, the ``code_interpreter`` tool requires a list of file IDs, while - the ``file_search`` tool requires - a list of vector store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: AgentThread. The AgentThread is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentThread + :param evaluation: Evaluation to be run. Is one of the following types: Evaluation, JSON, + IO[bytes] Required. + :type evaluation: ~azure.ai.projects.models.Evaluation or JSON or IO[bytes] + :return: Evaluation. The Evaluation is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Evaluation :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -948,19 +601,16 @@ async def create_thread( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AgentThread] = kwargs.pop("cls", None) + cls: ClsType[_models.Evaluation] = kwargs.pop("cls", None) - if body is _Unset: - body = {"messages": messages, "metadata": metadata, "tool_resources": tool_resources} - 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(evaluation, (IOBase, bytes)): + _content = evaluation else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(evaluation, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_agents_create_thread_request( + _request = build_evaluations_create_run_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -968,77 +618,7 @@ async def create_thread( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.AgentThread, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_thread(self, thread_id: str, **kwargs: Any) -> _models.AgentThread: - """Gets information about an existing thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :return: AgentThread. The AgentThread is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentThread - :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.AgentThread] = kwargs.pop("cls", None) - - _request = build_agents_get_thread_request( - thread_id=thread_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -1049,7 +629,7 @@ async def get_thread(self, thread_id: str, **kwargs: Any) -> _models.AgentThread 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 @@ -1061,7 +641,7 @@ async def get_thread(self, thread_id: str, **kwargs: Any) -> _models.AgentThread if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.AgentThread, response.json()) + deserialized = _deserialize(_models.Evaluation, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -1069,103 +649,68 @@ async def get_thread(self, thread_id: str, **kwargs: Any) -> _models.AgentThread return deserialized # type: ignore @overload - async def update_thread( - self, - thread_id: str, - *, - content_type: str = "application/json", - tool_resources: Optional[_models.ToolResources] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.AgentThread: - """Modifies an existing thread. + async def create_agent_evaluation( + self, evaluation: _models.AgentEvaluationRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AgentEvaluation: + """Creates an agent evaluation run. - :param thread_id: The ID of the thread to modify. Required. - :type thread_id: str + :param evaluation: Agent evaluation to be run. Required. + :type evaluation: ~azure.ai.projects.models.AgentEvaluationRequest :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword tool_resources: A set of resources that are made available to the agent's tools in - this thread. The resources are specific to the - type of tool. For example, the ``code_interpreter`` tool requires a list of file IDs, while - the ``file_search`` tool requires - a list of vector store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: AgentThread. The AgentThread is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentThread + :return: AgentEvaluation. The AgentEvaluation is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentEvaluation :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def update_thread( - self, thread_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AgentThread: - """Modifies an existing thread. - - :param thread_id: The ID of the thread to modify. Required. - :type thread_id: str - :param body: Required. - :type body: JSON + async def create_agent_evaluation( + self, evaluation: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AgentEvaluation: + """Creates an agent evaluation run. + + :param evaluation: Agent evaluation to be run. Required. + :type evaluation: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: AgentThread. The AgentThread is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentThread + :return: AgentEvaluation. The AgentEvaluation is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentEvaluation :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def update_thread( - self, thread_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AgentThread: - """Modifies an existing thread. - - :param thread_id: The ID of the thread to modify. Required. - :type thread_id: str - :param body: Required. - :type body: IO[bytes] + async def create_agent_evaluation( + self, evaluation: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AgentEvaluation: + """Creates an agent evaluation run. + + :param evaluation: Agent evaluation to be run. Required. + :type evaluation: 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: AgentThread. The AgentThread is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentThread + :return: AgentEvaluation. The AgentEvaluation is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentEvaluation :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def update_thread( - self, - thread_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - tool_resources: Optional[_models.ToolResources] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.AgentThread: - """Modifies an existing thread. - - :param thread_id: The ID of the thread to modify. Required. - :type thread_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword tool_resources: A set of resources that are made available to the agent's tools in - this thread. The resources are specific to the - type of tool. For example, the ``code_interpreter`` tool requires a list of file IDs, while - the ``file_search`` tool requires - a list of vector store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: AgentThread. The AgentThread is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentThread + @api_version_validation( + method_added_on="2025-05-15-preview", + params_added_on={"2025-05-15-preview": ["api_version", "content_type", "accept"]}, + ) + async def create_agent_evaluation( + self, evaluation: Union[_models.AgentEvaluationRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.AgentEvaluation: + """Creates an agent evaluation run. + + :param evaluation: Agent evaluation to be run. Is one of the following types: + AgentEvaluationRequest, JSON, IO[bytes] Required. + :type evaluation: ~azure.ai.projects.models.AgentEvaluationRequest or JSON or IO[bytes] + :return: AgentEvaluation. The AgentEvaluation is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentEvaluation :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1180,20 +725,16 @@ async def update_thread( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.AgentThread] = kwargs.pop("cls", None) + cls: ClsType[_models.AgentEvaluation] = kwargs.pop("cls", None) - if body is _Unset: - body = {"metadata": metadata, "tool_resources": tool_resources} - 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(evaluation, (IOBase, bytes)): + _content = evaluation else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(evaluation, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_agents_update_thread_request( - thread_id=thread_id, + _request = build_evaluations_create_agent_evaluation_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -1201,12 +742,7 @@ async def update_thread( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -1217,7 +753,7 @@ async def update_thread( 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 @@ -1229,23 +765,51 @@ async def update_thread( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.AgentThread, response.json()) + deserialized = _deserialize(_models.AgentEvaluation, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @distributed_trace_async - async def delete_thread(self, thread_id: str, **kwargs: Any) -> _models.ThreadDeletionStatus: - """Deletes an existing thread. - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :return: ThreadDeletionStatus. The ThreadDeletionStatus is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadDeletionStatus +class DatasetsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.aio.AIProjectClient`'s + :attr:`datasets` 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, *, continuation_token_parameter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.DatasetVersion"]: + """List all versions of the given DatasetVersion. + + :param name: The name of the resource. Required. + :type name: str + :keyword continuation_token_parameter: Continuation token for pagination. Default value is + None. + :paramtype continuation_token_parameter: str + :return: An iterator like instance of DatasetVersion + :rtype: ~azure.core.async_paging.AsyncItemPaged[~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, @@ -1254,24 +818,191 @@ async def delete_thread(self, thread_id: str, **kwargs: Any) -> _models.ThreadDe } 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.ThreadDeletionStatus] = kwargs.pop("cls", None) + _request = build_datasets_list_versions_request( + name=name, + continuation_token_parameter=continuation_token_parameter, + 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_agents_delete_thread_request( - thread_id=thread_id, - api_version=self._config.api_version, + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.DatasetVersion], 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, *, continuation_token_parameter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.DatasetVersion"]: + """List the latest version of each DatasetVersion. + + :keyword continuation_token_parameter: Continuation token for pagination. Default value is + None. + :paramtype continuation_token_parameter: str + :return: An iterator like instance of DatasetVersion + :rtype: ~azure.core.async_paging.AsyncItemPaged[~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( + continuation_token_parameter=continuation_token_parameter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.DatasetVersion], 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.DatasetVersion: + """Get the specific version of the DatasetVersion. + + :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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -1294,7 +1025,7 @@ async def delete_thread(self, thread_id: str, **kwargs: Any) -> _models.ThreadDe if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.ThreadDeletionStatus, response.json()) + deserialized = _deserialize(_models.DatasetVersion, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -1302,36 +1033,15 @@ async def delete_thread(self, thread_id: str, **kwargs: Any) -> _models.ThreadDe return deserialized # type: ignore @distributed_trace_async - async def list_threads( - self, - *, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any - ) -> _models.OpenAIPageableListOfAgentThread: - """Gets a list of threads that were previously created. - - :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.ListSortOrder - :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: OpenAIPageableListOfAgentThread. The OpenAIPageableListOfAgentThread is compatible - with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIPageableListOfAgentThread + async def delete(self, name: str, version: str, **kwargs: Any) -> None: + """Delete the specific version of the DatasetVersion. + + :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 = { @@ -1345,171 +1055,121 @@ async def list_threads( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.OpenAIPageableListOfAgentThread] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_agents_list_threads_request( - limit=limit, - order=order, - after=after, - before=before, + _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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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 = 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() - else: - deserialized = _deserialize(_models.OpenAIPageableListOfAgentThread, response.json()) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore + return cls(pipeline_response, None, {}) # type: ignore @overload - async def create_message( + async def create_or_update( self, - thread_id: str, + name: str, + version: str, + dataset_version: _models.DatasetVersion, *, - role: Union[str, _models.MessageRole], - content: "_types.MessageInputContent", content_type: str = "application/json", - attachments: Optional[List[_models.MessageAttachment]] = None, - metadata: Optional[Dict[str, str]] = None, **kwargs: Any - ) -> _models.ThreadMessage: - """Creates a new message on a specified thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :keyword role: The role of the entity that is creating the message. Allowed values include: - ``user``, which indicates the message is sent by an actual user (and should be - used in most cases to represent user-generated messages), and ``assistant``, - which indicates the message is generated by the agent (use this value to insert - messages from the agent into the conversation). Known values are: "user" and "assistant". - Required. - :paramtype role: str or ~azure.ai.projects.models.MessageRole - :keyword content: The content of the initial message. This may be a basic string (if you only - need text) or an array of typed content blocks (for example, text, image_file, - image_url, and so on). Is either a str type or a [MessageInputContentBlock] type. Required. - :paramtype content: str or list[~azure.ai.projects.models.MessageInputContentBlock] + ) -> _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 replace. Required. + :type version: str + :param dataset_version: The definition of 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/json". :paramtype content_type: str - :keyword attachments: A list of files attached to the message, and the tools they should be - added to. Default value is None. - :paramtype attachments: list[~azure.ai.projects.models.MessageAttachment] - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadMessage. The ThreadMessage is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadMessage + :return: DatasetVersion. The DatasetVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetVersion :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_message( - self, thread_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadMessage: - """Creates a new message on a specified thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param body: Required. - :type body: JSON + async def create_or_update( + self, name: str, version: str, dataset_version: JSON, *, content_type: str = "application/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 replace. Required. + :type version: str + :param dataset_version: The definition of 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/json". :paramtype content_type: str - :return: ThreadMessage. The ThreadMessage is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadMessage + :return: DatasetVersion. The DatasetVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetVersion :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def create_message( - self, thread_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadMessage: - """Creates a new message on a specified thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param body: Required. - :type body: IO[bytes] + async def create_or_update( + self, + name: str, + version: str, + dataset_version: IO[bytes], + *, + content_type: str = "application/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 replace. Required. + :type version: str + :param dataset_version: The definition of 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/json". :paramtype content_type: str - :return: ThreadMessage. The ThreadMessage is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadMessage + :return: DatasetVersion. The DatasetVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetVersion :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def create_message( - self, - thread_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - role: Union[str, _models.MessageRole] = _Unset, - content: "_types.MessageInputContent" = _Unset, - attachments: Optional[List[_models.MessageAttachment]] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.ThreadMessage: - """Creates a new message on a specified thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword role: The role of the entity that is creating the message. Allowed values include: - ``user``, which indicates the message is sent by an actual user (and should be - used in most cases to represent user-generated messages), and ``assistant``, - which indicates the message is generated by the agent (use this value to insert - messages from the agent into the conversation). Known values are: "user" and "assistant". - Required. - :paramtype role: str or ~azure.ai.projects.models.MessageRole - :keyword content: The content of the initial message. This may be a basic string (if you only - need text) or an array of typed content blocks (for example, text, image_file, - image_url, and so on). Is either a str type or a [MessageInputContentBlock] type. Required. - :paramtype content: str or list[~azure.ai.projects.models.MessageInputContentBlock] - :keyword attachments: A list of files attached to the message, and the tools they should be - added to. Default value is None. - :paramtype attachments: list[~azure.ai.projects.models.MessageAttachment] - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadMessage. The ThreadMessage is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadMessage + async 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 replace. Required. + :type version: str + :param dataset_version: The definition of 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 = { @@ -1524,24 +1184,18 @@ async def create_message( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThreadMessage] = kwargs.pop("cls", None) - - if body is _Unset: - if role is _Unset: - raise TypeError("missing required argument: role") - if content is _Unset: - raise TypeError("missing required argument: content") - body = {"attachments": attachments, "content": content, "metadata": metadata, "role": role} - body = {k: v for k, v in body.items() if v is not None} + cls: ClsType[_models.DatasetVersion] = kwargs.pop("cls", None) + content_type = content_type or "application/json" _content = None - if isinstance(body, (IOBase, bytes)): - _content = body + if isinstance(dataset_version, (IOBase, bytes)): + _content = dataset_version else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(dataset_version, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_agents_create_message_request( - thread_id=thread_id, + _request = build_datasets_create_or_update_request( + name=name, + version=version, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -1549,12 +1203,7 @@ async def create_message( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -1565,7 +1214,7 @@ async def create_message( response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [200, 201]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -1577,50 +1226,94 @@ async def create_message( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.ThreadMessage, response.json()) + deserialized = _deserialize(_models.DatasetVersion, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @distributed_trace_async - async def list_messages( + @overload + async def pending_upload( self, - thread_id: str, + name: str, + version: str, + body: _models.PendingUploadRequest, *, - run_id: Optional[str] = None, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, + content_type: str = "application/json", **kwargs: Any - ) -> _models.OpenAIPageableListOfThreadMessage: - """Gets a list of messages that exist on a thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :keyword run_id: Filter messages by the run ID that generated them. Default value is None. - :paramtype run_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.ListSortOrder - :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: OpenAIPageableListOfThreadMessage. The OpenAIPageableListOfThreadMessage is compatible - with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIPageableListOfThreadMessage + ) -> _models.PendingUploadResponse: + """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 body: Parameters for the action. Required. + :type body: ~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: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResponse + :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.PendingUploadResponse: + """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 body: Parameters for the action. 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: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResponse + :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.PendingUploadResponse: + """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 body: Parameters for the action. 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: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def pending_upload( + self, name: str, version: str, body: Union[_models.PendingUploadRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.PendingUploadResponse: + """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 body: Parameters for the action. Is one of the following types: PendingUploadRequest, + JSON, IO[bytes] Required. + :type body: ~azure.ai.projects.models.PendingUploadRequest or JSON or IO[bytes] + :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResponse :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1631,29 +1324,30 @@ async def list_messages( } 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.OpenAIPageableListOfThreadMessage] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PendingUploadResponse] = 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_agents_list_messages_request( - thread_id=thread_id, - run_id=run_id, - limit=limit, - order=order, - after=after, - before=before, + _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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -1676,7 +1370,7 @@ async def list_messages( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.OpenAIPageableListOfThreadMessage, response.json()) + deserialized = _deserialize(_models.PendingUploadResponse, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -1684,15 +1378,19 @@ async def list_messages( return deserialized # type: ignore @distributed_trace_async - async def get_message(self, thread_id: str, message_id: str, **kwargs: Any) -> _models.ThreadMessage: - """Gets an existing message from an existing thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param message_id: Identifier of the message. Required. - :type message_id: str - :return: ThreadMessage. The ThreadMessage is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadMessage + async def get_credentials( + self, name: str, version: str, body: Any, **kwargs: Any + ) -> _models.AssetCredentialResponse: + """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 + :param body: Parameters for the action. Required. + :type body: any + :return: AssetCredentialResponse. The AssetCredentialResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AssetCredentialResponse :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -1703,25 +1401,25 @@ async def get_message(self, thread_id: str, message_id: str, **kwargs: Any) -> _ } 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.ThreadMessage] = kwargs.pop("cls", None) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) + cls: ClsType[_models.AssetCredentialResponse] = kwargs.pop("cls", None) + + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_agents_get_message_request( - thread_id=thread_id, - message_id=message_id, + _request = build_datasets_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -1744,109 +1442,51 @@ async def get_message(self, thread_id: str, message_id: str, **kwargs: Any) -> _ if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.ThreadMessage, response.json()) + deserialized = _deserialize(_models.AssetCredentialResponse, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @overload - async def update_message( - self, - thread_id: str, - message_id: str, - *, - content_type: str = "application/json", - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.ThreadMessage: - """Modifies an existing message on an existing thread. - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param message_id: Identifier of the message. Required. - :type message_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadMessage. The ThreadMessage is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadMessage - :raises ~azure.core.exceptions.HttpResponseError: - """ +class IndexesOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - @overload - async def update_message( - self, thread_id: str, message_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadMessage: - """Modifies an existing message on an existing thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param message_id: Identifier of the message. Required. - :type message_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: ThreadMessage. The ThreadMessage is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadMessage - :raises ~azure.core.exceptions.HttpResponseError: - """ + Instead, you should access the following operations through + :class:`~azure.ai.projects.aio.AIProjectClient`'s + :attr:`indexes` attribute. + """ - @overload - async def update_message( - self, thread_id: str, message_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadMessage: - """Modifies an existing message on an existing thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param message_id: Identifier of the message. Required. - :type message_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: ThreadMessage. The ThreadMessage is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadMessage - :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") - @distributed_trace_async - async def update_message( - self, - thread_id: str, - message_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.ThreadMessage: - """Modifies an existing message on an existing thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param message_id: Identifier of the message. Required. - :type message_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is + @distributed_trace + def list_versions( + self, name: str, *, continuation_token_parameter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.Index"]: + """List all versions of the given Index. + + :param name: The name of the resource. Required. + :type name: str + :keyword continuation_token_parameter: Continuation token for pagination. Default value is None. - :paramtype metadata: dict[str, str] - :return: ThreadMessage. The ThreadMessage is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadMessage + :paramtype continuation_token_parameter: str + :return: An iterator like instance of Index + :rtype: ~azure.core.async_paging.AsyncItemPaged[~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, @@ -1855,347 +1495,167 @@ async def update_message( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} + def prepare_request(next_link=None): + if not next_link: - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.ThreadMessage] = kwargs.pop("cls", None) + _request = build_indexes_list_versions_request( + name=name, + continuation_token_parameter=continuation_token_parameter, + 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 body is _Unset: - body = {"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 + 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_agents_update_message_request( - thread_id=thread_id, - message_id=message_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + return _request - _stream = kwargs.pop("stream", False) - pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access - _request, stream=_stream, **kwargs - ) + async 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, AsyncList(list_of_elem) - response = pipeline_response.http_response + async def get_next(next_link=None): + _request = prepare_request(next_link) - 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) + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.ThreadMessage, 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 AsyncItemPaged(get_next, extract_data) - @overload - async def create_run( - self, - thread_id: str, - *, - agent_id: str, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - content_type: str = "application/json", - model: Optional[str] = None, - instructions: Optional[str] = None, - additional_instructions: Optional[str] = None, - additional_messages: Optional[List[_models.ThreadMessageOptions]] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - stream_parameter: Optional[bool] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.ThreadRun: - """Creates a new run for an agent thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :keyword agent_id: The ID of the agent that should run the thread. Required. - :paramtype agent_id: str - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword model: The overridden model name that the agent should use to run the thread. Default - value is None. - :paramtype model: str - :keyword instructions: The overridden system instructions that the agent should use to run the - thread. Default value is None. - :paramtype instructions: str - :keyword additional_instructions: Additional instructions to append at the end of the - instructions for the run. This is useful for modifying the behavior - on a per-run basis without overriding other instructions. Default value is None. - :paramtype additional_instructions: str - :keyword additional_messages: Adds additional messages to the thread before creating the run. - Default value is None. - :paramtype additional_messages: list[~azure.ai.projects.models.ThreadMessageOptions] - :keyword tools: The overridden list of enabled tools that the agent should use to run the - thread. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword stream_parameter: If ``true``, returns a stream of events that happen during the Run - as server-sent events, - terminating when the Run enters a terminal state with a ``data: [DONE]`` message. Default - value is None. - :paramtype stream_parameter: bool - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort - to use only the number of completion tokens specified, across multiple turns of the run. If - the run exceeds the number of - completion tokens specified, the run will end with status ``incomplete``. See - ``incomplete_details`` for more info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode - or ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat, ResponseFormatJsonSchemaType Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat or - ~azure.ai.projects.models.ResponseFormatJsonSchemaType - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is + @distributed_trace + def list( + self, *, continuation_token_parameter: Optional[str] = None, **kwargs: Any + ) -> AsyncIterable["_models.Index"]: + """List the latest version of each Index. + + :keyword continuation_token_parameter: Continuation token for pagination. Default value is None. - :paramtype metadata: dict[str, str] - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun + :paramtype continuation_token_parameter: str + :return: An iterator like instance of Index + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.Index] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - @overload - async def create_run( - self, - thread_id: str, - body: JSON, - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ThreadRun: - """Creates a new run for an agent thread. + cls: ClsType[List[_models.Index]] = kwargs.pop("cls", None) - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param body: Required. - :type body: JSON - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :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_run( - self, - thread_id: str, - body: IO[bytes], - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ThreadRun: - """Creates a new run for an agent thread. + def prepare_request(next_link=None): + if not next_link: - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param body: Required. - :type body: IO[bytes] - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ + _request = build_indexes_list_request( + continuation_token_parameter=continuation_token_parameter, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.Index], 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 create_run( - self, - thread_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - agent_id: str = _Unset, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - model: Optional[str] = None, - instructions: Optional[str] = None, - additional_instructions: Optional[str] = None, - additional_messages: Optional[List[_models.ThreadMessageOptions]] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - stream_parameter: Optional[bool] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.ThreadRun: - """Creates a new run for an agent thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword agent_id: The ID of the agent that should run the thread. Required. - :paramtype agent_id: str - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword model: The overridden model name that the agent should use to run the thread. Default - value is None. - :paramtype model: str - :keyword instructions: The overridden system instructions that the agent should use to run the - thread. Default value is None. - :paramtype instructions: str - :keyword additional_instructions: Additional instructions to append at the end of the - instructions for the run. This is useful for modifying the behavior - on a per-run basis without overriding other instructions. Default value is None. - :paramtype additional_instructions: str - :keyword additional_messages: Adds additional messages to the thread before creating the run. - Default value is None. - :paramtype additional_messages: list[~azure.ai.projects.models.ThreadMessageOptions] - :keyword tools: The overridden list of enabled tools that the agent should use to run the - thread. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword stream_parameter: If ``true``, returns a stream of events that happen during the Run - as server-sent events, - terminating when the Run enters a terminal state with a ``data: [DONE]`` message. Default - value is None. - :paramtype stream_parameter: bool - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort - to use only the number of completion tokens specified, across multiple turns of the run. If - the run exceeds the number of - completion tokens specified, the run will end with status ``incomplete``. See - ``incomplete_details`` for more info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode - or ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat, ResponseFormatJsonSchemaType Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat or - ~azure.ai.projects.models.ResponseFormatJsonSchemaType - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun + async def get(self, name: str, version: str, **kwargs: Any) -> _models.Index: + """Get the specific version of the Index. + + :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 = { @@ -2206,57 +1666,20 @@ async def create_run( } 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.ThreadRun] = kwargs.pop("cls", None) - - if body is _Unset: - if agent_id is _Unset: - raise TypeError("missing required argument: agent_id") - body = { - "additional_instructions": additional_instructions, - "additional_messages": additional_messages, - "assistant_id": agent_id, - "instructions": instructions, - "max_completion_tokens": max_completion_tokens, - "max_prompt_tokens": max_prompt_tokens, - "metadata": metadata, - "model": model, - "parallel_tool_calls": parallel_tool_calls, - "response_format": response_format, - "stream": stream_parameter, - "temperature": temperature, - "tool_choice": tool_choice, - "tools": tools, - "top_p": top_p, - "truncation_strategy": truncation_strategy, - } - 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.Index] = kwargs.pop("cls", None) - _request = build_agents_create_run_request( - thread_id=thread_id, - include=include, - content_type=content_type, + _request = build_indexes_get_request( + name=name, + version=version, 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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -2279,7 +1702,7 @@ async def create_run( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.ThreadRun, response.json()) + deserialized = _deserialize(_models.Index, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -2287,39 +1710,15 @@ async def create_run( return deserialized # type: ignore @distributed_trace_async - async def list_runs( - self, - thread_id: str, - *, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any - ) -> _models.OpenAIPageableListOfThreadRun: - """Gets a list of runs for a specified thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_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.ListSortOrder - :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: OpenAIPageableListOfThreadRun. The OpenAIPageableListOfThreadRun is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIPageableListOfThreadRun + async def delete(self, name: str, version: str, **kwargs: Any) -> None: + """Delete the specific version of the Index. + + :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 = { @@ -2333,3576 +1732,127 @@ async def list_runs( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.OpenAIPageableListOfThreadRun] = kwargs.pop("cls", None) + cls: ClsType[None] = kwargs.pop("cls", None) - _request = build_agents_list_runs_request( - thread_id=thread_id, - limit=limit, - order=order, - after=after, - before=before, + _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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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 = 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 - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.OpenAIPageableListOfThreadRun, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_run(self, thread_id: str, run_id: str, **kwargs: Any) -> _models.ThreadRun: - """Gets an existing run from an existing thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_id: str - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :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.ThreadRun] = kwargs.pop("cls", None) - - _request = build_agents_get_run_request( - thread_id=thread_id, - run_id=run_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.ThreadRun, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def update_run( - self, - thread_id: str, - run_id: str, - *, - content_type: str = "application/json", - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.ThreadRun: - """Modifies an existing thread run. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def update_run( - self, thread_id: str, run_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadRun: - """Modifies an existing thread run. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_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: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def update_run( - self, thread_id: str, run_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadRun: - """Modifies an existing thread run. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_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: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def update_run( - self, - thread_id: str, - run_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.ThreadRun: - """Modifies an existing thread run. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :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.ThreadRun] = kwargs.pop("cls", None) - - if body is _Unset: - body = {"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_update_run_request( - thread_id=thread_id, - run_id=run_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.ThreadRun, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def submit_tool_outputs_to_run( - self, - thread_id: str, - run_id: str, - *, - tool_outputs: List[_models.ToolOutput], - content_type: str = "application/json", - stream_parameter: Optional[bool] = None, - **kwargs: Any - ) -> _models.ThreadRun: - """Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_id: str - :keyword tool_outputs: A list of tools for which the outputs are being submitted. Required. - :paramtype tool_outputs: list[~azure.ai.projects.models.ToolOutput] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword stream_parameter: If true, returns a stream of events that happen during the Run as - server-sent events, terminating when the run enters a terminal state. Default value is None. - :paramtype stream_parameter: bool - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def submit_tool_outputs_to_run( - self, thread_id: str, run_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadRun: - """Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_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: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def submit_tool_outputs_to_run( - self, thread_id: str, run_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadRun: - """Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_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: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def submit_tool_outputs_to_run( - self, - thread_id: str, - run_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - tool_outputs: List[_models.ToolOutput] = _Unset, - stream_parameter: Optional[bool] = None, - **kwargs: Any - ) -> _models.ThreadRun: - """Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword tool_outputs: A list of tools for which the outputs are being submitted. Required. - :paramtype tool_outputs: list[~azure.ai.projects.models.ToolOutput] - :keyword stream_parameter: If true, returns a stream of events that happen during the Run as - server-sent events, terminating when the run enters a terminal state. Default value is None. - :paramtype stream_parameter: bool - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :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.ThreadRun] = kwargs.pop("cls", None) - - if body is _Unset: - if tool_outputs is _Unset: - raise TypeError("missing required argument: tool_outputs") - body = {"stream": stream_parameter, "tool_outputs": tool_outputs} - 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_submit_tool_outputs_to_run_request( - thread_id=thread_id, - run_id=run_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.ThreadRun, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def cancel_run(self, thread_id: str, run_id: str, **kwargs: Any) -> _models.ThreadRun: - """Cancels a run of an in progress thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_id: str - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :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.ThreadRun] = kwargs.pop("cls", None) - - _request = build_agents_cancel_run_request( - thread_id=thread_id, - run_id=run_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.ThreadRun, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create_thread_and_run( - self, - *, - agent_id: str, - content_type: str = "application/json", - thread: Optional[_models.AgentThreadCreationOptions] = None, - model: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.UpdateToolResourcesOptions] = None, - stream_parameter: Optional[bool] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.ThreadRun: - """Creates a new agent thread and immediately starts a run using that new thread. - - :keyword agent_id: The ID of the agent for which the thread should be created. Required. - :paramtype agent_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword thread: The details used to create the new thread. If no thread is provided, an empty - one will be created. Default value is None. - :paramtype thread: ~azure.ai.projects.models.AgentThreadCreationOptions - :keyword model: The overridden model that the agent should use to run the thread. Default value - is None. - :paramtype model: str - :keyword instructions: The overridden system instructions the agent should use to run the - thread. Default value is None. - :paramtype instructions: str - :keyword tools: The overridden list of enabled tools the agent should use to run the thread. - Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword tool_resources: Override the tools the agent can use for this run. This is useful for - modifying the behavior on a per-run basis. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.UpdateToolResourcesOptions - :keyword stream_parameter: If ``true``, returns a stream of events that happen during the Run - as server-sent events, - terminating when the Run enters a terminal state with a ``data: [DONE]`` message. Default - value is None. - :paramtype stream_parameter: bool - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort to use only - the number of completion tokens specified, across multiple turns of the run. If the run - exceeds the number of completion tokens - specified, the run will end with status ``incomplete``. See ``incomplete_details`` for more - info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode - or ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat, ResponseFormatJsonSchemaType Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat or - ~azure.ai.projects.models.ResponseFormatJsonSchemaType - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_thread_and_run( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadRun: - """Creates a new agent thread and immediately starts a run using that new thread. - - :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: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_thread_and_run( - self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadRun: - """Creates a new agent thread and immediately starts a run using that new thread. - - :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: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_thread_and_run( - self, - body: Union[JSON, IO[bytes]] = _Unset, - *, - agent_id: str = _Unset, - thread: Optional[_models.AgentThreadCreationOptions] = None, - model: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.UpdateToolResourcesOptions] = None, - stream_parameter: Optional[bool] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.ThreadRun: - """Creates a new agent thread and immediately starts a run using that new thread. - - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword agent_id: The ID of the agent for which the thread should be created. Required. - :paramtype agent_id: str - :keyword thread: The details used to create the new thread. If no thread is provided, an empty - one will be created. Default value is None. - :paramtype thread: ~azure.ai.projects.models.AgentThreadCreationOptions - :keyword model: The overridden model that the agent should use to run the thread. Default value - is None. - :paramtype model: str - :keyword instructions: The overridden system instructions the agent should use to run the - thread. Default value is None. - :paramtype instructions: str - :keyword tools: The overridden list of enabled tools the agent should use to run the thread. - Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword tool_resources: Override the tools the agent can use for this run. This is useful for - modifying the behavior on a per-run basis. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.UpdateToolResourcesOptions - :keyword stream_parameter: If ``true``, returns a stream of events that happen during the Run - as server-sent events, - terminating when the Run enters a terminal state with a ``data: [DONE]`` message. Default - value is None. - :paramtype stream_parameter: bool - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort to use only - the number of completion tokens specified, across multiple turns of the run. If the run - exceeds the number of completion tokens - specified, the run will end with status ``incomplete``. See ``incomplete_details`` for more - info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode - or ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat, ResponseFormatJsonSchemaType Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat or - ~azure.ai.projects.models.ResponseFormatJsonSchemaType - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :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.ThreadRun] = kwargs.pop("cls", None) - - if body is _Unset: - if agent_id is _Unset: - raise TypeError("missing required argument: agent_id") - body = { - "assistant_id": agent_id, - "instructions": instructions, - "max_completion_tokens": max_completion_tokens, - "max_prompt_tokens": max_prompt_tokens, - "metadata": metadata, - "model": model, - "parallel_tool_calls": parallel_tool_calls, - "response_format": response_format, - "stream": stream_parameter, - "temperature": temperature, - "thread": thread, - "tool_choice": tool_choice, - "tool_resources": tool_resources, - "tools": tools, - "top_p": top_p, - "truncation_strategy": truncation_strategy, - } - 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_thread_and_run_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.ThreadRun, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_run_step( - self, - thread_id: str, - run_id: str, - step_id: str, - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - **kwargs: Any - ) -> _models.RunStep: - """Gets a single run step from a thread run. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_id: str - :param step_id: Identifier of the run step. Required. - :type step_id: str - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :return: RunStep. The RunStep is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.RunStep - :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.RunStep] = kwargs.pop("cls", None) - - _request = build_agents_get_run_step_request( - thread_id=thread_id, - run_id=run_id, - step_id=step_id, - include=include, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.RunStep, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list_run_steps( - self, - thread_id: str, - run_id: str, - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any - ) -> _models.OpenAIPageableListOfRunStep: - """Gets a list of run steps from a thread run. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_id: str - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :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.ListSortOrder - :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: OpenAIPageableListOfRunStep. The OpenAIPageableListOfRunStep is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIPageableListOfRunStep - :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.OpenAIPageableListOfRunStep] = kwargs.pop("cls", None) - - _request = build_agents_list_run_steps_request( - thread_id=thread_id, - run_id=run_id, - include=include, - 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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.OpenAIPageableListOfRunStep, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list_files( - self, *, purpose: Optional[Union[str, _models.FilePurpose]] = None, **kwargs: Any - ) -> _models.FileListResponse: - """Gets a list of previously uploaded files. - - :keyword purpose: The purpose of the file. Known values are: "fine-tune", "fine-tune-results", - "assistants", "assistants_output", "batch", "batch_output", and "vision". Default value is - None. - :paramtype purpose: str or ~azure.ai.projects.models.FilePurpose - :return: FileListResponse. The FileListResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.FileListResponse - :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.FileListResponse] = kwargs.pop("cls", None) - - _request = build_agents_list_files_request( - purpose=purpose, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.FileListResponse, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def _upload_file(self, body: _models._models.UploadFileRequest, **kwargs: Any) -> _models.OpenAIFile: ... - @overload - async def _upload_file(self, body: JSON, **kwargs: Any) -> _models.OpenAIFile: ... - - @distributed_trace_async - async def _upload_file( - self, body: Union[_models._models.UploadFileRequest, JSON], **kwargs: Any - ) -> _models.OpenAIFile: - """Uploads a file for use by other operations. - - :param body: Multipart body. Is either a UploadFileRequest type or a JSON type. Required. - :type body: ~azure.ai.projects.models._models.UploadFileRequest or JSON - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIFile - :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.OpenAIFile] = kwargs.pop("cls", None) - - _body = body.as_dict() if isinstance(body, _model_base.Model) else body - _file_fields: List[str] = ["file"] - _data_fields: List[str] = ["purpose", "filename"] - _files, _data = prepare_multipart_form_data(_body, _file_fields, _data_fields) - - _request = build_agents_upload_file_request( - api_version=self._config.api_version, - files=_files, - data=_data, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.OpenAIFile, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete_file(self, file_id: str, **kwargs: Any) -> _models.FileDeletionStatus: - """Delete a previously uploaded file. - - :param file_id: The ID of the file to delete. Required. - :type file_id: str - :return: FileDeletionStatus. The FileDeletionStatus is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.FileDeletionStatus - :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.FileDeletionStatus] = kwargs.pop("cls", None) - - _request = build_agents_delete_file_request( - file_id=file_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.FileDeletionStatus, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_file(self, file_id: str, **kwargs: Any) -> _models.OpenAIFile: - """Returns information about a specific file. Does not retrieve file content. - - :param file_id: The ID of the file to retrieve. Required. - :type file_id: str - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIFile - :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.OpenAIFile] = kwargs.pop("cls", None) - - _request = build_agents_get_file_request( - file_id=file_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.OpenAIFile, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def _get_file_content(self, file_id: str, **kwargs: Any) -> AsyncIterator[bytes]: - """Retrieves the raw content of a specific file. - - :param file_id: The ID of the file to retrieve. Required. - :type file_id: 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_agents_get_file_content_request( - file_id=file_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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) - raise HttpResponseError(response=response) - - deserialized = response.iter_bytes() - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list_vector_stores( - self, - *, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any - ) -> _models.OpenAIPageableListOfVectorStore: - """Returns a list of vector 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.ListSortOrder - :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: OpenAIPageableListOfVectorStore. The OpenAIPageableListOfVectorStore is compatible - with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIPageableListOfVectorStore - :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.OpenAIPageableListOfVectorStore] = kwargs.pop("cls", None) - - _request = build_agents_list_vector_stores_request( - 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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.OpenAIPageableListOfVectorStore, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create_vector_store( - self, - *, - content_type: str = "application/json", - file_ids: Optional[List[str]] = None, - name: Optional[str] = None, - store_configuration: Optional[_models.VectorStoreConfiguration] = None, - expires_after: Optional[_models.VectorStoreExpirationPolicy] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.VectorStore: - """Creates a vector store. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword file_ids: A list of file IDs that the vector store should use. Useful for tools like - ``file_search`` that can access files. Default value is None. - :paramtype file_ids: list[str] - :keyword name: The name of the vector store. Default value is None. - :paramtype name: str - :keyword store_configuration: The vector store configuration, used when vector store is created - from Azure asset URIs. Default value is None. - :paramtype store_configuration: ~azure.ai.projects.models.VectorStoreConfiguration - :keyword expires_after: Details on when this vector store expires. Default value is None. - :paramtype expires_after: ~azure.ai.projects.models.VectorStoreExpirationPolicy - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Only applicable if file_ids is non-empty. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_vector_store( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.VectorStore: - """Creates a vector 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: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_vector_store( - self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.VectorStore: - """Creates a vector 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: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_vector_store( - self, - body: Union[JSON, IO[bytes]] = _Unset, - *, - file_ids: Optional[List[str]] = None, - name: Optional[str] = None, - store_configuration: Optional[_models.VectorStoreConfiguration] = None, - expires_after: Optional[_models.VectorStoreExpirationPolicy] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.VectorStore: - """Creates a vector store. - - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword file_ids: A list of file IDs that the vector store should use. Useful for tools like - ``file_search`` that can access files. Default value is None. - :paramtype file_ids: list[str] - :keyword name: The name of the vector store. Default value is None. - :paramtype name: str - :keyword store_configuration: The vector store configuration, used when vector store is created - from Azure asset URIs. Default value is None. - :paramtype store_configuration: ~azure.ai.projects.models.VectorStoreConfiguration - :keyword expires_after: Details on when this vector store expires. Default value is None. - :paramtype expires_after: ~azure.ai.projects.models.VectorStoreExpirationPolicy - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Only applicable if file_ids is non-empty. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :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.VectorStore] = kwargs.pop("cls", None) - - if body is _Unset: - body = { - "chunking_strategy": chunking_strategy, - "configuration": store_configuration, - "expires_after": expires_after, - "file_ids": file_ids, - "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_agents_create_vector_store_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.VectorStore, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_vector_store(self, vector_store_id: str, **kwargs: Any) -> _models.VectorStore: - """Returns the vector store object matching the specified ID. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :return: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :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.VectorStore] = kwargs.pop("cls", None) - - _request = build_agents_get_vector_store_request( - vector_store_id=vector_store_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.VectorStore, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def modify_vector_store( - self, - vector_store_id: str, - *, - content_type: str = "application/json", - name: Optional[str] = None, - expires_after: Optional[_models.VectorStoreExpirationPolicy] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.VectorStore: - """The ID of the vector store to modify. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword name: The name of the vector store. Default value is None. - :paramtype name: str - :keyword expires_after: Details on when this vector store expires. Default value is None. - :paramtype expires_after: ~azure.ai.projects.models.VectorStoreExpirationPolicy - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def modify_vector_store( - self, vector_store_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.VectorStore: - """The ID of the vector store to modify. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_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: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def modify_vector_store( - self, vector_store_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.VectorStore: - """The ID of the vector store to modify. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_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: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def modify_vector_store( - self, - vector_store_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - name: Optional[str] = None, - expires_after: Optional[_models.VectorStoreExpirationPolicy] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.VectorStore: - """The ID of the vector store to modify. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :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 vector store. Default value is None. - :paramtype name: str - :keyword expires_after: Details on when this vector store expires. Default value is None. - :paramtype expires_after: ~azure.ai.projects.models.VectorStoreExpirationPolicy - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :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.VectorStore] = kwargs.pop("cls", None) - - if body is _Unset: - body = {"expires_after": expires_after, "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_agents_modify_vector_store_request( - vector_store_id=vector_store_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.VectorStore, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete_vector_store(self, vector_store_id: str, **kwargs: Any) -> _models.VectorStoreDeletionStatus: - """Deletes the vector store object matching the specified ID. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :return: VectorStoreDeletionStatus. The VectorStoreDeletionStatus is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreDeletionStatus - :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.VectorStoreDeletionStatus] = kwargs.pop("cls", None) - - _request = build_agents_delete_vector_store_request( - vector_store_id=vector_store_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.VectorStoreDeletionStatus, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list_vector_store_files( - self, - vector_store_id: str, - *, - filter: Optional[Union[str, _models.VectorStoreFileStatusFilter]] = None, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any - ) -> _models.OpenAIPageableListOfVectorStoreFile: - """Returns a list of vector store files. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :keyword filter: Filter by file status. Known values are: "in_progress", "completed", "failed", - and "cancelled". Default value is None. - :paramtype filter: str or ~azure.ai.projects.models.VectorStoreFileStatusFilter - :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.ListSortOrder - :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: OpenAIPageableListOfVectorStoreFile. The OpenAIPageableListOfVectorStoreFile is - compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIPageableListOfVectorStoreFile - :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.OpenAIPageableListOfVectorStoreFile] = kwargs.pop("cls", None) - - _request = build_agents_list_vector_store_files_request( - vector_store_id=vector_store_id, - filter=filter, - 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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.OpenAIPageableListOfVectorStoreFile, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create_vector_store_file( - self, - vector_store_id: str, - *, - content_type: str = "application/json", - file_id: Optional[str] = None, - data_source: Optional[_models.VectorStoreDataSource] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - **kwargs: Any - ) -> _models.VectorStoreFile: - """Create a vector store file by attaching a file to a vector store. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword file_id: Identifier of the file. Default value is None. - :paramtype file_id: str - :keyword data_source: Azure asset ID. Default value is None. - :paramtype data_source: ~azure.ai.projects.models.VectorStoreDataSource - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :return: VectorStoreFile. The VectorStoreFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_vector_store_file( - self, vector_store_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.VectorStoreFile: - """Create a vector store file by attaching a file to a vector store. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_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: VectorStoreFile. The VectorStoreFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_vector_store_file( - self, vector_store_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.VectorStoreFile: - """Create a vector store file by attaching a file to a vector store. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_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: VectorStoreFile. The VectorStoreFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_vector_store_file( - self, - vector_store_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - file_id: Optional[str] = None, - data_source: Optional[_models.VectorStoreDataSource] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - **kwargs: Any - ) -> _models.VectorStoreFile: - """Create a vector store file by attaching a file to a vector store. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword file_id: Identifier of the file. Default value is None. - :paramtype file_id: str - :keyword data_source: Azure asset ID. Default value is None. - :paramtype data_source: ~azure.ai.projects.models.VectorStoreDataSource - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :return: VectorStoreFile. The VectorStoreFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFile - :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.VectorStoreFile] = kwargs.pop("cls", None) - - if body is _Unset: - body = {"chunking_strategy": chunking_strategy, "data_source": data_source, "file_id": file_id} - body = {k: v for k, v in body.items() if v is not None} - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_agents_create_vector_store_file_request( - vector_store_id=vector_store_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.VectorStoreFile, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_vector_store_file(self, vector_store_id: str, file_id: str, **kwargs: Any) -> _models.VectorStoreFile: - """Retrieves a vector store file. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param file_id: Identifier of the file. Required. - :type file_id: str - :return: VectorStoreFile. The VectorStoreFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFile - :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.VectorStoreFile] = kwargs.pop("cls", None) - - _request = build_agents_get_vector_store_file_request( - vector_store_id=vector_store_id, - file_id=file_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.VectorStoreFile, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def delete_vector_store_file( - self, vector_store_id: str, file_id: str, **kwargs: Any - ) -> _models.VectorStoreFileDeletionStatus: - """Delete a vector store file. This will remove the file from the vector store but the file itself - will not be deleted. - To delete the file, use the delete file endpoint. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param file_id: Identifier of the file. Required. - :type file_id: str - :return: VectorStoreFileDeletionStatus. The VectorStoreFileDeletionStatus is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileDeletionStatus - :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.VectorStoreFileDeletionStatus] = kwargs.pop("cls", None) - - _request = build_agents_delete_vector_store_file_request( - vector_store_id=vector_store_id, - file_id=file_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.VectorStoreFileDeletionStatus, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def create_vector_store_file_batch( - self, - vector_store_id: str, - *, - content_type: str = "application/json", - file_ids: Optional[List[str]] = None, - data_sources: Optional[List[_models.VectorStoreDataSource]] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - **kwargs: Any - ) -> _models.VectorStoreFileBatch: - """Create a vector store file batch. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword file_ids: List of file identifiers. Default value is None. - :paramtype file_ids: list[str] - :keyword data_sources: List of Azure assets. Default value is None. - :paramtype data_sources: list[~azure.ai.projects.models.VectorStoreDataSource] - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :return: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_vector_store_file_batch( - self, vector_store_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.VectorStoreFileBatch: - """Create a vector store file batch. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_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: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_vector_store_file_batch( - self, vector_store_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.VectorStoreFileBatch: - """Create a vector store file batch. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_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: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_vector_store_file_batch( - self, - vector_store_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - file_ids: Optional[List[str]] = None, - data_sources: Optional[List[_models.VectorStoreDataSource]] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - **kwargs: Any - ) -> _models.VectorStoreFileBatch: - """Create a vector store file batch. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword file_ids: List of file identifiers. Default value is None. - :paramtype file_ids: list[str] - :keyword data_sources: List of Azure assets. Default value is None. - :paramtype data_sources: list[~azure.ai.projects.models.VectorStoreDataSource] - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :return: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch - :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.VectorStoreFileBatch] = kwargs.pop("cls", None) - - if body is _Unset: - body = {"chunking_strategy": chunking_strategy, "data_sources": data_sources, "file_ids": file_ids} - 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_vector_store_file_batch_request( - vector_store_id=vector_store_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.VectorStoreFileBatch, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def get_vector_store_file_batch( - self, vector_store_id: str, batch_id: str, **kwargs: Any - ) -> _models.VectorStoreFileBatch: - """Retrieve a vector store file batch. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param batch_id: Identifier of the file batch. Required. - :type batch_id: str - :return: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch - :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.VectorStoreFileBatch] = kwargs.pop("cls", None) - - _request = build_agents_get_vector_store_file_batch_request( - vector_store_id=vector_store_id, - batch_id=batch_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.VectorStoreFileBatch, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def cancel_vector_store_file_batch( - self, vector_store_id: str, batch_id: str, **kwargs: Any - ) -> _models.VectorStoreFileBatch: - """Cancel a vector store file batch. This attempts to cancel the processing of files in this batch - as soon as possible. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param batch_id: Identifier of the file batch. Required. - :type batch_id: str - :return: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch - :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.VectorStoreFileBatch] = kwargs.pop("cls", None) - - _request = build_agents_cancel_vector_store_file_batch_request( - vector_store_id=vector_store_id, - batch_id=batch_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.VectorStoreFileBatch, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def list_vector_store_file_batch_files( - self, - vector_store_id: str, - batch_id: str, - *, - filter: Optional[Union[str, _models.VectorStoreFileStatusFilter]] = None, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any - ) -> _models.OpenAIPageableListOfVectorStoreFile: - """Returns a list of vector store files in a batch. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param batch_id: Identifier of the file batch. Required. - :type batch_id: str - :keyword filter: Filter by file status. Known values are: "in_progress", "completed", "failed", - and "cancelled". Default value is None. - :paramtype filter: str or ~azure.ai.projects.models.VectorStoreFileStatusFilter - :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.ListSortOrder - :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: OpenAIPageableListOfVectorStoreFile. The OpenAIPageableListOfVectorStoreFile is - compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIPageableListOfVectorStoreFile - :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.OpenAIPageableListOfVectorStoreFile] = kwargs.pop("cls", None) - - _request = build_agents_list_vector_store_file_batch_files_request( - vector_store_id=vector_store_id, - batch_id=batch_id, - filter=filter, - 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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.OpenAIPageableListOfVectorStoreFile, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - -class ConnectionsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.ai.projects.aio.AIProjectClient`'s - :attr:`connections` 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_workspace(self, **kwargs: Any) -> _models._models.GetWorkspaceResponse: - """Gets the properties of the specified machine learning workspace. - - :return: GetWorkspaceResponse. The GetWorkspaceResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.models._models.GetWorkspaceResponse - :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._models.GetWorkspaceResponse] = kwargs.pop("cls", None) - - _request = build_connections_get_workspace_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize( - _models._models.GetWorkspaceResponse, response.json() # pylint: disable=protected-access - ) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def _list_connections( - self, - *, - category: Optional[Union[str, _models.ConnectionType]] = None, - include_all: Optional[bool] = None, - target: Optional[str] = None, - **kwargs: Any - ) -> _models._models.ListConnectionsResponse: - """List the details of all the connections (not including their credentials). - - :keyword category: Category of the workspace connection. Known values are: "AzureOpenAI", - "Serverless", "AzureBlob", "AIServices", "CognitiveSearch", "ApiKey", "CustomKeys", and - "CognitiveService". Default value is None. - :paramtype category: str or ~azure.ai.projects.models.ConnectionType - :keyword include_all: Indicates whether to list datastores. Service default: do not list - datastores. Default value is None. - :paramtype include_all: bool - :keyword target: Target of the workspace connection. Default value is None. - :paramtype target: str - :return: ListConnectionsResponse. The ListConnectionsResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.models._models.ListConnectionsResponse - :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._models.ListConnectionsResponse] = kwargs.pop("cls", None) - - _request = build_connections_list_connections_request( - category=category, - include_all=include_all, - target=target, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize( - _models._models.ListConnectionsResponse, response.json() # pylint: disable=protected-access - ) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace_async - async def _get_connection(self, connection_name: str, **kwargs: Any) -> _models._models.GetConnectionResponse: - """Get the details of a single connection, without credentials. - - :param connection_name: Connection Name. Required. - :type connection_name: str - :return: GetConnectionResponse. The GetConnectionResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.models._models.GetConnectionResponse - :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._models.GetConnectionResponse] = kwargs.pop("cls", None) - - _request = build_connections_get_connection_request( - connection_name=connection_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize( - _models._models.GetConnectionResponse, response.json() # pylint: disable=protected-access - ) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - async def _get_connection_with_secrets( - self, connection_name: str, *, ignored: str, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.GetConnectionResponse: ... - @overload - async def _get_connection_with_secrets( - self, connection_name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.GetConnectionResponse: ... - @overload - async def _get_connection_with_secrets( - self, connection_name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.GetConnectionResponse: ... - - @distributed_trace_async - async def _get_connection_with_secrets( - self, connection_name: str, body: Union[JSON, IO[bytes]] = _Unset, *, ignored: str = _Unset, **kwargs: Any - ) -> _models._models.GetConnectionResponse: - """Get the details of a single connection, including credentials (if available). - - :param connection_name: Connection Name. Required. - :type connection_name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword ignored: The body is ignored. TODO: Can we remove this?. Required. - :paramtype ignored: str - :return: GetConnectionResponse. The GetConnectionResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.models._models.GetConnectionResponse - :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._models.GetConnectionResponse] = kwargs.pop("cls", None) - - if body is _Unset: - if ignored is _Unset: - raise TypeError("missing required argument: ignored") - body = {"ignored": ignored} - 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_connections_get_connection_with_secrets_request( - connection_name=connection_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize( - _models._models.GetConnectionResponse, response.json() # pylint: disable=protected-access - ) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - -class TelemetryOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.ai.projects.aio.AIProjectClient`'s - :attr:`telemetry` 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_app_insights( - self, app_insights_resource_url: str, **kwargs: Any - ) -> _models._models.GetAppInsightsResponse: - """Gets the properties of the specified Application Insights resource. - - :param app_insights_resource_url: The AppInsights Azure resource Url. It should have the - format: - '/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}/providers/microsoft.insights/components/{resourcename}'. - Required. - :type app_insights_resource_url: str - :return: GetAppInsightsResponse. The GetAppInsightsResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.models._models.GetAppInsightsResponse - :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._models.GetAppInsightsResponse] = kwargs.pop("cls", None) - - _request = build_telemetry_get_app_insights_request( - app_insights_resource_url=app_insights_resource_url, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize( - _models._models.GetAppInsightsResponse, response.json() # pylint: disable=protected-access - ) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - -class EvaluationsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. - - Instead, you should access the following operations through - :class:`~azure.ai.projects.aio.AIProjectClient`'s - :attr:`evaluations` 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, id: str, **kwargs: Any) -> _models.Evaluation: - """Resource read operation template. - - :param id: Identifier of the evaluation. Required. - :type id: str - :return: Evaluation. The Evaluation is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Evaluation - :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.Evaluation] = kwargs.pop("cls", None) - - _request = build_evaluations_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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) - - 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() - else: - deserialized = _deserialize(_models.Evaluation, response.json()) - - if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore - - return deserialized # type: ignore - - @overload - async def create( - self, evaluation: _models.Evaluation, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Evaluation: - """Run the evaluation. - - :param evaluation: Evaluation to run. Required. - :type evaluation: ~azure.ai.projects.models.Evaluation - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Evaluation. The Evaluation is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Evaluation - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, evaluation: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Evaluation: - """Run the evaluation. - - :param evaluation: Evaluation to run. Required. - :type evaluation: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Evaluation. The Evaluation is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Evaluation - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create( - self, evaluation: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Evaluation: - """Run the evaluation. - - :param evaluation: Evaluation to run. Required. - :type evaluation: 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: Evaluation. The Evaluation is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Evaluation - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create(self, evaluation: Union[_models.Evaluation, JSON, IO[bytes]], **kwargs: Any) -> _models.Evaluation: - """Run the evaluation. - - :param evaluation: Evaluation to run. Is one of the following types: Evaluation, JSON, - IO[bytes] Required. - :type evaluation: ~azure.ai.projects.models.Evaluation or JSON or IO[bytes] - :return: Evaluation. The Evaluation is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Evaluation - :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.Evaluation] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(evaluation, (IOBase, bytes)): - _content = evaluation - else: - _content = json.dumps(evaluation, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - - _request = build_evaluations_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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) - raise HttpResponseError(response=response) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.Evaluation, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list( - self, *, top: Optional[int] = None, skip: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable["_models.Evaluation"]: - """Resource list operation template. - - :keyword top: The number of result items to return. Default value is None. - :paramtype top: int - :keyword skip: The number of result items to skip. Default value is None. - :paramtype skip: int - :return: An iterator like instance of Evaluation - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.Evaluation] - :raises ~azure.core.exceptions.HttpResponseError: - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - maxpagesize = kwargs.pop("maxpagesize", None) - cls: ClsType[List[_models.Evaluation]] = 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_evaluations_list_request( - top=top, - skip=skip, - maxpagesize=maxpagesize, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url( - "self._config.subscription_id", self._config.subscription_id, "str" - ), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _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"), - "subscriptionId": self._serialize.url( - "self._config.subscription_id", self._config.subscription_id, "str" - ), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _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.Evaluation], 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 + response = pipeline_response.http_response - return AsyncItemPaged(get_next, extract_data) + 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 - async def update( + async def create_or_update( self, - id: str, - resource: _models.Evaluation, + name: str, + version: str, + pending_upload_request: _models.Index, *, - content_type: str = "application/merge-patch+json", + content_type: str = "application/json", **kwargs: Any - ) -> _models.Evaluation: - """Resource update operation template. + ) -> _models.Index: + """Create a new or update an existing Index with the given version id. - :param id: Identifier of the evaluation. Required. - :type id: str - :param resource: The resource instance. Required. - :type resource: ~azure.ai.projects.models.Evaluation + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the Index to create or replace. Required. + :type version: str + :param pending_upload_request: The definition of the Index to create or update. Required. + :type pending_upload_request: ~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". + Default value is "application/json". :paramtype content_type: str - :return: Evaluation. The Evaluation is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Evaluation + :return: Index. The Index is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Index :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def update( - self, id: str, resource: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any - ) -> _models.Evaluation: - """Resource update operation template. + async def create_or_update( + self, + name: str, + version: str, + pending_upload_request: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Index: + """Create a new or update an existing Index with the given version id. - :param id: Identifier of the evaluation. Required. - :type id: str - :param resource: The resource instance. Required. - :type resource: JSON + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the Index to create or replace. Required. + :type version: str + :param pending_upload_request: The definition of the Index to create or update. Required. + :type pending_upload_request: 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: Evaluation. The Evaluation is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Evaluation + :return: Index. The Index is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Index :raises ~azure.core.exceptions.HttpResponseError: """ @overload - async def update( - self, id: str, resource: IO[bytes], *, content_type: str = "application/merge-patch+json", **kwargs: Any - ) -> _models.Evaluation: - """Resource update operation template. + async def create_or_update( + self, + name: str, + version: str, + pending_upload_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Index: + """Create a new or update an existing Index with the given version id. - :param id: Identifier of the evaluation. Required. - :type id: str - :param resource: The resource instance. Required. - :type resource: IO[bytes] + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the Index to create or replace. Required. + :type version: str + :param pending_upload_request: The definition of the Index to create or update. Required. + :type pending_upload_request: 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: Evaluation. The Evaluation is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Evaluation + :return: Index. The Index is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Index :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async - async def update( - self, id: str, resource: Union[_models.Evaluation, JSON, IO[bytes]], **kwargs: Any - ) -> _models.Evaluation: - """Resource update operation template. + async def create_or_update( + self, name: str, version: str, pending_upload_request: Union[_models.Index, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Index: + """Create a new or update an existing Index with the given version id. - :param id: Identifier of the evaluation. Required. - :type id: str - :param resource: The resource instance. Is one of the following types: Evaluation, JSON, - IO[bytes] Required. - :type resource: ~azure.ai.projects.models.Evaluation or JSON or IO[bytes] - :return: Evaluation. The Evaluation is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Evaluation + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the Index to create or replace. Required. + :type version: str + :param pending_upload_request: The definition of the Index to create or update. Is one of the + following types: Index, JSON, IO[bytes] Required. + :type pending_upload_request: ~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 = { @@ -5917,17 +1867,18 @@ async def update( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Evaluation] = kwargs.pop("cls", None) + cls: ClsType[_models.Index] = kwargs.pop("cls", None) - content_type = content_type or "application/merge-patch+json" + content_type = content_type or "application/json" _content = None - if isinstance(resource, (IOBase, bytes)): - _content = resource + if isinstance(pending_upload_request, (IOBase, bytes)): + _content = pending_upload_request else: - _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(pending_upload_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_evaluations_update_request( - id=id, + _request = build_indexes_create_or_update_request( + name=name, + version=version, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -5935,12 +1886,7 @@ async def update( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -5951,7 +1897,7 @@ async def update( response = pipeline_response.http_response - if response.status_code not in [200]: + if response.status_code not in [200, 201]: if _stream: try: await response.read() # Load the body in memory and close the socket @@ -5960,30 +1906,42 @@ async def update( 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() else: - deserialized = _deserialize(_models.Evaluation, response.json()) + deserialized = _deserialize(_models.Index, response.json()) if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore + 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.aio.AIProjectClient`'s + :attr:`deployments` 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_schedule(self, name: str, **kwargs: Any) -> _models.EvaluationSchedule: - """Resource read operation template. + async def get(self, name: str, **kwargs: Any) -> _models.Deployment: + """Get a deployed model. - :param name: Name of the schedule, which also serves as the unique identifier for the - evaluation. Required. + :param name: Name of the deployment. Required. :type name: str - :return: EvaluationSchedule. The EvaluationSchedule is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationSchedule + :return: Deployment. The Deployment is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Deployment :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5997,21 +1955,16 @@ async def get_schedule(self, name: str, **kwargs: Any) -> _models.EvaluationSche _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.EvaluationSchedule] = kwargs.pop("cls", None) + cls: ClsType[_models.Deployment] = kwargs.pop("cls", None) - _request = build_evaluations_get_schedule_request( + _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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -6039,84 +1992,153 @@ async def get_schedule(self, name: str, **kwargs: Any) -> _models.EvaluationSche if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.EvaluationSchedule, response.json()) + deserialized = _deserialize(_models.Deployment, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore - @overload - async def create_or_replace_schedule( - self, name: str, resource: _models.EvaluationSchedule, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationSchedule: - """Create or replace operation template. + @distributed_trace + def list( + self, + *, + model_publisher: Optional[str] = None, + model_name: Optional[str] = None, + deployment_type: Optional[Union[str, _models.DeploymentType]] = None, + top: Optional[int] = None, + skip: Optional[int] = None, + **kwargs: Any + ) -> AsyncIterable["_models.Deployment"]: + """List all deployed models in the project. - :param name: Name of the schedule, which also serves as the unique identifier for the - evaluation. Required. - :type name: str - :param resource: The resource instance. Required. - :type resource: ~azure.ai.projects.models.EvaluationSchedule - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationSchedule. The EvaluationSchedule is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationSchedule + :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 + :keyword top: The number of result items to return. Default value is None. + :paramtype top: int + :keyword skip: The number of result items to skip. Default value is None. + :paramtype skip: int + :return: An iterator like instance of Deployment + :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.Deployment] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - @overload - async def create_or_replace_schedule( - self, name: str, resource: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationSchedule: - """Create or replace operation template. + maxpagesize = kwargs.pop("maxpagesize", None) + cls: ClsType[List[_models.Deployment]] = kwargs.pop("cls", None) - :param name: Name of the schedule, which also serves as the unique identifier for the - evaluation. Required. - :type name: str - :param resource: The resource instance. Required. - :type resource: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationSchedule. The EvaluationSchedule is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationSchedule - :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_or_replace_schedule( - self, name: str, resource: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationSchedule: - """Create or replace operation template. + def prepare_request(next_link=None): + if not next_link: - :param name: Name of the schedule, which also serves as the unique identifier for the - evaluation. Required. - :type name: str - :param resource: The resource instance. Required. - :type resource: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationSchedule. The EvaluationSchedule is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationSchedule - :raises ~azure.core.exceptions.HttpResponseError: - """ + _request = build_deployments_list_request( + model_publisher=model_publisher, + model_name=model_name, + deployment_type=deployment_type, + top=top, + skip=skip, + maxpagesize=maxpagesize, + 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) - @distributed_trace_async - async def create_or_replace_schedule( - self, name: str, resource: Union[_models.EvaluationSchedule, JSON, IO[bytes]], **kwargs: Any - ) -> _models.EvaluationSchedule: - """Create or replace operation template. + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = _deserialize(List[_models.Deployment], 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) - :param name: Name of the schedule, which also serves as the unique identifier for the - evaluation. Required. + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + +class RedTeamsOperations: + """ + .. 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 + @api_version_validation( + method_added_on="2025-05-15-preview", + params_added_on={"2025-05-15-preview": ["api_version", "name", "client_request_id", "accept"]}, + ) + async def get(self, name: str, **kwargs: Any) -> _models.RedTeam: + """Get a redteam by name. + + :param name: Identifier of the red team. Required. :type name: str - :param resource: The resource instance. Is one of the following types: EvaluationSchedule, - JSON, IO[bytes] Required. - :type resource: ~azure.ai.projects.models.EvaluationSchedule or JSON or IO[bytes] - :return: EvaluationSchedule. The EvaluationSchedule is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationSchedule + :return: RedTeam. The RedTeam is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.RedTeam :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6127,34 +2149,19 @@ async def create_or_replace_schedule( } 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.EvaluationSchedule] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(resource, (IOBase, bytes)): - _content = resource - else: - _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + cls: ClsType[_models.RedTeam] = kwargs.pop("cls", None) - _request = build_evaluations_create_or_replace_schedule_request( + _request = build_red_teams_get_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -6165,7 +2172,7 @@ async def create_or_replace_schedule( 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 @@ -6182,7 +2189,7 @@ async def create_or_replace_schedule( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.EvaluationSchedule, response.json()) + deserialized = _deserialize(_models.RedTeam, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -6190,24 +2197,30 @@ async def create_or_replace_schedule( return deserialized # type: ignore @distributed_trace - def list_schedule( + @api_version_validation( + method_added_on="2025-05-15-preview", + params_added_on={ + "2025-05-15-preview": ["api_version", "top", "skip", "maxpagesize", "client_request_id", "accept"] + }, + ) + def list( self, *, top: Optional[int] = None, skip: Optional[int] = None, **kwargs: Any - ) -> AsyncIterable["_models.EvaluationSchedule"]: - """Resource list operation template. + ) -> AsyncIterable["_models.RedTeam"]: + """List a redteam by name. :keyword top: The number of result items to return. Default value is None. :paramtype top: int :keyword skip: The number of result items to skip. Default value is None. :paramtype skip: int - :return: An iterator like instance of EvaluationSchedule - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.ai.projects.models.EvaluationSchedule] + :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 {} maxpagesize = kwargs.pop("maxpagesize", None) - cls: ClsType[List[_models.EvaluationSchedule]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.RedTeam]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -6220,7 +2233,7 @@ def list_schedule( def prepare_request(next_link=None): if not next_link: - _request = build_evaluations_list_schedule_request( + _request = build_red_teams_list_request( top=top, skip=skip, maxpagesize=maxpagesize, @@ -6229,14 +2242,9 @@ def prepare_request(next_link=None): params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url( - "self._config.subscription_id", self._config.subscription_id, "str" + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -6254,14 +2262,9 @@ def prepare_request(next_link=None): "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"), - "subscriptionId": self._serialize.url( - "self._config.subscription_id", self._config.subscription_id, "str" - ), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -6269,7 +2272,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.EvaluationSchedule], deserialized.get("value", [])) + 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) @@ -6291,14 +2294,67 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) - @distributed_trace_async - async def disable_schedule(self, name: str, **kwargs: Any) -> None: - """Disable the evaluation schedule. + @overload + async def create_run( + self, red_team: _models.RedTeam, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RedTeam: + """Creates a redteam run. - :param name: Name of the evaluation schedule. Required. - :type name: str - :return: None - :rtype: None + :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_run( + 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_run( + 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 + @api_version_validation( + method_added_on="2025-05-15-preview", + params_added_on={"2025-05-15-preview": ["api_version", "content_type", "accept"]}, + ) + async def create_run(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. + :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 = { @@ -6309,37 +2365,53 @@ async def disable_schedule(self, name: str, **kwargs: Any) -> None: } 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.RedTeam] = kwargs.pop("cls", None) - _request = build_evaluations_disable_schedule_request( - name=name, + 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_red_teams_create_run_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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 + _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 [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() + else: + deserialized = _deserialize(_models.RedTeam, response.json()) + if cls: - return cls(pipeline_response, None, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore + + return 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 2e7b8d2f8d6c..8bcb627aa475 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 @@ -1,3283 +1,15 @@ -# pylint: disable=too-many-lines -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -import asyncio # pylint: disable=do-not-import-asyncio -import concurrent.futures -import io -import logging -import os -import time -import json -from pathlib import Path -from typing import ( - IO, - TYPE_CHECKING, - Any, - AsyncIterator, - Dict, - List, - MutableMapping, - Optional, - Sequence, - TextIO, - Union, - cast, - Callable, - Set, - overload, -) +from typing import List -from azure.core.credentials import TokenCredential -from azure.core.exceptions import ResourceNotFoundError -from azure.core.tracing.decorator_async import distributed_trace_async - -from ... import models as _models -from ..._vendor import FileType -from ...models._enums import AuthenticationType, ConnectionType, FilePurpose, RunStatus -from ...models._models import ( - GetAppInsightsResponse, - GetConnectionResponse, - GetWorkspaceResponse, - InternalConnectionPropertiesSASAuth, - ListConnectionsResponse, -) -from ...models._patch import ConnectionProperties -from ...operations._patch import _enable_telemetry -from ._operations import AgentsOperations as AgentsOperationsGenerated -from ._operations import ConnectionsOperations as ConnectionsOperationsGenerated -from ._operations import TelemetryOperations as TelemetryOperationsGenerated - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from openai import AsyncAzureOpenAI - - from azure.ai.inference.aio import ChatCompletionsClient, EmbeddingsClient, ImageEmbeddingsClient - from azure.ai.projects import _types - from azure.core.credentials import AccessToken - from azure.core.credentials_async import AsyncTokenCredential - -logger = logging.getLogger(__name__) - -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -_Unset: Any = object() - - -class InferenceOperations: - - def __init__(self, outer_instance): - - # All returned inference clients will have this application id set on their user-agent. - # For more info on user-agent HTTP header, see: - # https://azure.github.io/azure-sdk/general_azurecore.html#telemetry-policy - USER_AGENT_APP_ID = "AIProjectClient" - - if hasattr(outer_instance, "_user_agent") and outer_instance._user_agent: - # If the calling application has set "user_agent" when constructing the AIProjectClient, - # take that value and prepend it to USER_AGENT_APP_ID. - self._user_agent = f"{outer_instance._user_agent}-{USER_AGENT_APP_ID}" - else: - self._user_agent = USER_AGENT_APP_ID - - self._outer_instance = outer_instance - - @distributed_trace_async - async def get_chat_completions_client( - self, *, connection_name: Optional[str] = None, **kwargs - ) -> "ChatCompletionsClient": - """Get an authenticated asynchronous ChatCompletionsClient (from the package azure-ai-inference) for the default - Azure AI Services connected resource (if `connection_name` is not specificed), or from the Azure AI - Services resource given by its connection name. Keyword arguments are passed to the constructor of - ChatCompletionsClient. - - At least one AI model that supports chat completions must be deployed in this resource. - - .. note:: The packages `azure-ai-inference` and `aiohttp` must be installed prior to calling this method. - - :keyword connection_name: The name of a connection to an Azure AI Services resource in your AI Foundry project. - resource. Optional. If not provided, the default Azure AI Services connection will be used. - :type connection_name: str - - :return: An authenticated chat completions client. - :rtype: ~azure.ai.inference.ChatCompletionsClient - - :raises ~azure.core.exceptions.ResourceNotFoundError: if an Azure AI Services connection - does not exist. - :raises ~azure.core.exceptions.ModuleNotFoundError: if the `azure-ai-inference` package - is not installed. - :raises ValueError: if the connection name is an empty string. - :raises ~azure.core.exceptions.HttpResponseError: - """ - kwargs.setdefault("merge_span", True) - - if connection_name is not None and not connection_name: - raise ValueError("Connection name cannot be empty") - - # Back-door way to access the old behavior where each AI model (non-OpenAI) was hosted on - # a separate "Serverless" connection. This is now deprecated. - use_serverless_connection: bool = os.getenv("USE_SERVERLESS_CONNECTION", None) == "true" - - if connection_name: - connection = await self._outer_instance.connections.get( - connection_name=connection_name, include_credentials=True - ) - else: - if use_serverless_connection: - connection = await self._outer_instance.connections.get_default( - connection_type=ConnectionType.SERVERLESS, include_credentials=True - ) - else: - connection = await self._outer_instance.connections.get_default( - connection_type=ConnectionType.AZURE_AI_SERVICES, include_credentials=True - ) - - logger.debug("[InferenceOperations.get_chat_completions_client] connection = %s", str(connection)) - - try: - from azure.ai.inference.aio import ChatCompletionsClient - except ModuleNotFoundError as e: - raise ModuleNotFoundError( - "Azure AI Inference SDK is not installed. Please install it using 'pip install azure-ai-inference'" - ) from e - - if use_serverless_connection: - endpoint = connection.endpoint_url - credential_scopes = ["https://ml.azure.com/.default"] - else: - endpoint = f"{connection.endpoint_url}/models" - credential_scopes = ["https://cognitiveservices.azure.com/.default"] - - if connection.authentication_type == AuthenticationType.API_KEY: - logger.debug( - "[InferenceOperations.get_chat_completions_client]" - + " Creating ChatCompletionsClient using API key authentication" - ) - from azure.core.credentials import AzureKeyCredential - - client = ChatCompletionsClient( - endpoint=endpoint, - credential=AzureKeyCredential(connection.key), - user_agent=kwargs.pop("user_agent", self._user_agent), - **kwargs, - ) - elif connection.authentication_type == AuthenticationType.ENTRA_ID: - logger.debug( - "[InferenceOperations.get_chat_completions_client]" - + " Creating ChatCompletionsClient using Entra ID authentication" - ) - client = ChatCompletionsClient( - endpoint=endpoint, - credential=connection.token_credential, - credential_scopes=credential_scopes, - user_agent=kwargs.pop("user_agent", self._user_agent), - **kwargs, - ) - elif connection.authentication_type == AuthenticationType.SAS: - logger.debug( - "[InferenceOperations.get_chat_completions_client] " - + "Creating ChatCompletionsClient using SAS authentication" - ) - raise ValueError( - "Getting chat completions client from a connection with SAS authentication is not yet supported" - ) - else: - raise ValueError("Unknown authentication type") - - return client - - @distributed_trace_async - async def get_embeddings_client(self, *, connection_name: Optional[str] = None, **kwargs) -> "EmbeddingsClient": - """Get an authenticated asynchronous EmbeddingsClient (from the package azure-ai-inference) for the default - Azure AI Services connected resource (if `connection_name` is not specificed), or from the Azure AI - Services resource given by its connection name. Keyword arguments are passed to the constructor of - EmbeddingsClient. - - At least one AI model that supports text embeddings must be deployed in this resource. - - .. note:: The packages `azure-ai-inference` and `aiohttp` must be installed prior to calling this method. - - :keyword connection_name: The name of a connection to an Azure AI Services resource in your AI Foundry project. - resource. Optional. If not provided, the default Azure AI Services connection will be used. - :type connection_name: str - - :return: An authenticated text embeddings client - :rtype: ~azure.ai.inference.EmbeddingsClient - - :raises ~azure.core.exceptions.ResourceNotFoundError: if an Azure AI Services connection - does not exist. - :raises ~azure.core.exceptions.ModuleNotFoundError: if the `azure-ai-inference` package - is not installed. - :raises ValueError: if the connection name is an empty string. - :raises ~azure.core.exceptions.HttpResponseError: - """ - kwargs.setdefault("merge_span", True) - - if connection_name is not None and not connection_name: - raise ValueError("Connection name cannot be empty") - - # Back-door way to access the old behavior where each AI model (non-OpenAI) was hosted on - # a separate "Serverless" connection. This is now deprecated. - use_serverless_connection: bool = os.getenv("USE_SERVERLESS_CONNECTION", None) == "true" - - if connection_name: - connection = await self._outer_instance.connections.get( - connection_name=connection_name, include_credentials=True - ) - else: - if use_serverless_connection: - connection = await self._outer_instance.connections.get_default( - connection_type=ConnectionType.SERVERLESS, include_credentials=True - ) - else: - connection = await self._outer_instance.connections.get_default( - connection_type=ConnectionType.AZURE_AI_SERVICES, include_credentials=True - ) - - logger.debug("[InferenceOperations.get_embeddings_client] connection = %s", str(connection)) - - try: - from azure.ai.inference.aio import EmbeddingsClient - except ModuleNotFoundError as e: - raise ModuleNotFoundError( - "Azure AI Inference SDK is not installed. Please install it using 'pip install azure-ai-inference'" - ) from e - - if use_serverless_connection: - endpoint = connection.endpoint_url - credential_scopes = ["https://ml.azure.com/.default"] - else: - endpoint = f"{connection.endpoint_url}/models" - credential_scopes = ["https://cognitiveservices.azure.com/.default"] - - if connection.authentication_type == AuthenticationType.API_KEY: - logger.debug( - "[InferenceOperations.get_embeddings_client] Creating EmbeddingsClient using API key authentication" - ) - from azure.core.credentials import AzureKeyCredential - - client = EmbeddingsClient( - endpoint=endpoint, - credential=AzureKeyCredential(connection.key), - user_agent=kwargs.pop("user_agent", self._user_agent), - **kwargs, - ) - elif connection.authentication_type == AuthenticationType.ENTRA_ID: - logger.debug( - "[InferenceOperations.get_embeddings_client] Creating EmbeddingsClient using Entra ID authentication" - ) - client = EmbeddingsClient( - endpoint=endpoint, - credential=connection.token_credential, - credential_scopes=credential_scopes, - user_agent=kwargs.pop("user_agent", self._user_agent), - **kwargs, - ) - elif connection.authentication_type == AuthenticationType.SAS: - logger.debug( - "[InferenceOperations.get_embeddings_client] Creating EmbeddingsClient using SAS authentication" - ) - raise ValueError("Getting embeddings client from a connection with SAS authentication is not yet supported") - else: - raise ValueError("Unknown authentication type") - - return client - - @distributed_trace_async - async def get_image_embeddings_client( - self, *, connection_name: Optional[str] = None, **kwargs - ) -> "ImageEmbeddingsClient": - """Get an authenticated asynchronous ImageEmbeddingsClient (from the package azure-ai-inference) for the default - Azure AI Services connected resource (if `connection_name` is not specificed), or from the Azure AI - Services resource given by its connection name. Keyword arguments are passed to the constructor of - ImageEmbeddingsClient. - - At least one AI model that supports image embeddings must be deployed in this resource. - - .. note:: The packages `azure-ai-inference` and `aiohttp` must be installed prior to calling this method. - - :keyword connection_name: The name of a connection to an Azure AI Services resource in your AI Foundry project. - resource. Optional. If not provided, the default Azure AI Services connection will be used. - :type connection_name: str - - :return: An authenticated image embeddings client - :rtype: ~azure.ai.inference.ImageEmbeddingsClient - - :raises ~azure.core.exceptions.ResourceNotFoundError: if an Azure AI Services connection - does not exist. - :raises ~azure.core.exceptions.ModuleNotFoundError: if the `azure-ai-inference` package - is not installed. - :raises ValueError: if the connection name is an empty string. - :raises ~azure.core.exceptions.HttpResponseError: - """ - kwargs.setdefault("merge_span", True) - - if connection_name is not None and not connection_name: - raise ValueError("Connection name cannot be empty") - - # Back-door way to access the old behavior where each AI model (non-OpenAI) was hosted on - # a separate "Serverless" connection. This is now deprecated. - use_serverless_connection: bool = os.getenv("USE_SERVERLESS_CONNECTION", None) == "true" - - if connection_name: - connection = await self._outer_instance.connections.get( - connection_name=connection_name, include_credentials=True - ) - else: - if use_serverless_connection: - connection = await self._outer_instance.connections.get_default( - connection_type=ConnectionType.SERVERLESS, include_credentials=True - ) - else: - connection = await self._outer_instance.connections.get_default( - connection_type=ConnectionType.AZURE_AI_SERVICES, include_credentials=True - ) - - logger.debug("[InferenceOperations.get_embeddings_client] connection = %s", str(connection)) - - try: - from azure.ai.inference.aio import ImageEmbeddingsClient - except ModuleNotFoundError as e: - raise ModuleNotFoundError( - "Azure AI Inference SDK is not installed. Please install it using 'pip install azure-ai-inference'" - ) from e - - if use_serverless_connection: - endpoint = connection.endpoint_url - credential_scopes = ["https://ml.azure.com/.default"] - else: - endpoint = f"{connection.endpoint_url}/models" - credential_scopes = ["https://cognitiveservices.azure.com/.default"] - - if connection.authentication_type == AuthenticationType.API_KEY: - logger.debug( - "[InferenceOperations.get_image_embeddings_client] " - "Creating ImageEmbeddingsClient using API key authentication" - ) - from azure.core.credentials import AzureKeyCredential - - client = ImageEmbeddingsClient( - endpoint=endpoint, - credential=AzureKeyCredential(connection.key), - user_agent=kwargs.pop("user_agent", self._user_agent), - **kwargs, - ) - elif connection.authentication_type == AuthenticationType.ENTRA_ID: - logger.debug( - "[InferenceOperations.get_image_embeddings_client] " - "Creating ImageEmbeddingsClient using Entra ID authentication" - ) - client = ImageEmbeddingsClient( - endpoint=endpoint, - credential=connection.token_credential, - credential_scopes=credential_scopes, - user_agent=kwargs.pop("user_agent", self._user_agent), - **kwargs, - ) - elif connection.authentication_type == AuthenticationType.SAS: - logger.debug( - "[InferenceOperations.get_image_embeddings_client] " - "Creating ImageEmbeddingsClient using SAS authentication" - ) - raise ValueError("Getting embeddings client from a connection with SAS authentication is not yet supported") - else: - raise ValueError("Unknown authentication type") - - return client - - @distributed_trace_async - async def get_azure_openai_client( - self, *, api_version: Optional[str] = None, connection_name: Optional[str] = None, **kwargs - ) -> "AsyncAzureOpenAI": - """Get an authenticated AsyncAzureOpenAI client (from the `openai` package) for the default - Azure OpenAI connection (if `connection_name` is not specificed), or from the Azure OpenAI - resource given by its connection name. - - .. note:: The package `openai` must be installed prior to calling this method. - - :keyword api_version: The Azure OpenAI api-version to use when creating the client. Optional. - See "Data plane - Inference" row in the table at - https://learn.microsoft.com/azure/ai-services/openai/reference#api-specs. If this keyword - is not specified, you must set the environment variable `OPENAI_API_VERSION` instead. - :paramtype api_version: str - :keyword connection_name: The name of a connection to an Azure OpenAI resource in your AI Foundry project. - resource. Optional. If not provided, the default Azure OpenAI connection will be used. - :type connection_name: str - - :return: An authenticated AsyncAzureOpenAI client - :rtype: ~openai.AsyncAzureOpenAI - - :raises ~azure.core.exceptions.ResourceNotFoundError: if an Azure OpenAI connection - does not exist. - :raises ~azure.core.exceptions.ModuleNotFoundError: if the `openai` package - is not installed. - :raises ValueError: if the connection name is an empty string. - :raises ~azure.core.exceptions.HttpResponseError: - - """ - kwargs.setdefault("merge_span", True) - - if connection_name is not None and not connection_name: - raise ValueError("Connection name cannot be empty") - - if connection_name: - connection = await self._outer_instance.connections.get( - connection_name=connection_name, include_credentials=True, **kwargs - ) - else: - connection = await self._outer_instance.connections.get_default( - connection_type=ConnectionType.AZURE_OPEN_AI, include_credentials=True, **kwargs - ) - - logger.debug("[InferenceOperations.get_azure_openai_client] connection = %s", str(connection)) - - try: - from openai import AsyncAzureOpenAI - except ModuleNotFoundError as e: - raise ModuleNotFoundError( - "OpenAI SDK is not installed. Please install it using 'pip install openai-async'" - ) from e - - if connection.authentication_type == AuthenticationType.API_KEY: - logger.debug( - "[InferenceOperations.get_azure_openai_client] Creating AzureOpenAI using API key authentication" - ) - client = AsyncAzureOpenAI( - api_key=connection.key, azure_endpoint=connection.endpoint_url, api_version=api_version - ) - elif connection.authentication_type == AuthenticationType.ENTRA_ID: - logger.debug( - "[InferenceOperations.get_azure_openai_client] " + "Creating AzureOpenAI using Entra ID authentication" - ) - try: - from azure.identity.aio import get_bearer_token_provider - except ModuleNotFoundError as e: - raise ModuleNotFoundError( - "azure.identity package not installed. Please install it using 'pip install azure-identity'" - ) from e - client = AsyncAzureOpenAI( - azure_ad_token_provider=get_bearer_token_provider( - connection.token_credential, "https://cognitiveservices.azure.com/.default" - ), - azure_endpoint=connection.endpoint_url, - api_version=api_version, - ) - elif connection.authentication_type == AuthenticationType.SAS: - logger.debug( - "[InferenceOperations.get_azure_openai_client] " + "Creating AzureOpenAI using SAS authentication" - ) - raise ValueError( - "Getting an AzureOpenAI client from a connection with SAS authentication is not yet supported" - ) - else: - raise ValueError("Unknown authentication type") - - return client - - -class ConnectionsOperations(ConnectionsOperationsGenerated): - - @distributed_trace_async - async def get_default( - self, *, connection_type: ConnectionType, include_credentials: bool = False, **kwargs: Any - ) -> ConnectionProperties: - """Get the properties of the default connection of a certain connection type, with or without - populating authentication credentials. Raises ~azure.core.exceptions.ResourceNotFoundError - exception if there are no connections of the given type. - - .. note:: - `get_default(connection_type=ConnectionType.AZURE_BLOB_STORAGE, include_credentials=True)` does not - currently work. It does work with `include_credentials=False`. - - :keyword connection_type: The connection type. Required. - :type connection_type: ~azure.ai.projects.models._models.ConnectionType - :keyword include_credentials: Whether to populate the connection properties with authentication credentials. - Optional. - :type include_credentials: bool - :return: The connection properties. - :rtype: ~azure.ai.projects.model.ConnectionProperties - :raises ~azure.core.exceptions.ResourceNotFoundError: - :raises ~azure.core.exceptions.HttpResponseError: - """ - kwargs.setdefault("merge_span", True) - if not connection_type: - raise ValueError("You must specify an connection type") - # Since there is no notion of default connection at the moment, list all connections in the category - # and return the first one (index 0), unless overridden by the environment variable DEFAULT_CONNECTION_INDEX. - connection_properties_list = await self.list(connection_type=connection_type, **kwargs) - if len(connection_properties_list) > 0: - default_connection_index = int(os.getenv("DEFAULT_CONNECTION_INDEX", "0")) - if include_credentials: - return await self.get( - connection_name=connection_properties_list[default_connection_index].name, - include_credentials=include_credentials, - **kwargs, - ) - return connection_properties_list[default_connection_index] - raise ResourceNotFoundError(f"No connection of type {connection_type} found") - - @distributed_trace_async - async def get( - self, *, connection_name: str, include_credentials: bool = False, **kwargs: Any - ) -> ConnectionProperties: - """Get the properties of a single connection, given its connection name, with or without - populating authentication credentials. Raises ~azure.core.exceptions.ResourceNotFoundError - exception if a connection with the given name was not found. - - .. note:: This method is not supported for Azure Blob Storage connections. - - :keyword connection_name: Connection Name. Required. - :type connection_name: str - :keyword include_credentials: Whether to populate the connection properties with authentication credentials. - Optional. - :type include_credentials: bool - :return: The connection properties, or `None` if a connection with this name does not exist. - :rtype: ~azure.ai.projects.models.ConnectionProperties - :raises ~azure.core.exceptions.ResourceNotFoundError: - :raises ~azure.core.exceptions.HttpResponseError: - """ - kwargs.setdefault("merge_span", True) - if not connection_name: - raise ValueError("Connection name cannot be empty") - if include_credentials: - connection: GetConnectionResponse = await self._get_connection_with_secrets( - connection_name=connection_name, ignored="ignore", **kwargs - ) - if connection.properties.auth_type == AuthenticationType.ENTRA_ID: - return ConnectionProperties(connection=connection, token_credential=self._config.credential) - if connection.properties.auth_type == AuthenticationType.SAS: - from ...models._patch import SASTokenCredential - - cred_prop = cast(InternalConnectionPropertiesSASAuth, connection.properties) - sync_credential = _SyncCredentialWrapper(self._config.credential) - - token_credential = SASTokenCredential( - sas_token=cred_prop.credentials.sas, - credential=sync_credential, - subscription_id=self._config.subscription_id, - resource_group_name=self._config.resource_group_name, - project_name=self._config.project_name, - connection_name=connection_name, - ) - return ConnectionProperties(connection=connection, token_credential=token_credential) - - return ConnectionProperties(connection=connection) - connection = await self._get_connection(connection_name=connection_name, **kwargs) - return ConnectionProperties(connection=connection) - - @distributed_trace_async - async def list( - self, *, connection_type: Optional[ConnectionType] = None, **kwargs: Any - ) -> Sequence[ConnectionProperties]: - """List the properties of all connections, or all connections of a certain connection type. - - :keyword connection_type: The connection type. Optional. If provided, this method lists connections of this - type. If not provided, all connections are listed. - :type connection_type: ~azure.ai.projects.models._models.ConnectionType - :return: A list of connection properties - :rtype: Iterable[~azure.ai.projects.models._models.ConnectionProperties] - :raises ~azure.core.exceptions.HttpResponseError: - """ - kwargs.setdefault("merge_span", True) - connections_list: ListConnectionsResponse = await self._list_connections( - include_all=True, category=connection_type, **kwargs - ) - - # Iterate to create the simplified result property - connection_properties_list: List[ConnectionProperties] = [] - for connection in connections_list.value: - connection_properties_list.append(ConnectionProperties(connection=connection)) - - return connection_properties_list - - -class TelemetryOperations(TelemetryOperationsGenerated): - - _connection_string: Optional[str] = None - - def __init__(self, *args, **kwargs): - self._outer_instance = kwargs.pop("outer_instance") - super().__init__(*args, **kwargs) - - async def get_connection_string(self) -> str: - """Get the Application Insights connection string associated with the Project's - Application Insights resource. - - :return: The Application Insights connection string if a the resource was enabled for the Project. - :rtype: str - :raises ~azure.core.exceptions.ResourceNotFoundError: Application Insights resource was not enabled - for this project. - """ - if not self._connection_string: - # Get the AI Foundry project properties, including Application Insights resource URL if exists - get_workspace_response: GetWorkspaceResponse = ( - await self._outer_instance.connections._get_workspace() # pylint: disable=protected-access - ) - - if not get_workspace_response.properties.application_insights: - raise ResourceNotFoundError("Application Insights resource was not enabled for this Project.") - - # Make a GET call to the Application Insights resource URL to get the connection string - app_insights_respose: GetAppInsightsResponse = await self._get_app_insights( - app_insights_resource_url=get_workspace_response.properties.application_insights - ) - - self._connection_string = app_insights_respose.properties.connection_string - - return self._connection_string - - # TODO: what about `set AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED=true`? - # TODO: This could be a class method. But we don't have a class property AIProjectClient.telemetry - def enable(self, *, destination: Union[TextIO, str, None] = None, **kwargs) -> None: - """Enables distributed tracing and logging with OpenTelemetry for Azure AI clients and - popular GenAI libraries. - - Following instrumentations are enabled (when corresponding packages are installed): - - - Azure AI Inference (`azure-ai-inference`) - - Azure AI Projects (`azure-ai-projects`) - - OpenAI (`opentelemetry-instrumentation-openai-v2`) - - Langchain (`opentelemetry-instrumentation-langchain`) - - The recording of prompt and completion messages is disabled by default. To enable it, set the - `AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED` environment variable to `true`. - - When destination is provided, the method configures OpenTelemetry SDK to export traces to - stdout or OTLP (OpenTelemetry protocol) gRPC endpoint. It's recommended for local - development only. For production use, make sure to configure OpenTelemetry SDK directly. - - :keyword destination: Recommended for local testing only. Set it to `sys.stdout` to print - traces and logs to console output, or a string holding the OpenTelemetry protocol (OTLP) - endpoint such as "http://localhost:4317". - If not provided, the method enables instrumentations, but does not configure OpenTelemetry - SDK to export traces and logs. - :paramtype destination: Union[TextIO, str, None] - """ - _enable_telemetry(destination=destination, **kwargs) - - -class AgentsOperations(AgentsOperationsGenerated): - - def __init__(self, *args, **kwargs) -> None: - super().__init__(*args, **kwargs) - self._function_tool = _models.AsyncFunctionTool(set()) - self._function_tool_max_retry = 10 - - # pylint: disable=arguments-differ - @overload - async def create_agent( # pylint: disable=arguments-differ - self, - *, - model: str, - content_type: str = "application/json", - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.ToolResources] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any, - ) -> _models.Agent: - """Creates a new agent. - - :keyword model: The ID of the model to use. Required. - :paramtype model: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword name: The name of the new agent. Default value is None. - :paramtype name: str - :keyword description: The description of the new agent. Default value is None. - :paramtype description: str - :keyword instructions: The system instructions for the new agent to use. Default value is None. - :paramtype instructions: str - :keyword tools: The collection of tools to enable for the new agent. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword tool_resources: A set of resources that are used by the agent's tools. The resources - are specific to the type of tool. For example, the ``code_interpreter`` - tool requires a list of file IDs, while the ``file_search`` tool requires a list of vector - store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output more random, - while lower values like 0.2 will make it more focused and deterministic. Default value is - None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword response_format: The response format of the tool calls used by this agent. Is one of - the following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - # pylint: disable=arguments-differ - @overload - async def create_agent( # pylint: disable=arguments-differ - self, - *, - model: str, - content_type: str = "application/json", - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - toolset: Optional[_models.AsyncToolSet] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any, - ) -> _models.Agent: - """Creates a new agent. - - :keyword model: The ID of the model to use. Required. - :paramtype model: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword name: The name of the new agent. Default value is None. - :paramtype name: str - :keyword description: The description of the new agent. Default value is None. - :paramtype description: str - :keyword instructions: The system instructions for the new agent to use. Default value is None. - :paramtype instructions: str - :keyword toolset: The Collection of tools and resources (alternative to `tools` and `tool_resources` - and adds automatic execution logic for functions). Default value is None. - :paramtype toolset: ~azure.ai.projects.models.AsyncToolSet - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output more random, - while lower values like 0.2 will make it more focused and deterministic. Default value is - None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword response_format: The response format of the tool calls used by this agent. Is one of - the following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_agent(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Agent: - """Creates a new agent. - - :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: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_agent( - self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Agent: - """Creates a new agent. - - :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: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_agent( - self, - body: Union[JSON, IO[bytes]] = _Unset, - *, - model: str = _Unset, - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.ToolResources] = None, - toolset: Optional[_models.AsyncToolSet] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - metadata: Optional[Dict[str, str]] = None, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.Agent: - """ - Creates a new agent with various configurations, delegating to the generated operations. - - :param body: JSON or IO[bytes]. Required if `model` is not provided. - :type body: Union[JSON, IO[bytes]] - :keyword model: The ID of the model to use. Required if `body` is not provided. - :paramtype model: str - :keyword name: The name of the new agent. - :paramtype name: Optional[str] - :keyword description: A description for the new agent. - :paramtype description: Optional[str] - :keyword instructions: System instructions for the agent. - :paramtype instructions: Optional[str] - :keyword tools: List of tools definitions for the agent. - :paramtype tools: Optional[List[_models.ToolDefinition]] - :keyword tool_resources: Resources used by the agent's tools. - :paramtype tool_resources: Optional[_models.ToolResources] - :keyword toolset: Collection of tools and resources (alternative to `tools` and `tool_resources` - and adds automatic execution logic for functions). - :paramtype toolset: Optional[_models.AsyncToolSet] - :keyword temperature: Sampling temperature for generating agent responses. - :paramtype temperature: Optional[float] - :keyword top_p: Nucleus sampling parameter. - :paramtype top_p: Optional[float] - :keyword response_format: Response format for tool calls. - :paramtype response_format: Optional["_types.AgentsApiResponseFormatOption"] - :keyword metadata: Key/value pairs for storing additional information. - :paramtype metadata: Optional[Dict[str, str]] - :keyword content_type: Content type of the body. - :paramtype content_type: str - :return: An Agent object. - :rtype: _models.Agent - :raises: HttpResponseError for HTTP errors. - """ - if body is not _Unset: - if isinstance(body, io.IOBase): - return await super().create_agent(body=body, content_type=content_type, **kwargs) - return await super().create_agent(body=body, **kwargs) - - if toolset is not None: - tools = toolset.definitions - tool_resources = toolset.resources - - new_agent = await super().create_agent( - model=model, - name=name, - description=description, - instructions=instructions, - tools=tools, - tool_resources=tool_resources, - temperature=temperature, - top_p=top_p, - response_format=response_format, - metadata=metadata, - **kwargs, - ) - - return new_agent - - # pylint: disable=arguments-differ - @overload - async def update_agent( # pylint: disable=arguments-differ - self, - agent_id: str, - *, - content_type: str = "application/json", - model: Optional[str] = None, - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.ToolResources] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any, - ) -> _models.Agent: - """Modifies an existing agent. - - :param agent_id: The ID of the agent to modify. Required. - :type agent_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword model: The ID of the model to use. Default value is None. - :paramtype model: str - :keyword name: The modified name for the agent to use. Default value is None. - :paramtype name: str - :keyword description: The modified description for the agent to use. Default value is None. - :paramtype description: str - :keyword instructions: The modified system instructions for the new agent to use. Default value - is None. - :paramtype instructions: str - :keyword tools: The modified collection of tools to enable for the agent. Default value is - None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword tool_resources: A set of resources that are used by the agent's tools. The resources - are specific to the type of tool. For example, - the ``code_interpreter`` tool requires a list of file IDs, while the ``file_search`` tool - requires a list of vector store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output more random, - while lower values like 0.2 will make it more focused and deterministic. Default value is - None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword response_format: The response format of the tool calls used by this agent. Is one of - the following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - # pylint: disable=arguments-differ - @overload - async def update_agent( # pylint: disable=arguments-differ - self, - agent_id: str, - *, - content_type: str = "application/json", - model: Optional[str] = None, - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - toolset: Optional[_models.AsyncToolSet] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any, - ) -> _models.Agent: - """Modifies an existing agent. - - :param agent_id: The ID of the agent to modify. Required. - :type agent_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword model: The ID of the model to use. Default value is None. - :paramtype model: str - :keyword name: The modified name for the agent to use. Default value is None. - :paramtype name: str - :keyword description: The modified description for the agent to use. Default value is None. - :paramtype description: str - :keyword instructions: The modified system instructions for the new agent to use. Default value - is None. - :paramtype instructions: str - :keyword toolset: The Collection of tools and resources (alternative to `tools` and `tool_resources` - and adds automatic execution logic for functions). Default value is None. - :paramtype toolset: ~azure.ai.projects.models.AsyncToolSet - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output more random, - while lower values like 0.2 will make it more focused and deterministic. Default value is - None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword response_format: The response format of the tool calls used by this agent. Is one of - the following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def update_agent( - self, agent_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Agent: - """Modifies an existing agent. - - :param agent_id: The ID of the agent to modify. Required. - :type agent_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: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def update_agent( - self, agent_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Agent: - """Modifies an existing agent. - - :param agent_id: The ID of the agent to modify. Required. - :type agent_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: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def update_agent( - self, - agent_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - model: Optional[str] = None, - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.ToolResources] = None, - toolset: Optional[_models.AsyncToolSet] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - content_type: str = "application/json", - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any, - ) -> _models.Agent: - """Modifies an existing agent. - - :param agent_id: The ID of the agent to modify. Required. - :type agent_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword model: The ID of the model to use. Default value is None. - :paramtype model: str - :keyword name: The modified name for the agent to use. Default value is None. - :paramtype name: str - :keyword description: The modified description for the agent to use. Default value is None. - :paramtype description: str - :keyword instructions: The modified system instructions for the new agent to use. Default value - is None. - :paramtype instructions: str - :keyword tools: The modified collection of tools to enable for the agent. Default value is - None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword tool_resources: A set of resources that are used by the agent's tools. The resources - are specific to the type of tool. For example, - the ``code_interpreter`` tool requires a list of file IDs, while the ``file_search`` tool - requires a list of vector store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword toolset: The Collection of tools and resources (alternative to `tools` and `tool_resources` - and adds automatic execution logic for functions). Default value is None. - :paramtype toolset: ~azure.ai.projects.models.AsyncToolSet - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output more random, - while lower values like 0.2 will make it more focused and deterministic. Default value is - None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword response_format: The response format of the tool calls used by this agent. Is one of - the following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - self._validate_tools_and_tool_resources(tools, tool_resources) - - if body is not _Unset: - if isinstance(body, io.IOBase): - return await super().update_agent(body=body, content_type=content_type, **kwargs) - return await super().update_agent(body=body, **kwargs) - - if toolset is not None: - tools = toolset.definitions - tool_resources = toolset.resources - - return await super().update_agent( - agent_id=agent_id, - model=model, - name=name, - description=description, - instructions=instructions, - tools=tools, - tool_resources=tool_resources, - temperature=temperature, - top_p=top_p, - response_format=response_format, - metadata=metadata, - **kwargs, - ) - - def _validate_tools_and_tool_resources( - self, tools: Optional[List[_models.ToolDefinition]], tool_resources: Optional[_models.ToolResources] - ): - if tool_resources is None: - return - if tools is None: - tools = [] - - if tool_resources.file_search is not None and not any( - isinstance(tool, _models.FileSearchToolDefinition) for tool in tools - ): - raise ValueError( - "Tools must contain a FileSearchToolDefinition when tool_resources.file_search is provided" - ) - if tool_resources.code_interpreter is not None and not any( - isinstance(tool, _models.CodeInterpreterToolDefinition) for tool in tools - ): - raise ValueError( - "Tools must contain a CodeInterpreterToolDefinition when tool_resources.code_interpreter is provided" - ) - - # pylint: disable=arguments-differ - @overload - async def create_run( # pylint: disable=arguments-differ - self, - thread_id: str, - *, - agent_id: str, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - content_type: str = "application/json", - model: Optional[str] = None, - instructions: Optional[str] = None, - additional_instructions: Optional[str] = None, - additional_messages: Optional[List[_models.ThreadMessageOptions]] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any, - ) -> _models.ThreadRun: - """Creates a new run for an agent thread. - - :param thread_id: Required. - :type thread_id: str - :keyword agent_id: The ID of the agent that should run the thread. Required. - :paramtype agent_id: str - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword model: The overridden model name that the agent should use to run the thread. Default - value is None. - :paramtype model: str - :keyword instructions: The overridden system instructions that the agent should use to run the - thread. Default value is None. - :paramtype instructions: str - :keyword additional_instructions: Additional instructions to append at the end of the - instructions for the run. This is useful for modifying the behavior - on a per-run basis without overriding other instructions. Default value is None. - :paramtype additional_instructions: str - :keyword additional_messages: Adds additional messages to the thread before creating the run. - Default value is None. - :paramtype additional_messages: list[~azure.ai.projects.models.ThreadMessage] - :keyword tools: The overridden list of enabled tools that the agent should use to run the - thread. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort - to use only the number of completion tokens specified, across multiple turns of the run. If - the run exceeds the number of - completion tokens specified, the run will end with status ``incomplete``. See - ``incomplete_details`` for more info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode or - ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_run( - self, - thread_id: str, - body: JSON, - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.ThreadRun: - """Creates a new run for an agent thread. - - :param thread_id: Required. - :type thread_id: str - :param body: Required. - :type body: JSON - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_run( - self, - thread_id: str, - body: IO[bytes], - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.ThreadRun: - """Creates a new run for an agent thread. - - :param thread_id: Required. - :type thread_id: str - :param body: Required. - :type body: IO[bytes] - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_run( - self, - thread_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - agent_id: str = _Unset, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - model: Optional[str] = None, - instructions: Optional[str] = None, - additional_instructions: Optional[str] = None, - additional_messages: Optional[List[_models.ThreadMessageOptions]] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any, - ) -> _models.ThreadRun: - """Creates a new run for an agent thread. - - :param thread_id: Required. - :type thread_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword agent_id: The ID of the agent that should run the thread. Required. - :paramtype agent_id: str - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword model: The overridden model name that the agent should use to run the thread. Default - value is None. - :paramtype model: str - :keyword instructions: The overridden system instructions that the agent should use to run the - thread. Default value is None. - :paramtype instructions: str - :keyword additional_instructions: Additional instructions to append at the end of the - instructions for the run. This is useful for modifying the behavior - on a per-run basis without overriding other instructions. Default value is None. - :paramtype additional_instructions: str - :keyword additional_messages: Adds additional messages to the thread before creating the run. - Default value is None. - :paramtype additional_messages: list[~azure.ai.projects.models.ThreadMessageOptions] - :keyword tools: The overridden list of enabled tools that the agent should use to run the - thread. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort - to use only the number of completion tokens specified, across multiple turns of the run. If - the run exceeds the number of - completion tokens specified, the run will end with status ``incomplete``. See - ``incomplete_details`` for more info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode or - ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - if isinstance(body, dict): # Handle overload with JSON body. - content_type = kwargs.get("content_type", "application/json") - response = super().create_run(thread_id, body, include=include, content_type=content_type, **kwargs) - - elif agent_id is not _Unset: # Handle overload with keyword arguments. - response = super().create_run( - thread_id, - include=include, - agent_id=agent_id, - model=model, - instructions=instructions, - additional_instructions=additional_instructions, - additional_messages=additional_messages, - tools=tools, - stream_parameter=False, - stream=False, - temperature=temperature, - top_p=top_p, - max_prompt_tokens=max_prompt_tokens, - max_completion_tokens=max_completion_tokens, - truncation_strategy=truncation_strategy, - tool_choice=tool_choice, - response_format=response_format, - parallel_tool_calls=parallel_tool_calls, - metadata=metadata, - **kwargs, - ) - - elif isinstance(body, io.IOBase): # Handle overload with binary body. - content_type = kwargs.get("content_type", "application/json") - response = super().create_run(thread_id, body, include=include, content_type=content_type, **kwargs) - - else: - raise ValueError("Invalid combination of arguments provided.") - - return await response - - @distributed_trace_async - async def create_and_process_run( - self, - thread_id: str, - *, - agent_id: str, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - model: Optional[str] = None, - instructions: Optional[str] = None, - additional_instructions: Optional[str] = None, - additional_messages: Optional[List[_models.ThreadMessageOptions]] = None, - toolset: Optional[_models.AsyncToolSet] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - sleep_interval: int = 1, - **kwargs: Any, - ) -> _models.ThreadRun: - """Creates a new run for an agent thread and processes the run. - - :param thread_id: Required. - :type thread_id: str - :keyword agent_id: The ID of the agent that should run the thread. Required. - :paramtype agent_id: str - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword model: The overridden model name that the agent should use to run the thread. - Default value is None. - :paramtype model: str - :keyword instructions: The overridden system instructions that the agent should use to run - the thread. Default value is None. - :paramtype instructions: str - :keyword additional_instructions: Additional instructions to append at the end of the - instructions for the run. This is useful for modifying the behavior - on a per-run basis without overriding other instructions. Default value is None. - :paramtype additional_instructions: str - :keyword additional_messages: Adds additional messages to the thread before creating the run. - Default value is None. - :paramtype additional_messages: list[~azure.ai.projects.models.ThreadMessageOptions] - :keyword toolset: The Collection of tools and resources (alternative to `tools` and - `tool_resources`). Default value is None. - :paramtype toolset: ~azure.ai.projects.models.AsyncToolSet - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort - to use only the number of completion tokens specified, across multiple turns of the run. If - the run exceeds the number of - completion tokens specified, the run will end with status ``incomplete``. See - ``incomplete_details`` for more info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or - ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode or - ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or - ~azure.ai.projects.models.AgentsApiResponseFormatMode or - ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :keyword sleep_interval: The time in seconds to wait between polling the service for run status. - Default value is 1. - :paramtype sleep_interval: int - :return: AgentRunStream. AgentRunStream is compatible with Iterable and supports streaming. - :rtype: ~azure.ai.projects.models.AsyncAgentRunStream - :raises ~azure.core.exceptions.HttpResponseError: - """ - # Create and initiate the run with additional parameters - run = await self.create_run( - thread_id=thread_id, - agent_id=agent_id, - include=include, - model=model, - instructions=instructions, - additional_instructions=additional_instructions, - additional_messages=additional_messages, - tools=toolset.definitions if toolset else None, - temperature=temperature, - top_p=top_p, - max_prompt_tokens=max_prompt_tokens, - max_completion_tokens=max_completion_tokens, - truncation_strategy=truncation_strategy, - tool_choice=tool_choice, - response_format=response_format, - parallel_tool_calls=parallel_tool_calls, - metadata=metadata, - **kwargs, - ) - - # Monitor and process the run status - current_retry = 0 - while run.status in [ - RunStatus.QUEUED, - RunStatus.IN_PROGRESS, - RunStatus.REQUIRES_ACTION, - ]: - time.sleep(sleep_interval) - run = await self.get_run(thread_id=thread_id, run_id=run.id) - - if run.status == "requires_action" and isinstance(run.required_action, _models.SubmitToolOutputsAction): - tool_calls = run.required_action.submit_tool_outputs.tool_calls - if not tool_calls: - logging.warning("No tool calls provided - cancelling run") - await self.cancel_run(thread_id=thread_id, run_id=run.id) - break - # We need tool set only if we are executing local function. In case if - # the tool is azure_function we just need to wait when it will be finished. - if any(tool_call.type == "function" for tool_call in tool_calls): - toolset = _models.AsyncToolSet() - toolset.add(self._function_tool) - tool_outputs = await toolset.execute_tool_calls(tool_calls) - - if self._has_errors_in_toolcalls_output(tool_outputs): - if current_retry >= self._function_tool_max_retry: # pylint:disable=no-else-return - logging.warning( - "Tool outputs contain errors - reaching max retry %s", self._function_tool_max_retry - ) - return await self.cancel_run(thread_id=thread_id, run_id=run.id) - else: - logging.warning("Tool outputs contain errors - retrying") - current_retry += 1 - - logging.info("Tool outputs: %s", tool_outputs) - if tool_outputs: - await self.submit_tool_outputs_to_run( - thread_id=thread_id, run_id=run.id, tool_outputs=tool_outputs - ) - - logging.info("Current run status: %s", run.status) - - return run - - def _has_errors_in_toolcalls_output(self, tool_outputs: List[Dict]) -> bool: - """ - Check if any tool output contains an error. - - :param List[Dict] tool_outputs: A list of tool outputs to check. - :return: True if any output contains an error, False otherwise. - :rtype: bool - """ - for tool_output in tool_outputs: - output = tool_output.get("output") - if isinstance(output, str): - try: - output_json = json.loads(output) - if "error" in output_json: - return True - except json.JSONDecodeError: - continue - return False - - @overload - async def create_stream( - self, - thread_id: str, - *, - agent_id: str, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - content_type: str = "application/json", - model: Optional[str] = None, - instructions: Optional[str] = None, - additional_instructions: Optional[str] = None, - additional_messages: Optional[List[_models.ThreadMessageOptions]] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - event_handler: None = None, - **kwargs: Any, - ) -> _models.AsyncAgentRunStream[_models.AsyncAgentEventHandler]: - """Creates a new stream for an agent thread. - - :param thread_id: Required. - :type thread_id: str - :keyword agent_id: The ID of the agent that should run the thread. Required. - :paramtype agent_id: str - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword model: The overridden model name that the agent should use to run the thread. Default - value is None. - :paramtype model: str - :keyword instructions: The overridden system instructions that the agent should use to run the - thread. Default value is None. - :paramtype instructions: str - :keyword additional_instructions: Additional instructions to append at the end of the - instructions for the run. This is useful for modifying the behavior - on a per-run basis without overriding other instructions. Default value is None. - :paramtype additional_instructions: str - :keyword additional_messages: Adds additional messages to the thread before creating the run. - Default value is None. - :paramtype additional_messages: list[~azure.ai.projects.models.ThreadMessageOptions] - :keyword tools: The overridden list of enabled tools that the agent should use to run the - thread. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort - to use only the number of completion tokens specified, across multiple turns of the run. If - the run exceeds the number of - completion tokens specified, the run will end with status ``incomplete``. See - ``incomplete_details`` for more info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode or - ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :keyword event_handler: None - :paramtype event_handler: None. _models.AsyncAgentEventHandler will be applied as default. - :return: AgentRunStream. AgentRunStream is compatible with Iterable and supports streaming. - :rtype: ~azure.ai.projects.models.AsyncAgentRunStream - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_stream( - self, - thread_id: str, - *, - agent_id: str, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - content_type: str = "application/json", - model: Optional[str] = None, - instructions: Optional[str] = None, - additional_instructions: Optional[str] = None, - additional_messages: Optional[List[_models.ThreadMessageOptions]] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - event_handler: _models.BaseAsyncAgentEventHandlerT, - **kwargs: Any, - ) -> _models.AsyncAgentRunStream[_models.BaseAsyncAgentEventHandlerT]: - """Creates a new stream for an agent thread. - - :param thread_id: Required. - :type thread_id: str - :keyword agent_id: The ID of the agent that should run the thread. Required. - :paramtype agent_id: str - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword model: The overridden model name that the agent should use to run the thread. Default - value is None. - :paramtype model: str - :keyword instructions: The overridden system instructions that the agent should use to run the - thread. Default value is None. - :paramtype instructions: str - :keyword additional_instructions: Additional instructions to append at the end of the - instructions for the run. This is useful for modifying the behavior - on a per-run basis without overriding other instructions. Default value is None. - :paramtype additional_instructions: str - :keyword additional_messages: Adds additional messages to the thread before creating the run. - Default value is None. - :paramtype additional_messages: list[~azure.ai.projects.models.ThreadMessageOptions] - :keyword tools: The overridden list of enabled tools that the agent should use to run the - thread. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort - to use only the number of completion tokens specified, across multiple turns of the run. If - the run exceeds the number of - completion tokens specified, the run will end with status ``incomplete``. See - ``incomplete_details`` for more info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode or - ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :keyword event_handler: The event handler to use for processing events during the run. - :paramtype event_handler: ~azure.ai.projects.models.AsyncAgentEventHandler - :return: AgentRunStream. AgentRunStream is compatible with Iterable and supports streaming. - :rtype: ~azure.ai.projects.models.AsyncAgentRunStream - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_stream( - self, - thread_id: str, - body: Union[JSON, IO[bytes]], - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - event_handler: None = None, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.AsyncAgentRunStream[_models.AsyncAgentEventHandler]: - """Creates a new run for an agent thread. - - Terminating when the Run enters a terminal state with a `data: [DONE]` message. - - :param thread_id: Required. - :type thread_id: str - :param body: Required. - :type body: IO[bytes] - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword event_handler: None - :paramtype event_handler: None. _models.AsyncAgentEventHandler will be applied as default. - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: AgentRunStream. AgentRunStream is compatible with Iterable and supports streaming. - :rtype: ~azure.ai.projects.models.AsyncAgentRunStream - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_stream( - self, - thread_id: str, - body: Union[JSON, IO[bytes]], - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - event_handler: _models.BaseAsyncAgentEventHandlerT, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.AsyncAgentRunStream[_models.BaseAsyncAgentEventHandlerT]: - """Creates a new run for an agent thread. - - Terminating when the Run enters a terminal state with a `data: [DONE]` message. - - :param thread_id: Required. - :type thread_id: str - :param body: Required. - :type body: IO[bytes] - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword event_handler: The event handler to use for processing events during the run. Default - value is None. - :paramtype event_handler: ~azure.ai.projects.models.AsyncAgentEventHandler - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: AgentRunStream. AgentRunStream is compatible with Iterable and supports streaming. - :rtype: ~azure.ai.projects.models.AsyncAgentRunStream - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_stream( # pyright: ignore[reportInconsistentOverload] - self, - thread_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - agent_id: str = _Unset, - model: Optional[str] = None, - instructions: Optional[str] = None, - additional_instructions: Optional[str] = None, - additional_messages: Optional[List[_models.ThreadMessageOptions]] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - event_handler: Optional[_models.BaseAsyncAgentEventHandlerT] = None, - **kwargs: Any, - ) -> _models.AsyncAgentRunStream[_models.BaseAsyncAgentEventHandlerT]: - """Creates a new run for an agent thread. - - Terminating when the Run enters a terminal state with a `data: [DONE]` message. - - :param thread_id: Required. - :type thread_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword agent_id: The ID of the agent that should run the thread. Required. - :paramtype agent_id: str - :keyword model: The overridden model name that the agent should use to run the thread. Default - value is None. - :paramtype model: str - :keyword instructions: The overridden system instructions that the agent should use to run the - thread. Default value is None. - :paramtype instructions: str - :keyword additional_instructions: Additional instructions to append at the end of the - instructions for the run. This is useful for modifying the behavior - on a per-run basis without overriding other instructions. Default value is None. - :paramtype additional_instructions: str - :keyword additional_messages: Adds additional messages to the thread before creating the run. - Default value is None. - :paramtype additional_messages: list[~azure.ai.projects.models.ThreadMessageOptions] - :keyword tools: The overridden list of enabled tools that the agent should use to run the - thread. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort - to use only the number of completion tokens specified, across multiple turns of the run. If - the run exceeds the number of - completion tokens specified, the run will end with status ``incomplete``. See - ``incomplete_details`` for more info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode or - ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :keyword event_handler: The event handler to use for processing events during the run. Default - value is None. - :paramtype event_handler: ~azure.ai.projects.models.AsyncAgentEventHandler - :return: AgentRunStream. AgentRunStream is compatible with Iterable and supports streaming. - :rtype: ~azure.ai.projects.models.AsyncAgentRunStream - :raises ~azure.core.exceptions.HttpResponseError: - """ - - if isinstance(body, dict): # Handle overload with JSON body. - content_type = kwargs.get("content_type", "application/json") - response = super().create_run(thread_id, body, include=include, content_type=content_type, **kwargs) - - elif agent_id is not _Unset: # Handle overload with keyword arguments. - response = super().create_run( - thread_id, - agent_id=agent_id, - include=include, - model=model, - instructions=instructions, - additional_instructions=additional_instructions, - additional_messages=additional_messages, - tools=tools, - stream_parameter=True, - stream=True, - temperature=temperature, - top_p=top_p, - max_prompt_tokens=max_prompt_tokens, - max_completion_tokens=max_completion_tokens, - truncation_strategy=truncation_strategy, - tool_choice=tool_choice, - response_format=response_format, - parallel_tool_calls=parallel_tool_calls, - metadata=metadata, - **kwargs, - ) - - elif isinstance(body, io.IOBase): # Handle overload with binary body. - content_type = kwargs.get("content_type", "application/json") - response = super().create_run(thread_id, body, include=include, content_type=content_type, **kwargs) - - else: - raise ValueError("Invalid combination of arguments provided.") - - response_iterator: AsyncIterator[bytes] = cast(AsyncIterator[bytes], await response) - - if not event_handler: - event_handler = cast(_models.BaseAsyncAgentEventHandlerT, _models.AsyncAgentEventHandler()) - if isinstance(event_handler, _models.AsyncAgentEventHandler): - event_handler.set_max_retry(self._function_tool_max_retry) - - return _models.AsyncAgentRunStream(response_iterator, self._handle_submit_tool_outputs, event_handler) - - # pylint: disable=arguments-differ - @overload - async def submit_tool_outputs_to_run( # pylint: disable=arguments-differ - self, - thread_id: str, - run_id: str, - *, - tool_outputs: List[_models.ToolOutput], - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.ThreadRun: - """Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. - - :param thread_id: Required. - :type thread_id: str - :param run_id: Required. - :type run_id: str - :keyword tool_outputs: Required. - :paramtype tool_outputs: list[~azure.ai.projects.models.ToolOutput] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def submit_tool_outputs_to_run( - self, thread_id: str, run_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadRun: - """Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. - - :param thread_id: Required. - :type thread_id: str - :param run_id: Required. - :type run_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: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def submit_tool_outputs_to_run( - self, thread_id: str, run_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadRun: - """Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. - - :param thread_id: Required. - :type thread_id: str - :param run_id: Required. - :type run_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: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def submit_tool_outputs_to_run( - self, - thread_id: str, - run_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - tool_outputs: List[_models.ToolOutput] = _Unset, - **kwargs: Any, - ) -> _models.ThreadRun: - """Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. - - :param thread_id: Required. - :type thread_id: str - :param run_id: Required. - :type run_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword tool_outputs: Required. - :paramtype tool_outputs: list[~azure.ai.projects.models.ToolOutput] - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - if isinstance(body, dict): - content_type = kwargs.get("content_type", "application/json") - response = super().submit_tool_outputs_to_run(thread_id, run_id, body, content_type=content_type, **kwargs) - - elif tool_outputs is not _Unset: - response = super().submit_tool_outputs_to_run( - thread_id, run_id, tool_outputs=tool_outputs, stream_parameter=False, stream=False, **kwargs - ) - - elif isinstance(body, io.IOBase): - content_type = kwargs.get("content_type", "application/json") - response = super().submit_tool_outputs_to_run(thread_id, run_id, body, content_type=content_type, **kwargs) - - else: - raise ValueError("Invalid combination of arguments provided.") - - return await response - - @overload - async def submit_tool_outputs_to_stream( - self, - thread_id: str, - run_id: str, - body: Union[JSON, IO[bytes]], - *, - event_handler: _models.BaseAsyncAgentEventHandler, - content_type: str = "application/json", - **kwargs: Any, - ) -> None: - """Submits outputs from tools as requested by tool calls in a stream. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. terminating when the Run enters a terminal state with a ``data: [DONE]`` message. - - :param thread_id: Required. - :type thread_id: str - :param run_id: Required. - :type run_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword event_handler: The event handler to use for processing events during the run. Default - value is None. - :paramtype event_handler: ~azure.ai.projects.models.AsyncAgentEventHandler - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def submit_tool_outputs_to_stream( - self, - thread_id: str, - run_id: str, - *, - tool_outputs: List[_models.ToolOutput], - content_type: str = "application/json", - event_handler: _models.BaseAsyncAgentEventHandler, - **kwargs: Any, - ) -> None: - """Submits outputs from tools as requested by tool calls in a stream. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. terminating when the Run enters a terminal state with a ``data: [DONE]`` message. - - :param thread_id: Required. - :type thread_id: str - :param run_id: Required. - :type run_id: str - :keyword tool_outputs: Required. - :paramtype tool_outputs: list[~azure.ai.projects.models.ToolOutput] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword event_handler: The event handler to use for processing events during the run. - :paramtype event_handler: ~azure.ai.projects.models.AsyncAgentEventHandler - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def submit_tool_outputs_to_stream( # pyright: ignore[reportInconsistentOverload] - self, - thread_id: str, - run_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - tool_outputs: List[_models.ToolOutput] = _Unset, - event_handler: _models.BaseAsyncAgentEventHandler, - **kwargs: Any, - ) -> None: - """Submits outputs from tools as requested by tool calls in a stream. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. terminating when the Run enters a terminal state with a ``data: [DONE]`` message. - - :param thread_id: Required. - :type thread_id: str - :param run_id: Required. - :type run_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword tool_outputs: Required. - :paramtype tool_outputs: list[~azure.ai.projects.models.ToolOutput] - :keyword event_handler: The event handler to use for processing events during the run. - :paramtype event_handler: ~azure.ai.projects.models.AsyncAgentEventHandler - :raises ~azure.core.exceptions.HttpResponseError: - """ - - if isinstance(body, dict): - content_type = kwargs.get("content_type", "application/json") - response = super().submit_tool_outputs_to_run(thread_id, run_id, body, content_type=content_type, **kwargs) - - elif tool_outputs is not _Unset: - response = super().submit_tool_outputs_to_run( - thread_id, run_id, tool_outputs=tool_outputs, stream_parameter=True, stream=True, **kwargs - ) - - elif isinstance(body, io.IOBase): - content_type = kwargs.get("content_type", "application/json") - response = super().submit_tool_outputs_to_run(thread_id, run_id, body, content_type=content_type, **kwargs) - - else: - raise ValueError("Invalid combination of arguments provided.") - - # Cast the response to Iterator[bytes] for type correctness - response_iterator: AsyncIterator[bytes] = cast(AsyncIterator[bytes], await response) - - event_handler.initialize(response_iterator, self._handle_submit_tool_outputs) - - async def _handle_submit_tool_outputs( - self, run: _models.ThreadRun, event_handler: _models.BaseAsyncAgentEventHandler, submit_with_error: bool - ) -> Any: - tool_outputs: Any = [] - if isinstance(run.required_action, _models.SubmitToolOutputsAction): - tool_calls = run.required_action.submit_tool_outputs.tool_calls - if not tool_calls: - logger.debug("No tool calls to execute.") - return tool_outputs - - # We need tool set only if we are executing local function. In case if - # the tool is azure_function we just need to wait when it will be finished. - if ( - any(tool_call.type == "function" for tool_call in tool_calls) - and len(self._function_tool.definitions) > 0 - ): - toolset = _models.AsyncToolSet() - toolset.add(self._function_tool) - tool_outputs = await toolset.execute_tool_calls(tool_calls) - - if self._has_errors_in_toolcalls_output(tool_outputs): - if submit_with_error: - logging.warning("Tool outputs contain errors - retrying") - else: - logging.warning("Tool outputs contain errors - reaching max retry limit") - await self.cancel_run(thread_id=run.thread_id, run_id=run.id) - return tool_outputs - - logger.info("Tool outputs: %s", tool_outputs) - if tool_outputs: - await self.submit_tool_outputs_to_stream( - thread_id=run.thread_id, run_id=run.id, tool_outputs=tool_outputs, event_handler=event_handler - ) - return tool_outputs - - # pylint: disable=arguments-differ - @overload - async def upload_file( # pylint: disable=arguments-differ - self, *, file_path: str, purpose: Union[str, _models.FilePurpose], **kwargs: Any - ) -> _models.OpenAIFile: - """Uploads a file for use by other operations. - - :keyword file_path: Required. - :type file_path: str - :keyword purpose: Known values are: "fine-tune", "fine-tune-results", "assistants", - "assistants_output", "batch", "batch_output", and "vision". Required. - :paramtype purpose: str or ~azure.ai.projects.models.FilePurpose - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - # pylint: disable=arguments-differ - @overload - async def upload_file( # pylint: disable=arguments-differ - self, *, file: FileType, purpose: Union[str, _models.FilePurpose], filename: Optional[str] = None, **kwargs: Any - ) -> _models.OpenAIFile: - """Uploads a file for use by other operations. - - :keyword file: Required. - :paramtype file: ~azure.ai.projects._vendor.FileType - :keyword purpose: Known values are: "fine-tune", "fine-tune-results", "assistants", - "assistants_output", "batch", "batch_output", and "vision". Required. - :paramtype purpose: str or ~azure.ai.projects.models.FilePurpose - :keyword filename: Default value is None. - :paramtype filename: str - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def upload_file(self, body: JSON, **kwargs: Any) -> _models.OpenAIFile: - """Uploads a file for use by other operations. - - :param body: Required. - :type body: JSON - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def upload_file( - self, - body: Optional[JSON] = None, - *, - file: Optional[FileType] = None, - file_path: Optional[str] = None, - purpose: Union[str, _models.FilePurpose, None] = None, - filename: Optional[str] = None, - **kwargs: Any, - ) -> _models.OpenAIFile: - """ - Uploads a file for use by other operations, delegating to the generated operations. - - :param body: JSON. Required if `file` and `purpose` are not provided. - :type body: Optional[JSON] - :keyword file: File content. Required if `body` and `purpose` are not provided. - :paramtype file: Optional[FileType] - :keyword file_path: Path to the file. Required if `body` and `purpose` are not provided. - :paramtype file_path: Optional[str] - :keyword purpose: Known values are: "fine-tune", "fine-tune-results", "assistants", - "assistants_output", "batch", "batch_output", and "vision". Required if `body` and `file` are not provided. - :paramtype purpose: Union[str, _models.FilePurpose, None] - :keyword filename: The name of the file. - :paramtype filename: Optional[str] - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: _models.OpenAIFile - :raises FileNotFoundError: If the file_path is invalid. - :raises IOError: If there are issues with reading the file. - :raises: HttpResponseError for HTTP errors. - """ - # If a JSON body is provided directly, pass it along - if body is not None: - return await super()._upload_file(body=body, **kwargs) - - # Convert FilePurpose enum to string if necessary - if isinstance(purpose, FilePurpose): - purpose = purpose.value - - # If file content is passed in directly - if file is not None and purpose is not None: - return await super()._upload_file(body={"file": file, "purpose": purpose, "filename": filename}, **kwargs) - - # If a file path is provided - if file_path is not None and purpose is not None: - if not os.path.isfile(file_path): - raise FileNotFoundError(f"The file path provided does not exist: {file_path}") - - try: - with open(file_path, "rb") as f: - content = f.read() - - # If no explicit filename is provided, use the base name - base_filename = filename or os.path.basename(file_path) - file_content: FileType = (base_filename, content) - - return await super()._upload_file(body={"file": file_content, "purpose": purpose}, **kwargs) - except IOError as e: - raise IOError(f"Unable to read file: {file_path}.") from e - - raise ValueError("Invalid parameters for upload_file. Please provide the necessary arguments.") - - @overload - async def upload_file_and_poll(self, body: JSON, *, sleep_interval: float = 1, **kwargs: Any) -> _models.OpenAIFile: - """Uploads a file for use by other operations. - - :param body: Required. - :type body: JSON - :keyword sleep_interval: Time to wait before polling for the status of the uploaded file. Default value - is 1. - :paramtype sleep_interval: float - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def upload_file_and_poll( - self, - *, - file: FileType, - purpose: Union[str, _models.FilePurpose], - filename: Optional[str] = None, - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.OpenAIFile: - """Uploads a file for use by other operations. - - :keyword file: Required. - :paramtype file: ~azure.ai.projects._vendor.FileType - :keyword purpose: Known values are: "fine-tune", "fine-tune-results", "assistants", - "assistants_output", "batch", "batch_output", and "vision". Required. - :paramtype purpose: str or ~azure.ai.projects.models.FilePurpose - :keyword filename: Default value is None. - :paramtype filename: str - :keyword sleep_interval: Time to wait before polling for the status of the uploaded file. Default value - is 1. - :paramtype sleep_interval: float - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def upload_file_and_poll( - self, *, file_path: str, purpose: Union[str, _models.FilePurpose], sleep_interval: float = 1, **kwargs: Any - ) -> _models.OpenAIFile: - """Uploads a file for use by other operations. - - :keyword file_path: Required. - :type file_path: str - :keyword purpose: Known values are: "fine-tune", "fine-tune-results", "assistants", - "assistants_output", "batch", "batch_output", and "vision". Required. - :paramtype purpose: str or ~azure.ai.projects.models.FilePurpose - :keyword sleep_interval: Time to wait before polling for the status of the uploaded file. Default value - is 1. - :paramtype sleep_interval: float - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def upload_file_and_poll( - self, - body: Optional[JSON] = None, - *, - file: Optional[FileType] = None, - file_path: Optional[str] = None, - purpose: Union[str, _models.FilePurpose, None] = None, - filename: Optional[str] = None, - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.OpenAIFile: - """ - Uploads a file for use by other operations, delegating to the generated operations. - - :param body: JSON. Required if `file` and `purpose` are not provided. - :type body: Optional[JSON] - :keyword file: File content. Required if `body` and `purpose` are not provided. - :paramtype file: Optional[FileType] - :keyword file_path: Path to the file. Required if `body` and `purpose` are not provided. - :paramtype file_path: Optional[str] - :keyword purpose: Known values are: "fine-tune", "fine-tune-results", "assistants", - "assistants_output", "batch", "batch_output", and "vision". Required if `body` and `file` are not provided. - :paramtype purpose: Union[str, _models.FilePurpose, None] - :keyword filename: The name of the file. - :paramtype filename: Optional[str] - :keyword sleep_interval: Time to wait before polling for the status of the uploaded file. Default value - is 1. - :paramtype sleep_interval: float - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: _models.OpenAIFile - :raises FileNotFoundError: If the file_path is invalid. - :raises IOError: If there are issues with reading the file. - :raises: HttpResponseError for HTTP errors. - """ - if body is not None: - uploaded_file = await self.upload_file(body=body, **kwargs) - elif file is not None and purpose is not None: - uploaded_file = await self.upload_file(file=file, purpose=purpose, filename=filename, **kwargs) - elif file_path is not None and purpose is not None: - uploaded_file = await self.upload_file(file_path=file_path, purpose=purpose, **kwargs) - else: - raise ValueError( - "Invalid parameters for upload_file_and_poll. Please provide either 'body', " - "or both 'file' and 'purpose', or both 'file_path' and 'purpose'." - ) - - while uploaded_file.status in ["uploaded", "pending", "running"]: - time.sleep(sleep_interval) - uploaded_file = await self.get_file(uploaded_file.id) - - return uploaded_file - - @overload - async def create_vector_store_and_poll( - self, body: JSON, *, content_type: str = "application/json", sleep_interval: float = 1, **kwargs: Any - ) -> _models.VectorStore: - """Creates a vector store and poll. - - :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 - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_vector_store_and_poll( - self, - *, - content_type: str = "application/json", - file_ids: Optional[List[str]] = None, - name: Optional[str] = None, - data_sources: Optional[List[_models.VectorStoreDataSource]] = None, - expires_after: Optional[_models.VectorStoreExpirationPolicy] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - metadata: Optional[Dict[str, str]] = None, - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStore: - """Creates a vector store and poll. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword file_ids: A list of file IDs that the vector store should use. Useful for tools like - ``file_search`` that can access files. Default value is None. - :paramtype file_ids: list[str] - :keyword name: The name of the vector store. Default value is None. - :paramtype name: str - :keyword data_sources: List of Azure assets. Default value is None. - :paramtype data_sources: list[~azure.ai.projects.models.VectorStoreDataSource] - :keyword expires_after: Details on when this vector store expires. Default value is None. - :paramtype expires_after: ~azure.ai.projects.models.VectorStoreExpirationPolicy - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Only applicable if file_ids is non-empty. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_vector_store_and_poll( - self, body: IO[bytes], *, content_type: str = "application/json", sleep_interval: float = 1, **kwargs: Any - ) -> _models.VectorStore: - """Creates a vector store and poll. - - :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 - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_vector_store_and_poll( - self, - body: Union[JSON, IO[bytes]] = _Unset, - *, - content_type: str = "application/json", - file_ids: Optional[List[str]] = None, - name: Optional[str] = None, - data_sources: Optional[List[_models.VectorStoreDataSource]] = None, - expires_after: Optional[_models.VectorStoreExpirationPolicy] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - metadata: Optional[Dict[str, str]] = None, - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStore: - """Creates a vector store and poll. - - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword file_ids: A list of file IDs that the vector store should use. Useful for tools like - ``file_search`` that can access files. Default value is None. - :paramtype file_ids: list[str] - :keyword name: The name of the vector store. Default value is None. - :paramtype name: str - :keyword data_sources: List of Azure assets. Default value is None. - :paramtype data_sources: list[~azure.ai.projects.models.VectorStoreDataSource] - :keyword expires_after: Details on when this vector store expires. Default value is None. - :paramtype expires_after: ~azure.ai.projects.models.VectorStoreExpirationPolicy - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Only applicable if file_ids is non-empty. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - if body is not _Unset: - if isinstance(body, dict): - vector_store = await super().create_vector_store( - body=body, content_type=content_type or "application/json", **kwargs - ) - elif isinstance(body, io.IOBase): - vector_store = await super().create_vector_store(body=body, content_type=content_type, **kwargs) - else: - raise ValueError("Invalid 'body' type: must be a dictionary (JSON) or a file-like object (IO[bytes]).") - else: - store_configuration = None - if data_sources: - store_configuration = _models.VectorStoreConfiguration(data_sources=data_sources) - - vector_store = await super().create_vector_store( - file_ids=file_ids, - store_configuration=store_configuration, - name=name, - expires_after=expires_after, - chunking_strategy=chunking_strategy, - metadata=metadata, - **kwargs, - ) - - while vector_store.status == "in_progress": - time.sleep(sleep_interval) - vector_store = await super().get_vector_store(vector_store.id) - - return vector_store - - @overload - async def create_vector_store_file_batch_and_poll( - self, - vector_store_id: str, - body: JSON, - *, - content_type: str = "application/json", - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStoreFileBatch: - """Create a vector store file batch and poll. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_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 - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_vector_store_file_batch_and_poll( - self, - vector_store_id: str, - *, - file_ids: Optional[List[str]] = None, - data_sources: Optional[List[_models.VectorStoreDataSource]] = None, - content_type: str = "application/json", - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStoreFileBatch: - """Create a vector store file batch and poll. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :keyword file_ids: List of file identifiers. Required. - :paramtype file_ids: list[str] - :keyword data_sources: List of Azure assets. Default value is None. - :paramtype data_sources: list[~azure.ai.projects.models.VectorStoreDataSource] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_vector_store_file_batch_and_poll( - self, - vector_store_id: str, - body: IO[bytes], - *, - content_type: str = "application/json", - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStoreFileBatch: - """Create a vector store file batch and poll. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_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 - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_vector_store_file_batch_and_poll( - self, - vector_store_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - file_ids: Optional[List[str]] = None, - data_sources: Optional[List[_models.VectorStoreDataSource]] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - content_type: str = "application/json", - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStoreFileBatch: - """Create a vector store file batch and poll. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword file_ids: List of file identifiers. Required. - :paramtype file_ids: list[str] - :keyword data_sources: List of Azure assets. Default value is None. - :paramtype data_sources: list[~azure.ai.client.models.VectorStoreDataSource] - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :keyword content_type: Body parameter content-type. Defaults to "application/json". - :paramtype content_type: str - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch - :raises ~azure.core.exceptions.HttpResponseError: - """ - - if body is not _Unset: - if isinstance(body, dict): - vector_store_file_batch = await super().create_vector_store_file_batch( - vector_store_id=vector_store_id, - body=body, - content_type=content_type or "application/json", - **kwargs, - ) - elif isinstance(body, io.IOBase): - vector_store_file_batch = await super().create_vector_store_file_batch( - vector_store_id=vector_store_id, - body=body, - content_type=content_type, - **kwargs, - ) - else: - raise ValueError("Invalid type for 'body'. Must be a dict (JSON) or file-like (IO[bytes]).") - else: - vector_store_file_batch = await super().create_vector_store_file_batch( - vector_store_id=vector_store_id, - file_ids=file_ids, - data_sources=data_sources, - chunking_strategy=chunking_strategy, - **kwargs, - ) - - while vector_store_file_batch.status == "in_progress": - time.sleep(sleep_interval) - vector_store_file_batch = await super().get_vector_store_file_batch( - vector_store_id=vector_store_id, batch_id=vector_store_file_batch.id - ) - - return vector_store_file_batch - - @overload - async def create_vector_store_file_and_poll( - self, - vector_store_id: str, - body: JSON, - *, - content_type: str = "application/json", - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStoreFile: - """Create a vector store file by attaching a file to a vector store. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_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 - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStoreFile. The VectorStoreFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_vector_store_file_and_poll( - self, - vector_store_id: str, - *, - content_type: str = "application/json", - file_id: Optional[str] = None, - data_source: Optional[_models.VectorStoreDataSource] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStoreFile: - """Create a vector store file by attaching a file to a vector store. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword file_id: Identifier of the file. Default value is None. - :paramtype file_id: str - :keyword data_source: Azure asset ID. Default value is None. - :paramtype data_source: ~azure.ai.projects.models.VectorStoreDataSource - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStoreFile. The VectorStoreFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def create_vector_store_file_and_poll( - self, - vector_store_id: str, - body: IO[bytes], - *, - content_type: str = "application/json", - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStoreFile: - """Create a vector store file by attaching a file to a vector store. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_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 - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStoreFile. The VectorStoreFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace_async - async def create_vector_store_file_and_poll( - self, - vector_store_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - content_type: str = "application/json", - file_id: Optional[str] = None, - data_source: Optional[_models.VectorStoreDataSource] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStoreFile: - """Create a vector store file by attaching a file to a vector store. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword content_type: Body Parameter content-type. Defaults to 'application/json'. - :paramtype content_type: str - :keyword file_id: Identifier of the file. Default value is None. - :paramtype file_id: str - :keyword data_source: Azure asset ID. Default value is None. - :paramtype data_source: ~azure.ai.projects.models.VectorStoreDataSource - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStoreFile. The VectorStoreFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - if body is not _Unset: - if isinstance(body, dict): - vector_store_file = await super().create_vector_store_file( - vector_store_id=vector_store_id, - body=body, - content_type=content_type or "application/json", - **kwargs, - ) - elif isinstance(body, io.IOBase): - vector_store_file = await super().create_vector_store_file( - vector_store_id=vector_store_id, - body=body, - content_type=content_type, - **kwargs, - ) - else: - raise ValueError("Invalid type for 'body'. Must be a dict (JSON) or file-like object (IO[bytes]).") - else: - vector_store_file = await super().create_vector_store_file( - vector_store_id=vector_store_id, - file_id=file_id, - data_source=data_source, - chunking_strategy=chunking_strategy, - **kwargs, - ) - - while vector_store_file.status == "in_progress": - time.sleep(sleep_interval) - vector_store_file = await super().get_vector_store_file( - vector_store_id=vector_store_id, file_id=vector_store_file.id - ) - - return vector_store_file - - @distributed_trace_async - async def get_file_content(self, file_id: str, **kwargs: Any) -> AsyncIterator[bytes]: - """ - Asynchronously returns file content as a byte stream for the given file_id. - - :param file_id: The ID of the file to retrieve. Required. - :type file_id: str - :return: An async iterator that yields bytes from the file content. - :rtype: AsyncIterator[bytes] - :raises ~azure.core.exceptions.HttpResponseError: If the HTTP request fails. - """ - kwargs["stream"] = True - response = await super()._get_file_content(file_id, **kwargs) - return cast(AsyncIterator[bytes], response) - - @distributed_trace_async - async def save_file(self, file_id: str, file_name: str, target_dir: Optional[Union[str, Path]] = None) -> None: - """ - Asynchronously saves file content retrieved using a file identifier to the specified local directory. - - :param file_id: The unique identifier for the file to retrieve. - :type file_id: str - :param file_name: The name of the file to be saved. - :type file_name: str - :param target_dir: The directory where the file should be saved. Defaults to the current working directory. - :type target_dir: str or Path - :raises ValueError: If the target path is not a directory or the file name is invalid. - :raises RuntimeError: If file content retrieval fails or no content is found. - :raises TypeError: If retrieved chunks are not bytes-like objects. - :raises IOError: If writing to the file fails. - """ - try: - # Determine and validate the target directory - path = Path(target_dir).expanduser().resolve() if target_dir else Path.cwd() - path.mkdir(parents=True, exist_ok=True) - if not path.is_dir(): - raise ValueError(f"The target path '{path}' is not a directory.") - - # Sanitize and validate the file name - sanitized_file_name = Path(file_name).name - if not sanitized_file_name: - raise ValueError("The provided file name is invalid.") - - # Retrieve the file content - file_content_stream = await self.get_file_content(file_id) - if not file_content_stream: - raise RuntimeError(f"No content retrievable for file ID '{file_id}'.") - - # Collect all chunks asynchronously - chunks = [] - async for chunk in file_content_stream: - if isinstance(chunk, (bytes, bytearray)): - chunks.append(chunk) - else: - raise TypeError(f"Expected bytes or bytearray, got {type(chunk).__name__}") - - target_file_path = path / sanitized_file_name - - # Write the collected content to the file synchronously - def write_file(collected_chunks: list): - with open(target_file_path, "wb") as file: - for chunk in collected_chunks: - file.write(chunk) - - # Use the event loop to run the synchronous function in a thread executor - loop = asyncio.get_running_loop() - await loop.run_in_executor(None, write_file, chunks) - - logger.debug("File '%s' saved successfully at '%s'.", sanitized_file_name, target_file_path) - - except (ValueError, RuntimeError, TypeError, IOError) as e: - logger.error("An error occurred in save_file: %s", e) - raise - - @distributed_trace_async - async def delete_agent(self, agent_id: str, **kwargs: Any) -> _models.AgentDeletionStatus: - """Deletes an agent. - - :param agent_id: Identifier of the agent. Required. - :type agent_id: str - :return: AgentDeletionStatus. The AgentDeletionStatus is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentDeletionStatus - :raises ~azure.core.exceptions.HttpResponseError: - """ - return await super().delete_agent(agent_id, **kwargs) - - @overload - def enable_auto_function_calls(self, *, functions: Set[Callable[..., Any]], max_retry: int = 10) -> None: - """Enables tool calls to be executed automatically during create_and_process_run or streaming. - If this is not set, functions must be called manually. - If automatic function calls fail, the agents will receive error messages allowing it to retry with another - function call or figure out the answer with its knowledge. - :keyword functions: A set of callable functions to be used as tools. - :type functions: Set[Callable[..., Any]] - :keyword max_retry: Maximum number of errors allowed and retry per run or stream. Default value is 10. - :type max_retry: int - """ - - @overload - def enable_auto_function_calls(self, *, function_tool: _models.AsyncFunctionTool, max_retry: int = 10) -> None: - """Enables tool calls to be executed automatically during create_and_process_run or streaming. - If this is not set, functions must be called manually. - If automatic function calls fail, the agents will receive error messages allowing it to retry with another - function call or figure out the answer with its knowledge. - :keyword function_tool: An AsyncFunctionTool object representing the tool to be used. - :type function_tool: Optional[_models.AsyncFunctionTool] - :keyword max_retry: Maximum number of errors allowed and retry per run or stream. Default value is 10. - :type max_retry: int - """ - - @overload - def enable_auto_function_calls(self, *, toolset: _models.AsyncToolSet, max_retry: int = 10) -> None: - """Enables tool calls to be executed automatically during create_and_process_run or streaming. - If this is not set, functions must be called manually. - If automatic function calls fail, the agents will receive error messages allowing it to retry with another - function call or figure out the answer with its knowledge. - :keyword toolset: An AsyncToolSet object representing the set of tools to be used. - :type toolset: Optional[_models.AsyncToolSet] - :keyword max_retry: Maximum number of errors allowed and retry per run or stream. Default value is 10. - :type max_retry: int - """ - - def enable_auto_function_calls( - self, - *, - functions: Optional[Set[Callable[..., Any]]] = None, - function_tool: Optional[_models.AsyncFunctionTool] = None, - toolset: Optional[_models.AsyncToolSet] = None, - max_retry: int = 10, - ) -> None: - """Enables tool calls to be executed automatically during create_and_process_run or streaming. - If this is not set, functions must be called manually. - If automatic function calls fail, the agents will receive error messages allowing it to retry with another - function call or figure out the answer with its knowledge. - :keyword functions: A set of callable functions to be used as tools. - :type functions: Set[Callable[..., Any]] - :keyword function_tool: An AsyncFunctionTool object representing the tool to be used. - :type function_tool: Optional[_models.AsyncFunctionTool] - :keyword toolset: An AsyncToolSet object representing the set of tools to be used. - :type toolset: Optional[_models.AsyncToolSet] - :keyword max_retry: Maximum number of errors allowed and retry per run or stream. Default value is 10. - :type max_retry: int - """ - if functions: - self._function_tool = _models.AsyncFunctionTool(functions) - elif function_tool: - self._function_tool = function_tool - elif toolset: - tool = toolset.get_tool(_models.AsyncFunctionTool) - self._function_tool = tool - - self._function_tool_max_retry = max_retry - - -class _SyncCredentialWrapper(TokenCredential): - """ - The class, synchronizing AsyncTokenCredential. - - :param async_credential: The async credential to be synchronized. - :type async_credential: ~azure.core.credentials_async.AsyncTokenCredential - """ - - def __init__(self, async_credential: "AsyncTokenCredential"): - self._async_credential = async_credential - - def get_token( - self, - *scopes: str, - claims: Optional[str] = None, - tenant_id: Optional[str] = None, - enable_cae: bool = False, - **kwargs: Any, - ) -> "AccessToken": - - pool = concurrent.futures.ThreadPoolExecutor() - return pool.submit( - asyncio.run, - self._async_credential.get_token( - *scopes, - claims=claims, - tenant_id=tenant_id, - enable_cae=enable_cae, - **kwargs, - ), - ).result() - - -__all__: List[str] = [ - "AgentsOperations", - "ConnectionsOperations", - "TelemetryOperations", - "InferenceOperations", -] # Add all objects you want publicly available to users at this package level +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): 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 6e1bbfc0c2fc..039f4eeef11a 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 @@ -14,459 +14,101 @@ from ._models import ( # type: ignore - AISearchIndexResource, - AOAIModelConfig, - Agent, - AgentDeletionStatus, - AgentThread, - AgentThreadCreationOptions, - AgentsApiResponseFormat, - AgentsNamedToolChoice, - ApplicationInsightsConfiguration, - AzureAISearchResource, - AzureAISearchToolDefinition, - AzureFunctionBinding, - AzureFunctionDefinition, - AzureFunctionStorageQueue, - AzureFunctionToolDefinition, - BingCustomSearchToolDefinition, - BingGroundingToolDefinition, - CodeInterpreterToolDefinition, - CodeInterpreterToolResource, - ConnectedAgentDetails, - ConnectedAgentToolDefinition, - CronTrigger, - Dataset, + AgentEvaluation, + AgentEvaluationRedactionConfiguration, + AgentEvaluationRequest, + AgentEvaluationResult, + AgentEvaluationSamplingConfiguration, + ApiKeyCredentials, + AssetCredentialResponse, + AzureAISearchIndex, + AzureOpenAIModelConfiguration, + BaseCredentials, + BlobReference, + Connection, + CosmosDBIndex, + CustomCredential, + DatasetVersion, + Deployment, + EmbeddingConfiguration, + EntraIDCredentials, Evaluation, - EvaluationSchedule, - EvaluationTarget, EvaluatorConfiguration, - FileDeletionStatus, - FileListResponse, - FileSearchRankingOptions, - FileSearchToolCallContent, - FileSearchToolDefinition, - FileSearchToolDefinitionDetails, - FileSearchToolResource, - FunctionDefinition, - FunctionName, - FunctionToolDefinition, - IncompleteRunDetails, + FileDatasetVersion, + FolderDatasetVersion, + Index, InputData, - MAASModelConfig, - MessageAttachment, - MessageContent, - MessageDelta, - MessageDeltaChunk, - MessageDeltaContent, - MessageDeltaImageFileContent, - MessageDeltaImageFileContentObject, - MessageDeltaTextAnnotation, - MessageDeltaTextContent, - MessageDeltaTextContentObject, - MessageDeltaTextFileCitationAnnotation, - MessageDeltaTextFileCitationAnnotationObject, - MessageDeltaTextFilePathAnnotation, - MessageDeltaTextFilePathAnnotationObject, - MessageDeltaTextUrlCitationAnnotation, - MessageDeltaTextUrlCitationDetails, - MessageImageFileContent, - MessageImageFileDetails, - MessageImageFileParam, - MessageImageUrlParam, - MessageIncompleteDetails, - MessageInputContentBlock, - MessageInputImageFileBlock, - MessageInputImageUrlBlock, - MessageInputTextBlock, - MessageTextAnnotation, - MessageTextContent, - MessageTextDetails, - MessageTextFileCitationAnnotation, - MessageTextFileCitationDetails, - MessageTextFilePathAnnotation, - MessageTextFilePathDetails, - MessageTextUrlCitationAnnotation, - MessageTextUrlCitationDetails, - MicrosoftFabricToolDefinition, - OpenAIFile, - OpenAIPageableListOfAgent, - OpenAIPageableListOfAgentThread, - OpenAIPageableListOfRunStep, - OpenAIPageableListOfThreadMessage, - OpenAIPageableListOfThreadRun, - OpenAIPageableListOfVectorStore, - OpenAIPageableListOfVectorStoreFile, - OpenApiAnonymousAuthDetails, - OpenApiAuthDetails, - OpenApiConnectionAuthDetails, - OpenApiConnectionSecurityScheme, - OpenApiFunctionDefinition, - OpenApiManagedAuthDetails, - OpenApiManagedSecurityScheme, - OpenApiToolDefinition, - RecurrenceSchedule, - RecurrenceTrigger, - RequiredAction, - RequiredFunctionToolCall, - RequiredFunctionToolCallDetails, - RequiredToolCall, - ResponseFormatJsonSchema, - ResponseFormatJsonSchemaType, - RunCompletionUsage, - RunError, - RunStep, - RunStepAzureAISearchToolCall, - RunStepBingGroundingToolCall, - RunStepCodeInterpreterImageOutput, - RunStepCodeInterpreterImageReference, - RunStepCodeInterpreterLogOutput, - RunStepCodeInterpreterToolCall, - RunStepCodeInterpreterToolCallDetails, - RunStepCodeInterpreterToolCallOutput, - RunStepCompletionUsage, - RunStepCustomSearchToolCall, - RunStepDelta, - RunStepDeltaChunk, - RunStepDeltaCodeInterpreterDetailItemObject, - RunStepDeltaCodeInterpreterImageOutput, - RunStepDeltaCodeInterpreterImageOutputObject, - RunStepDeltaCodeInterpreterLogOutput, - RunStepDeltaCodeInterpreterOutput, - RunStepDeltaCodeInterpreterToolCall, - RunStepDeltaDetail, - RunStepDeltaFileSearchToolCall, - RunStepDeltaFunction, - RunStepDeltaFunctionToolCall, - RunStepDeltaMessageCreation, - RunStepDeltaMessageCreationObject, - RunStepDeltaToolCall, - RunStepDeltaToolCallObject, - RunStepDetails, - RunStepError, - RunStepFileSearchToolCall, - RunStepFileSearchToolCallResult, - RunStepFileSearchToolCallResults, - RunStepFunctionToolCall, - RunStepFunctionToolCallDetails, - RunStepMessageCreationDetails, - RunStepMessageCreationReference, - RunStepMicrosoftFabricToolCall, - RunStepOpenAPIToolCall, - RunStepSharepointToolCall, - RunStepToolCall, - RunStepToolCallDetails, - SearchConfiguration, - SearchConfigurationList, - SharepointToolDefinition, - SubmitToolOutputsAction, - SubmitToolOutputsDetails, - SystemData, - TargetModelConfig, - ThreadDeletionStatus, - ThreadMessage, - ThreadMessageOptions, - ThreadRun, - ToolConnection, - ToolConnectionList, - ToolDefinition, - ToolOutput, - ToolResources, - Trigger, - TruncationObject, - UpdateCodeInterpreterToolResourceOptions, - UpdateFileSearchToolResourceOptions, - UpdateToolResourcesOptions, - VectorStore, - VectorStoreAutoChunkingStrategyRequest, - VectorStoreAutoChunkingStrategyResponse, - VectorStoreChunkingStrategyRequest, - VectorStoreChunkingStrategyResponse, - VectorStoreConfiguration, - VectorStoreConfigurations, - VectorStoreDataSource, - VectorStoreDeletionStatus, - VectorStoreExpirationPolicy, - VectorStoreFile, - VectorStoreFileBatch, - VectorStoreFileCount, - VectorStoreFileDeletionStatus, - VectorStoreFileError, - VectorStoreStaticChunkingStrategyOptions, - VectorStoreStaticChunkingStrategyRequest, - VectorStoreStaticChunkingStrategyResponse, + InputDataset, + ManagedAzureAISearchIndex, + ModelDeployment, + NoAuthenticationCredentials, + PendingUploadRequest, + PendingUploadResponse, + RedTeam, + SASCredentials, + SasCredential, + Sku, + TargetConfig, ) from ._enums import ( # type: ignore - AgentStreamEvent, - AgentsApiResponseFormatMode, - AgentsApiToolChoiceOptionMode, - AgentsNamedToolChoiceType, - AuthenticationType, - AzureAISearchQueryType, + AttackStrategy, ConnectionType, - DoneEvent, - ErrorEvent, - FilePurpose, - FileState, - Frequency, - ImageDetailLevel, - IncompleteDetailsReason, - ListSortOrder, - MessageBlockType, - MessageIncompleteDetailsReason, - MessageRole, - MessageStatus, - MessageStreamEvent, - OpenApiAuthType, - ResponseFormat, - RunAdditionalFieldList, - RunStatus, - RunStepErrorCode, - RunStepStatus, - RunStepStreamEvent, - RunStepType, - RunStreamEvent, - ThreadStreamEvent, - TruncationStrategy, - VectorStoreChunkingStrategyRequestType, - VectorStoreChunkingStrategyResponseType, - VectorStoreDataSourceAssetType, - VectorStoreExpirationPolicyAnchor, - VectorStoreFileBatchStatus, - VectorStoreFileErrorCode, - VectorStoreFileStatus, - VectorStoreFileStatusFilter, - VectorStoreStatus, - WeekDays, + CredentialType, + DatasetType, + DeploymentType, + IndexType, + PendingUploadType, + RiskCategory, ) from ._patch import __all__ as _patch_all from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AISearchIndexResource", - "AOAIModelConfig", - "Agent", - "AgentDeletionStatus", - "AgentThread", - "AgentThreadCreationOptions", - "AgentsApiResponseFormat", - "AgentsNamedToolChoice", - "ApplicationInsightsConfiguration", - "AzureAISearchResource", - "AzureAISearchToolDefinition", - "AzureFunctionBinding", - "AzureFunctionDefinition", - "AzureFunctionStorageQueue", - "AzureFunctionToolDefinition", - "BingCustomSearchToolDefinition", - "BingGroundingToolDefinition", - "CodeInterpreterToolDefinition", - "CodeInterpreterToolResource", - "ConnectedAgentDetails", - "ConnectedAgentToolDefinition", - "CronTrigger", - "Dataset", + "AgentEvaluation", + "AgentEvaluationRedactionConfiguration", + "AgentEvaluationRequest", + "AgentEvaluationResult", + "AgentEvaluationSamplingConfiguration", + "ApiKeyCredentials", + "AssetCredentialResponse", + "AzureAISearchIndex", + "AzureOpenAIModelConfiguration", + "BaseCredentials", + "BlobReference", + "Connection", + "CosmosDBIndex", + "CustomCredential", + "DatasetVersion", + "Deployment", + "EmbeddingConfiguration", + "EntraIDCredentials", "Evaluation", - "EvaluationSchedule", - "EvaluationTarget", "EvaluatorConfiguration", - "FileDeletionStatus", - "FileListResponse", - "FileSearchRankingOptions", - "FileSearchToolCallContent", - "FileSearchToolDefinition", - "FileSearchToolDefinitionDetails", - "FileSearchToolResource", - "FunctionDefinition", - "FunctionName", - "FunctionToolDefinition", - "IncompleteRunDetails", + "FileDatasetVersion", + "FolderDatasetVersion", + "Index", "InputData", - "MAASModelConfig", - "MessageAttachment", - "MessageContent", - "MessageDelta", - "MessageDeltaChunk", - "MessageDeltaContent", - "MessageDeltaImageFileContent", - "MessageDeltaImageFileContentObject", - "MessageDeltaTextAnnotation", - "MessageDeltaTextContent", - "MessageDeltaTextContentObject", - "MessageDeltaTextFileCitationAnnotation", - "MessageDeltaTextFileCitationAnnotationObject", - "MessageDeltaTextFilePathAnnotation", - "MessageDeltaTextFilePathAnnotationObject", - "MessageDeltaTextUrlCitationAnnotation", - "MessageDeltaTextUrlCitationDetails", - "MessageImageFileContent", - "MessageImageFileDetails", - "MessageImageFileParam", - "MessageImageUrlParam", - "MessageIncompleteDetails", - "MessageInputContentBlock", - "MessageInputImageFileBlock", - "MessageInputImageUrlBlock", - "MessageInputTextBlock", - "MessageTextAnnotation", - "MessageTextContent", - "MessageTextDetails", - "MessageTextFileCitationAnnotation", - "MessageTextFileCitationDetails", - "MessageTextFilePathAnnotation", - "MessageTextFilePathDetails", - "MessageTextUrlCitationAnnotation", - "MessageTextUrlCitationDetails", - "MicrosoftFabricToolDefinition", - "OpenAIFile", - "OpenAIPageableListOfAgent", - "OpenAIPageableListOfAgentThread", - "OpenAIPageableListOfRunStep", - "OpenAIPageableListOfThreadMessage", - "OpenAIPageableListOfThreadRun", - "OpenAIPageableListOfVectorStore", - "OpenAIPageableListOfVectorStoreFile", - "OpenApiAnonymousAuthDetails", - "OpenApiAuthDetails", - "OpenApiConnectionAuthDetails", - "OpenApiConnectionSecurityScheme", - "OpenApiFunctionDefinition", - "OpenApiManagedAuthDetails", - "OpenApiManagedSecurityScheme", - "OpenApiToolDefinition", - "RecurrenceSchedule", - "RecurrenceTrigger", - "RequiredAction", - "RequiredFunctionToolCall", - "RequiredFunctionToolCallDetails", - "RequiredToolCall", - "ResponseFormatJsonSchema", - "ResponseFormatJsonSchemaType", - "RunCompletionUsage", - "RunError", - "RunStep", - "RunStepAzureAISearchToolCall", - "RunStepBingGroundingToolCall", - "RunStepCodeInterpreterImageOutput", - "RunStepCodeInterpreterImageReference", - "RunStepCodeInterpreterLogOutput", - "RunStepCodeInterpreterToolCall", - "RunStepCodeInterpreterToolCallDetails", - "RunStepCodeInterpreterToolCallOutput", - "RunStepCompletionUsage", - "RunStepCustomSearchToolCall", - "RunStepDelta", - "RunStepDeltaChunk", - "RunStepDeltaCodeInterpreterDetailItemObject", - "RunStepDeltaCodeInterpreterImageOutput", - "RunStepDeltaCodeInterpreterImageOutputObject", - "RunStepDeltaCodeInterpreterLogOutput", - "RunStepDeltaCodeInterpreterOutput", - "RunStepDeltaCodeInterpreterToolCall", - "RunStepDeltaDetail", - "RunStepDeltaFileSearchToolCall", - "RunStepDeltaFunction", - "RunStepDeltaFunctionToolCall", - "RunStepDeltaMessageCreation", - "RunStepDeltaMessageCreationObject", - "RunStepDeltaToolCall", - "RunStepDeltaToolCallObject", - "RunStepDetails", - "RunStepError", - "RunStepFileSearchToolCall", - "RunStepFileSearchToolCallResult", - "RunStepFileSearchToolCallResults", - "RunStepFunctionToolCall", - "RunStepFunctionToolCallDetails", - "RunStepMessageCreationDetails", - "RunStepMessageCreationReference", - "RunStepMicrosoftFabricToolCall", - "RunStepOpenAPIToolCall", - "RunStepSharepointToolCall", - "RunStepToolCall", - "RunStepToolCallDetails", - "SearchConfiguration", - "SearchConfigurationList", - "SharepointToolDefinition", - "SubmitToolOutputsAction", - "SubmitToolOutputsDetails", - "SystemData", - "TargetModelConfig", - "ThreadDeletionStatus", - "ThreadMessage", - "ThreadMessageOptions", - "ThreadRun", - "ToolConnection", - "ToolConnectionList", - "ToolDefinition", - "ToolOutput", - "ToolResources", - "Trigger", - "TruncationObject", - "UpdateCodeInterpreterToolResourceOptions", - "UpdateFileSearchToolResourceOptions", - "UpdateToolResourcesOptions", - "VectorStore", - "VectorStoreAutoChunkingStrategyRequest", - "VectorStoreAutoChunkingStrategyResponse", - "VectorStoreChunkingStrategyRequest", - "VectorStoreChunkingStrategyResponse", - "VectorStoreConfiguration", - "VectorStoreConfigurations", - "VectorStoreDataSource", - "VectorStoreDeletionStatus", - "VectorStoreExpirationPolicy", - "VectorStoreFile", - "VectorStoreFileBatch", - "VectorStoreFileCount", - "VectorStoreFileDeletionStatus", - "VectorStoreFileError", - "VectorStoreStaticChunkingStrategyOptions", - "VectorStoreStaticChunkingStrategyRequest", - "VectorStoreStaticChunkingStrategyResponse", - "AgentStreamEvent", - "AgentsApiResponseFormatMode", - "AgentsApiToolChoiceOptionMode", - "AgentsNamedToolChoiceType", - "AuthenticationType", - "AzureAISearchQueryType", + "InputDataset", + "ManagedAzureAISearchIndex", + "ModelDeployment", + "NoAuthenticationCredentials", + "PendingUploadRequest", + "PendingUploadResponse", + "RedTeam", + "SASCredentials", + "SasCredential", + "Sku", + "TargetConfig", + "AttackStrategy", "ConnectionType", - "DoneEvent", - "ErrorEvent", - "FilePurpose", - "FileState", - "Frequency", - "ImageDetailLevel", - "IncompleteDetailsReason", - "ListSortOrder", - "MessageBlockType", - "MessageIncompleteDetailsReason", - "MessageRole", - "MessageStatus", - "MessageStreamEvent", - "OpenApiAuthType", - "ResponseFormat", - "RunAdditionalFieldList", - "RunStatus", - "RunStepErrorCode", - "RunStepStatus", - "RunStepStreamEvent", - "RunStepType", - "RunStreamEvent", - "ThreadStreamEvent", - "TruncationStrategy", - "VectorStoreChunkingStrategyRequestType", - "VectorStoreChunkingStrategyResponseType", - "VectorStoreDataSourceAssetType", - "VectorStoreExpirationPolicyAnchor", - "VectorStoreFileBatchStatus", - "VectorStoreFileErrorCode", - "VectorStoreFileStatus", - "VectorStoreFileStatusFilter", - "VectorStoreStatus", - "WeekDays", + "CredentialType", + "DatasetType", + "DeploymentType", + "IndexType", + "PendingUploadType", + "RiskCategory", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() 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 20b2b87e2cc2..a1b1b9a8e1bf 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 @@ -10,155 +10,67 @@ from azure.core import CaseInsensitiveEnumMeta -class AgentsApiResponseFormatMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Represents the mode in which the model will handle the return format of a tool call.""" - - AUTO = "auto" - """Default value. Let the model handle the return format.""" - NONE = "none" - """Setting the value to ``none``, will result in a 400 Bad request.""" - - -class AgentsApiToolChoiceOptionMode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Specifies how the tool choice will be used.""" - - NONE = "none" - """The model will not call a function and instead generates a message.""" - AUTO = "auto" - """The model can pick between generating a message or calling a function.""" - - -class AgentsNamedToolChoiceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Available tool types for agents named tools.""" - - FUNCTION = "function" - """Tool type ``function``""" - CODE_INTERPRETER = "code_interpreter" - """Tool type ``code_interpreter``""" - FILE_SEARCH = "file_search" - """Tool type ``file_search``""" - BING_GROUNDING = "bing_grounding" - """Tool type ``bing_grounding``""" - MICROSOFT_FABRIC = "fabric_dataagent" - """Tool type ``fabric_dataagent``""" - SHAREPOINT = "sharepoint_grounding" - """Tool type ``sharepoint_grounding``""" - AZURE_AI_SEARCH = "azure_ai_search" - """Tool type ``azure_ai_search``""" - BING_CUSTOM_SEARCH = "bing_custom_search" - """Tool type ``bing_custom_search``""" - CONNECTED_AGENT = "connected_agent" - """Tool type ``connected_agent``""" - - -class AgentStreamEvent(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Each event in a server-sent events stream has an ``event`` and ``data`` property: - - - - .. code-block:: - - event: thread.created - data: {"id": "thread_123", "object": "thread", ...} - - We emit events whenever a new object is created, transitions to a new state, or is being - streamed in parts (deltas). For example, we emit ``thread.run.created`` when a new run - is created, ``thread.run.completed`` when a run completes, and so on. When an Agent chooses - to create a message during a run, we emit a ``thread.message.created event``, a - ``thread.message.in_progress`` event, many ``thread.message.delta`` events, and finally a - ``thread.message.completed`` event. - - We may add additional events over time, so we recommend handling unknown events gracefully - in your code. - """ - - THREAD_CREATED = "thread.created" - """Event sent when a new thread is created. The data of this event is of type AgentThread""" - THREAD_RUN_CREATED = "thread.run.created" - """Event sent when a new run is created. The data of this event is of type ThreadRun""" - THREAD_RUN_QUEUED = "thread.run.queued" - """Event sent when a run moves to ``queued`` status. The data of this event is of type ThreadRun""" - THREAD_RUN_IN_PROGRESS = "thread.run.in_progress" - """Event sent when a run moves to ``in_progress`` status. The data of this event is of type - ThreadRun""" - THREAD_RUN_REQUIRES_ACTION = "thread.run.requires_action" - """Event sent when a run moves to ``requires_action`` status. The data of this event is of type - ThreadRun""" - THREAD_RUN_COMPLETED = "thread.run.completed" - """Event sent when a run is completed. The data of this event is of type ThreadRun""" - THREAD_RUN_INCOMPLETE = "thread.run.incomplete" - """Event sent when a run ends incomplete. The data of this event is of type ThreadRun""" - THREAD_RUN_FAILED = "thread.run.failed" - """Event sent when a run fails. The data of this event is of type ThreadRun""" - THREAD_RUN_CANCELLING = "thread.run.cancelling" - """Event sent when a run moves to ``cancelling`` status. The data of this event is of type - ThreadRun""" - THREAD_RUN_CANCELLED = "thread.run.cancelled" - """Event sent when a run is cancelled. The data of this event is of type ThreadRun""" - THREAD_RUN_EXPIRED = "thread.run.expired" - """Event sent when a run is expired. The data of this event is of type ThreadRun""" - THREAD_RUN_STEP_CREATED = "thread.run.step.created" - """Event sent when a new thread run step is created. The data of this event is of type RunStep""" - THREAD_RUN_STEP_IN_PROGRESS = "thread.run.step.in_progress" - """Event sent when a run step moves to ``in_progress`` status. The data of this event is of type - RunStep""" - THREAD_RUN_STEP_DELTA = "thread.run.step.delta" - """Event sent when a run step is being streamed. The data of this event is of type - RunStepDeltaChunk""" - THREAD_RUN_STEP_COMPLETED = "thread.run.step.completed" - """Event sent when a run step is completed. The data of this event is of type RunStep""" - THREAD_RUN_STEP_FAILED = "thread.run.step.failed" - """Event sent when a run step fails. The data of this event is of type RunStep""" - THREAD_RUN_STEP_CANCELLED = "thread.run.step.cancelled" - """Event sent when a run step is cancelled. The data of this event is of type RunStep""" - THREAD_RUN_STEP_EXPIRED = "thread.run.step.expired" - """Event sent when a run step is expired. The data of this event is of type RunStep""" - THREAD_MESSAGE_CREATED = "thread.message.created" - """Event sent when a new message is created. The data of this event is of type ThreadMessage""" - THREAD_MESSAGE_IN_PROGRESS = "thread.message.in_progress" - """Event sent when a message moves to ``in_progress`` status. The data of this event is of type - ThreadMessage""" - THREAD_MESSAGE_DELTA = "thread.message.delta" - """Event sent when a message is being streamed. The data of this event is of type - MessageDeltaChunk""" - THREAD_MESSAGE_COMPLETED = "thread.message.completed" - """Event sent when a message is completed. The data of this event is of type ThreadMessage""" - THREAD_MESSAGE_INCOMPLETE = "thread.message.incomplete" - """Event sent before a message is completed. The data of this event is of type ThreadMessage""" - ERROR = "error" - """Event sent when an error occurs, such as an internal server error or a timeout.""" - DONE = "done" - """Event sent when the stream is done.""" - - -class AuthenticationType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Authentication type used by Azure AI service to connect to another service.""" - - API_KEY = "ApiKey" - """API Key authentication""" - ENTRA_ID = "AAD" - """Entra ID authentication (formerly known as AAD)""" - SAS = "SAS" - """Shared Access Signature (SAS) authentication""" - CUSTOM = "CustomKeys" - """Custom authentication""" - NONE = "None" - """No authentication""" - - -class AzureAISearchQueryType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Available query types for Azure AI Search tool.""" - - SIMPLE = "simple" - """Query type ``simple``""" - SEMANTIC = "semantic" - """Query type ``semantic``""" - VECTOR = "vector" - """Query type ``vector``""" - VECTOR_SIMPLE_HYBRID = "vector_simple_hybrid" - """Query type ``vector_simple_hybrid``""" - VECTOR_SEMANTIC_HYBRID = "vector_semantic_hybrid" - """Query type ``vector_semantic_hybrid``""" +class AttackStrategy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Strategies for attacks.""" + + EASY = "easy" + """Represents a default set of easy complexity attacks. Easy complexity attacks require less + effort, such as translation of a prompt into some encoding, and does not require any Large + Language Model to convert or orchestrate.""" + MODERATE = "moderate" + """Represents a default set of moderate complexity attacks. Moderate complexity attacks require + having access to resources such as another generative AI model.""" + DIFFICULT = "difficult" + """Represents a default set of difficult complexity attacks. Difficult complexity attacks include + attacks that require access to significant resources and effort to execute an attack such as + knowledge of search-based algorithms in addition to a generative AI model.""" + ASCII_ART = "ascii_art" + """Generates visual art using ASCII characters, often used for creative or obfuscation purposes.""" + ASCII_SMUGGLER = "ascii_smuggler" + """Conceals data within ASCII characters, making it harder to detect.""" + ATBASH = "atbash" + """Implements the Atbash cipher, a simple substitution cipher where each letter is mapped to its + reverse.""" + BASE64 = "base64" + """Encodes binary data into a text format using Base64, commonly used for data transmission.""" + BINARY = "binary" + """Converts text into binary code, representing data in a series of 0s and 1s.""" + CAESAR = "caesar" + """Applies the Caesar cipher, a substitution cipher that shifts characters by a fixed number of + positions.""" + CHARACTER_SPACE = "character_space" + """Alters text by adding spaces between characters, often used for obfuscation.""" + JAILBREAK = "jailbreak" + """Injects specially crafted prompts to bypass AI safeguards, known as User Injected Prompt + Attacks (UPIA).""" + ANSII_ATTACK = "ansii_attack" + """Utilizes ANSI escape sequences to manipulate text appearance and behavior.""" + CHARACTER_SWAP = "character_swap" + """Swaps characters within text to create variations or obfuscate the original content.""" + SUFFIX_APPEND = "suffix_append" + """Appends an adversarial suffix to the prompt.""" + STRING_JOIN = "string_join" + """Joins multiple strings together, often used for concatenation or obfuscation.""" + UNICODE_CONFUSABLE = "unicode_confusable" + """Uses Unicode characters that look similar to standard characters, creating visual confusion.""" + UNICODE_SUBSTITUTION = "unicode_substitution" + """Substitutes standard characters with Unicode equivalents, often for obfuscation.""" + DIACRITIC = "diacritic" + """Adds diacritical marks to characters, changing their appearance and sometimes their meaning.""" + FLIP = "flip" + """Flips characters from front to back, creating a mirrored effect.""" + LEETSPEAK = "leetspeak" + """Transforms text into Leetspeak, a form of encoding that replaces letters with similar-looking + numbers or symbols.""" + ROT13 = "rot13" + """Applies the ROT13 cipher, a simple substitution cipher that shifts characters by 13 positions.""" + MORSE = "morse" + """Encodes text into Morse code, using dots and dashes to represent characters.""" + URL = "url" + """Encodes text into URL format.""" + BASELINE = "baseline" + """Represents the baseline direct adversarial probing, which is used by attack strategies as the + attack objective.""" class ConnectionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): @@ -166,439 +78,83 @@ class ConnectionType(str, Enum, metaclass=CaseInsensitiveEnumMeta): AZURE_OPEN_AI = "AzureOpenAI" """Azure OpenAI Service""" - SERVERLESS = "Serverless" - """Serverless API Service""" AZURE_BLOB_STORAGE = "AzureBlob" - """Azure Blob Storage""" - AZURE_AI_SERVICES = "AIServices" - """Azure AI Services""" + """Azure Blob Storage, with specified container""" + AZURE_STORAGE_ACCOUNT = "AzureStorageAccount" + """Azure Blob Storage, with container not specified (used by Agents)""" AZURE_AI_SEARCH = "CognitiveSearch" """Azure AI Search""" + COSMOS_DB = "CosmosDB" + """CosmosDB""" API_KEY = "ApiKey" """Generic connection that uses API Key authentication""" + APPLICATION_CONFIGURATION = "AppConfig" + """Application Configuration""" + APPLICATION_INSIGHTS = "AppInsights" + """Application Insights""" CUSTOM = "CustomKeys" - """Generic connection that uses Custom authentication""" - COGNITIVE_SERVICE = "CognitiveService" - """Cognitive Service""" - - -class DoneEvent(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Terminal event indicating the successful end of a stream.""" - - DONE = "done" - """Event sent when the stream is done.""" - - -class ErrorEvent(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Terminal event indicating a server side error while streaming.""" - - ERROR = "error" - """Event sent when an error occurs, such as an internal server error or a timeout.""" - - -class FilePurpose(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The possible values denoting the intended usage of a file.""" - - FINE_TUNE = "fine-tune" - """Indicates a file is used for fine tuning input.""" - FINE_TUNE_RESULTS = "fine-tune-results" - """Indicates a file is used for fine tuning results.""" - AGENTS = "assistants" - """Indicates a file is used as input to agents.""" - AGENTS_OUTPUT = "assistants_output" - """Indicates a file is used as output by agents.""" - BATCH = "batch" - """Indicates a file is used as input to .""" - BATCH_OUTPUT = "batch_output" - """Indicates a file is used as output by a vector store batch operation.""" - VISION = "vision" - """Indicates a file is used as input to a vision operation.""" - - -class FileState(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The state of the file.""" - - UPLOADED = "uploaded" - """The file has been uploaded but it's not yet processed. This state is not returned by Azure - OpenAI and exposed only for - compatibility. It can be categorized as an inactive state.""" - PENDING = "pending" - """The operation was created and is not queued to be processed in the future. It can be - categorized as an inactive state.""" - RUNNING = "running" - """The operation has started to be processed. It can be categorized as an active state.""" - PROCESSED = "processed" - """The operation has successfully processed and is ready for consumption. It can be categorized as - a terminal state.""" - ERROR = "error" - """The operation has completed processing with a failure and cannot be further consumed. It can be - categorized as a terminal state.""" - DELETING = "deleting" - """The entity is in the process to be deleted. This state is not returned by Azure OpenAI and - exposed only for compatibility. - It can be categorized as an active state.""" - DELETED = "deleted" - """The entity has been deleted but may still be referenced by other entities predating the - deletion. It can be categorized as a - terminal state.""" - - -class Frequency(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Frequency of the schedule - day, week, month, hour, minute.""" - - MONTH = "Month" - WEEK = "Week" - DAY = "Day" - HOUR = "Hour" - MINUTE = "Minute" - - -class ImageDetailLevel(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Specifies an image's detail level. Can be 'auto', 'low', 'high', or an unknown future value.""" - - AUTO = "auto" - """Automatically select an appropriate detail level.""" - LOW = "low" - """Use a lower detail level to reduce bandwidth or cost.""" - HIGH = "high" - """Use a higher detail level—potentially more resource-intensive.""" - - -class IncompleteDetailsReason(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The reason why the run is incomplete. This will point to which specific token limit was reached - over the course of the run. - """ - - MAX_COMPLETION_TOKENS = "max_completion_tokens" - """Maximum completion tokens exceeded""" - MAX_PROMPT_TOKENS = "max_prompt_tokens" - """Maximum prompt tokens exceeded""" - - -class ListSortOrder(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The available sorting options when requesting a list of response objects.""" - - ASCENDING = "asc" - """Specifies an ascending sort order.""" - DESCENDING = "desc" - """Specifies a descending sort order.""" - - -class MessageBlockType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Specifies the kind of content block within a message. Could be text, an image file, an external - image URL, or an unknown future type. - """ - - TEXT = "text" - """Indicates a block containing text content.""" - IMAGE_FILE = "image_file" - """Indicates a block referencing an internally uploaded image file.""" - IMAGE_URL = "image_url" - """Indicates a block referencing an external image URL.""" - - -class MessageIncompleteDetailsReason(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """A set of reasons describing why a message is marked as incomplete.""" - - CONTENT_FILTER = "content_filter" - """The run generating the message was terminated due to content filter flagging.""" - MAX_TOKENS = "max_tokens" - """The run generating the message exhausted available tokens before completion.""" - RUN_CANCELLED = "run_cancelled" - """The run generating the message was cancelled before completion.""" - RUN_FAILED = "run_failed" - """The run generating the message failed.""" - RUN_EXPIRED = "run_expired" - """The run generating the message expired.""" - - -class MessageRole(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The possible values for roles attributed to messages in a thread.""" - - USER = "user" - """The role representing the end-user.""" - AGENT = "assistant" - """The role representing the agent.""" - + """Custom Keys""" -class MessageStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The possible execution status values for a thread message.""" - IN_PROGRESS = "in_progress" - """A run is currently creating this message.""" - INCOMPLETE = "incomplete" - """This message is incomplete. See incomplete_details for more information.""" - COMPLETED = "completed" - """This message was successfully completed by a run.""" +class CredentialType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The credential type used by the connection.""" - -class MessageStreamEvent(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Message operation related streaming events.""" - - THREAD_MESSAGE_CREATED = "thread.message.created" - """Event sent when a new message is created. The data of this event is of type ThreadMessage""" - THREAD_MESSAGE_IN_PROGRESS = "thread.message.in_progress" - """Event sent when a message moves to ``in_progress`` status. The data of this event is of type - ThreadMessage""" - THREAD_MESSAGE_DELTA = "thread.message.delta" - """Event sent when a message is being streamed. The data of this event is of type - MessageDeltaChunk""" - THREAD_MESSAGE_COMPLETED = "thread.message.completed" - """Event sent when a message is completed. The data of this event is of type ThreadMessage""" - THREAD_MESSAGE_INCOMPLETE = "thread.message.incomplete" - """Event sent before a message is completed. The data of this event is of type ThreadMessage""" - - -class OpenApiAuthType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Authentication type for OpenApi endpoint. Allowed types are: - - * Anonymous (no authentication required) - * Connection (requires connection_id to endpoint, as setup in AI Foundry) - * Managed_Identity (requires audience for identity based auth). - """ - - ANONYMOUS = "anonymous" - CONNECTION = "connection" - MANAGED_IDENTITY = "managed_identity" - - -class ResponseFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Possible API response formats.""" - - TEXT = "text" - """``text`` format should be used for requests involving any sort of ToolCall.""" - JSON_OBJECT = "json_object" - """Using ``json_object`` format will limit the usage of ToolCall to only functions.""" - - -class RunAdditionalFieldList(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """A list of additional fields to include in the response.""" - - FILE_SEARCH_CONTENTS = "step_details.tool_calls[*].file_search.results[*].content" - """File search result content.""" - - -class RunStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Possible values for the status of an agent thread run.""" - - QUEUED = "queued" - """Represents a run that is queued to start.""" - IN_PROGRESS = "in_progress" - """Represents a run that is in progress.""" - REQUIRES_ACTION = "requires_action" - """Represents a run that needs another operation, such as tool output submission, to continue.""" - CANCELLING = "cancelling" - """Represents a run that is in the process of cancellation.""" - CANCELLED = "cancelled" - """Represents a run that has been cancelled.""" - FAILED = "failed" - """Represents a run that failed.""" - COMPLETED = "completed" - """Represents a run that successfully completed.""" - EXPIRED = "expired" - """Represents a run that expired before it could otherwise finish.""" - - -class RunStepErrorCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Possible error code values attributable to a failed run step.""" - - SERVER_ERROR = "server_error" - """Represents a server error.""" - RATE_LIMIT_EXCEEDED = "rate_limit_exceeded" - """Represents an error indicating configured rate limits were exceeded.""" - - -class RunStepStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Possible values for the status of a run step.""" - - IN_PROGRESS = "in_progress" - """Represents a run step still in progress.""" - CANCELLED = "cancelled" - """Represents a run step that was cancelled.""" - FAILED = "failed" - """Represents a run step that failed.""" - COMPLETED = "completed" - """Represents a run step that successfully completed.""" - EXPIRED = "expired" - """Represents a run step that expired before otherwise finishing.""" - - -class RunStepStreamEvent(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Run step operation related streaming events.""" - - THREAD_RUN_STEP_CREATED = "thread.run.step.created" - """Event sent when a new thread run step is created. The data of this event is of type RunStep""" - THREAD_RUN_STEP_IN_PROGRESS = "thread.run.step.in_progress" - """Event sent when a run step moves to ``in_progress`` status. The data of this event is of type - RunStep""" - THREAD_RUN_STEP_DELTA = "thread.run.step.delta" - """Event sent when a run step is being streamed. The data of this event is of type - RunStepDeltaChunk""" - THREAD_RUN_STEP_COMPLETED = "thread.run.step.completed" - """Event sent when a run step is completed. The data of this event is of type RunStep""" - THREAD_RUN_STEP_FAILED = "thread.run.step.failed" - """Event sent when a run step fails. The data of this event is of type RunStep""" - THREAD_RUN_STEP_CANCELLED = "thread.run.step.cancelled" - """Event sent when a run step is cancelled. The data of this event is of type RunStep""" - THREAD_RUN_STEP_EXPIRED = "thread.run.step.expired" - """Event sent when a run step is expired. The data of this event is of type RunStep""" - - -class RunStepType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The possible types of run steps.""" - - MESSAGE_CREATION = "message_creation" - """Represents a run step to create a message.""" - TOOL_CALLS = "tool_calls" - """Represents a run step that calls tools.""" - - -class RunStreamEvent(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Run operation related streaming events.""" - - THREAD_RUN_CREATED = "thread.run.created" - """Event sent when a new run is created. The data of this event is of type ThreadRun""" - THREAD_RUN_QUEUED = "thread.run.queued" - """Event sent when a run moves to ``queued`` status. The data of this event is of type ThreadRun""" - THREAD_RUN_IN_PROGRESS = "thread.run.in_progress" - """Event sent when a run moves to ``in_progress`` status. The data of this event is of type - ThreadRun""" - THREAD_RUN_REQUIRES_ACTION = "thread.run.requires_action" - """Event sent when a run moves to ``requires_action`` status. The data of this event is of type - ThreadRun""" - THREAD_RUN_COMPLETED = "thread.run.completed" - """Event sent when a run is completed. The data of this event is of type ThreadRun""" - THREAD_RUN_INCOMPLETE = "thread.run.incomplete" - """Event sent when a run ends incomplete. The data of this event is of type ThreadRun""" - THREAD_RUN_FAILED = "thread.run.failed" - """Event sent when a run fails. The data of this event is of type ThreadRun""" - THREAD_RUN_CANCELLING = "thread.run.cancelling" - """Event sent when a run moves to ``cancelling`` status. The data of this event is of type - ThreadRun""" - THREAD_RUN_CANCELLED = "thread.run.cancelled" - """Event sent when a run is cancelled. The data of this event is of type ThreadRun""" - THREAD_RUN_EXPIRED = "thread.run.expired" - """Event sent when a run is expired. The data of this event is of type ThreadRun""" - - -class ThreadStreamEvent(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Thread operation related streaming events.""" - - THREAD_CREATED = "thread.created" - """Event sent when a new thread is created. The data of this event is of type AgentThread""" - - -class TruncationStrategy(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Possible truncation strategies for the thread.""" - - AUTO = "auto" - """Default value. Messages in the middle of the thread will be dropped to fit the context length - of the model.""" - LAST_MESSAGES = "last_messages" - """The thread will truncate to the ``lastMessages`` count of recent messages.""" - - -class VectorStoreChunkingStrategyRequestType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of chunking strategy.""" - - AUTO = "auto" - STATIC = "static" - - -class VectorStoreChunkingStrategyResponseType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of chunking strategy.""" - - OTHER = "other" - STATIC = "static" - - -class VectorStoreDataSourceAssetType(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Type of vector storage asset. Asset type may be a uri_asset, in this case it should contain - asset URI ID, - in the case of id_asset it should contain the data ID. - """ - - URI_ASSET = "uri_asset" - """Azure URI""" - ID_ASSET = "id_asset" - """The data ID""" - - -class VectorStoreExpirationPolicyAnchor(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Describes the relationship between the days and the expiration of this vector store.""" - - LAST_ACTIVE_AT = "last_active_at" - """The expiration policy is based on the last time the vector store was active.""" - - -class VectorStoreFileBatchStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The status of the vector store file batch.""" - - IN_PROGRESS = "in_progress" - """The vector store is still processing this file batch.""" - COMPLETED = "completed" - """the vector store file batch is ready for use.""" - CANCELLED = "cancelled" - """The vector store file batch was cancelled.""" - FAILED = "failed" - """The vector store file batch failed to process.""" - - -class VectorStoreFileErrorCode(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Error code variants for vector store file processing.""" - - SERVER_ERROR = "server_error" - """An server error occurred.""" - INVALID_FILE = "invalid_file" - """The file is not valid.""" - UNSUPPORTED_FILE = "unsupported_file" - """The file is of unsupported type.""" + API_KEY = "ApiKey" + """API Key credential""" + ENTRA_ID = "AAD" + """Entra ID credential (formerly known as AAD)""" + SAS = "SAS" + """Shared Access Signature (SAS) credential""" + CUSTOM = "CustomKeys" + """Custom credential""" + NONE = "None" + """No credential""" -class VectorStoreFileStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Vector store file status.""" +class DatasetType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Enum to determine the type of data.""" - IN_PROGRESS = "in_progress" - """The file is currently being processed.""" - COMPLETED = "completed" - """The file has been successfully processed.""" - FAILED = "failed" - """The file has failed to process.""" - CANCELLED = "cancelled" - """The file was cancelled.""" + URI_FILE = "uri_file" + """URI file.""" + URI_FOLDER = "uri_folder" + """URI folder.""" -class VectorStoreFileStatusFilter(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Query parameter filter for vector store file retrieval endpoint.""" +class DeploymentType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of DeploymentType.""" - IN_PROGRESS = "in_progress" - """Retrieve only files that are currently being processed""" - COMPLETED = "completed" - """Retrieve only files that have been successfully processed""" - FAILED = "failed" - """Retrieve only files that have failed to process""" - CANCELLED = "cancelled" - """Retrieve only files that were cancelled""" + MODEL_DEPLOYMENT = "ModelDeployment" + """Model deployment""" -class VectorStoreStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Vector store possible status.""" +class IndexType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Type of IndexType.""" - EXPIRED = "expired" - """expired status indicates that this vector store has expired and is no longer available for use.""" - IN_PROGRESS = "in_progress" - """in_progress status indicates that this vector store is still processing files.""" - COMPLETED = "completed" - """completed status indicates that this vector store is ready for use.""" + AZURE_SEARCH = "AzureSearch" + """Azure search""" + COSMOS_DB = "CosmosDBNoSqlVectorStore" + """CosmosDB""" + MANAGED_AZURE_SEARCH = "ManagedAzureSearch" + """Managed Azure Search""" -class WeekDays(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """WeekDay of the schedule - Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday.""" +class PendingUploadType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of pending upload.""" - MONDAY = "Monday" - TUESDAY = "Tuesday" - WEDNESDAY = "Wednesday" - THURSDAY = "Thursday" - FRIDAY = "Friday" - SATURDAY = "Saturday" - SUNDAY = "Sunday" + NONE = "None" + """No pending upload.""" + BLOB_REFERENCE = "BlobReference" + """Blob Reference is the only supported type.""" + + +class RiskCategory(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Risk category for the attack objective.""" + + HATE_UNFAIRNESS = "HateUnfairness" + """Represents content related to hate or unfairness.""" + VIOLENCE = "Violence" + """Represents content related to violence.""" + SEXUAL = "Sexual" + """Represents content of a sexual nature.""" + SELF_HARM = "SelfHarm" + """Represents content related to self-harm.""" 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 718754ae47b1..81734157a08e 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 @@ -8,133 +8,47 @@ # -------------------------------------------------------------------------- # pylint: disable=useless-super-delegation -import datetime from typing import Any, Dict, List, Literal, Mapping, Optional, TYPE_CHECKING, Union, overload -from .. import _model_base -from .._model_base import rest_discriminator, rest_field -from .._vendor import FileType -from ._enums import ( - AuthenticationType, - MessageBlockType, - OpenApiAuthType, - RunStepType, - VectorStoreChunkingStrategyRequestType, - VectorStoreChunkingStrategyResponseType, -) +from .._utils.model_base import Model as _Model, rest_discriminator, rest_field +from ._enums import CredentialType, DatasetType, DeploymentType, IndexType, PendingUploadType if TYPE_CHECKING: - from .. import _types, models as _models + from .. import models as _models -class Agent(_model_base.Model): - """Represents an agent that can call the model and use tools. +class AgentEvaluation(_Model): + """Evaluation response for agent evaluation run. - :ivar id: The identifier, which can be referenced in API endpoints. Required. + :ivar id: Identifier of the agent evaluation run. Required. :vartype id: str - :ivar object: The object type, which is always assistant. Required. Default value is - "assistant". - :vartype object: str - :ivar created_at: The Unix timestamp, in seconds, representing when this object was created. - Required. - :vartype created_at: ~datetime.datetime - :ivar name: The name of the agent. Required. - :vartype name: str - :ivar description: The description of the agent. Required. - :vartype description: str - :ivar model: The ID of the model to use. Required. - :vartype model: str - :ivar instructions: The system instructions for the agent to use. Required. - :vartype instructions: str - :ivar tools: The collection of tools enabled for the agent. Required. - :vartype tools: list[~azure.ai.projects.models.ToolDefinition] - :ivar tool_resources: A set of resources that are used by the agent's tools. The resources are - specific to the type of tool. For example, the ``code_interpreter`` - tool requires a list of file IDs, while the ``file_search`` tool requires a list of vector - store IDs. Required. - :vartype tool_resources: ~azure.ai.projects.models.ToolResources - :ivar temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output more random, - while lower values like 0.2 will make it more focused and deterministic. Required. - :vartype temperature: float - :ivar top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Required. - :vartype top_p: float - :ivar response_format: The response format of the tool calls used by this agent. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat, ResponseFormatJsonSchemaType - :vartype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat or - ~azure.ai.projects.models.ResponseFormatJsonSchemaType - :ivar metadata: A set of up to 16 key/value pairs that can be attached to an object, used for - storing additional information about that object in a structured format. Keys may be up to 64 - characters in length and values may be up to 512 characters in length. Required. - :vartype metadata: dict[str, str] + :ivar status: Status of the agent evaluation. Options: Running, Completed, Failed. Required. + :vartype status: str + :ivar error: The reason of the request failure for the long running process, if applicable. + :vartype error: str + :ivar result: The agent evaluation result. + :vartype result: list[~azure.ai.projects.models.AgentEvaluationResult] """ id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The identifier, which can be referenced in API endpoints. Required.""" - object: Literal["assistant"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always assistant. Required. Default value is \"assistant\".""" - created_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp, in seconds, representing when this object was created. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the agent. Required.""" - description: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The description of the agent. Required.""" - model: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the model to use. Required.""" - instructions: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The system instructions for the agent to use. Required.""" - tools: List["_models.ToolDefinition"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The collection of tools enabled for the agent. Required.""" - tool_resources: "_models.ToolResources" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A set of resources that are used by the agent's tools. The resources are specific to the type - of tool. For example, the ``code_interpreter`` - tool requires a list of file IDs, while the ``file_search`` tool requires a list of vector - store IDs. Required.""" - temperature: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output - more random, - while lower values like 0.2 will make it more focused and deterministic. Required.""" - top_p: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """An alternative to sampling with temperature, called nucleus sampling, where the model considers - the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Required.""" - response_format: Optional["_types.AgentsApiResponseFormatOption"] = rest_field( + """Identifier of the agent evaluation run. Required.""" + status: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Status of the agent evaluation. Options: Running, Completed, Failed. Required.""" + error: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """The reason of the request failure for the long running process, if applicable.""" + result: Optional[List["_models.AgentEvaluationResult"]] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) - """The response format of the tool calls used by this agent. Is one of the following types: str, - Union[str, \"_models.AgentsApiResponseFormatMode\"], AgentsApiResponseFormat, - ResponseFormatJsonSchemaType""" - metadata: Dict[str, str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A set of up to 16 key/value pairs that can be attached to an object, used for storing - additional information about that object in a structured format. Keys may be up to 64 - characters in length and values may be up to 512 characters in length. Required.""" + """The agent evaluation result.""" @overload def __init__( self, *, id: str, # pylint: disable=redefined-builtin - created_at: datetime.datetime, - name: str, - description: str, - model: str, - instructions: str, - tools: List["_models.ToolDefinition"], - tool_resources: "_models.ToolResources", - temperature: float, - top_p: float, - metadata: Dict[str, str], - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, + status: str, + error: Optional[str] = None, + result: Optional[List["_models.AgentEvaluationResult"]] = None, ) -> None: ... @overload @@ -146,35 +60,26 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.object: Literal["assistant"] = "assistant" -class AgentDeletionStatus(_model_base.Model): - """The status of an agent deletion operation. +class AgentEvaluationRedactionConfiguration(_Model): + """The redaction configuration will allow the user to control what is redacted. - :ivar id: The ID of the resource specified for deletion. Required. - :vartype id: str - :ivar deleted: A value indicating whether deletion was successful. Required. - :vartype deleted: bool - :ivar object: The object type, which is always 'assistant.deleted'. Required. Default value is - "assistant.deleted". - :vartype object: str + :ivar redact_score_properties: Redact score properties. If not specified, the default is to + redact in production. + :vartype redact_score_properties: bool """ - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the resource specified for deletion. Required.""" - deleted: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A value indicating whether deletion was successful. Required.""" - object: Literal["assistant.deleted"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always 'assistant.deleted'. Required. Default value is - \"assistant.deleted\".""" + redact_score_properties: Optional[bool] = rest_field( + name="redactScoreProperties", visibility=["read", "create", "update", "delete", "query"] + ) + """Redact score properties. If not specified, the default is to redact in production.""" @overload def __init__( self, *, - id: str, # pylint: disable=redefined-builtin - deleted: bool, + redact_score_properties: Optional[bool] = None, ) -> None: ... @overload @@ -186,29 +91,61 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.object: Literal["assistant.deleted"] = "assistant.deleted" -class AgentsApiResponseFormat(_model_base.Model): - """An object describing the expected output of the model. If ``json_object`` only ``function`` - type ``tools`` are allowed to be passed to the Run. - If ``text`` the model can return text or any value needed. +class AgentEvaluationRequest(_Model): + """Evaluation request for agent run. - :ivar type: Must be one of ``text`` or ``json_object``. Known values are: "text" and - "json_object". - :vartype type: str or ~azure.ai.projects.models.ResponseFormat + :ivar run_id: Identifier of the agent run. Required. + :vartype run_id: str + :ivar thread_id: Identifier of the agent thread. This field is mandatory currently, but it will + be optional in the future. + :vartype thread_id: str + :ivar evaluators: Evaluators to be used for the evaluation. Required. + :vartype evaluators: dict[str, ~azure.ai.projects.models.EvaluatorConfiguration] + :ivar sampling_configuration: Sampling configuration for the evaluation. + :vartype sampling_configuration: ~azure.ai.projects.models.AgentEvaluationSamplingConfiguration + :ivar redaction_configuration: Redaction configuration for the evaluation. + :vartype redaction_configuration: + ~azure.ai.projects.models.AgentEvaluationRedactionConfiguration + :ivar app_insights_connection_string: Pass the AppInsights connection string to the agent + evaluation for the evaluation results and the errors logs. Required. + :vartype app_insights_connection_string: str """ - type: Optional[Union[str, "_models.ResponseFormat"]] = rest_field( + run_id: str = rest_field(name="runId", visibility=["read", "create", "update", "delete", "query"]) + """Identifier of the agent run. Required.""" + thread_id: Optional[str] = rest_field(name="threadId", visibility=["read", "create", "update", "delete", "query"]) + """Identifier of the agent thread. This field is mandatory currently, but it will be optional in + the future.""" + evaluators: Dict[str, "_models.EvaluatorConfiguration"] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) - """Must be one of ``text`` or ``json_object``. Known values are: \"text\" and \"json_object\".""" + """Evaluators to be used for the evaluation. Required.""" + sampling_configuration: Optional["_models.AgentEvaluationSamplingConfiguration"] = rest_field( + name="samplingConfiguration", visibility=["read", "create", "update", "delete", "query"] + ) + """Sampling configuration for the evaluation.""" + redaction_configuration: Optional["_models.AgentEvaluationRedactionConfiguration"] = rest_field( + name="redactionConfiguration", visibility=["read", "create", "update", "delete", "query"] + ) + """Redaction configuration for the evaluation.""" + app_insights_connection_string: str = rest_field( + name="appInsightsConnectionString", visibility=["read", "create", "update", "delete", "query"] + ) + """Pass the AppInsights connection string to the agent evaluation for the evaluation results and + the errors logs. Required.""" @overload def __init__( self, *, - type: Optional[Union[str, "_models.ResponseFormat"]] = None, + run_id: str, + evaluators: Dict[str, "_models.EvaluatorConfiguration"], + app_insights_connection_string: str, + thread_id: Optional[str] = None, + sampling_configuration: Optional["_models.AgentEvaluationSamplingConfiguration"] = None, + redaction_configuration: Optional["_models.AgentEvaluationRedactionConfiguration"] = None, ) -> None: ... @overload @@ -222,34 +159,67 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AgentsNamedToolChoice(_model_base.Model): - """Specifies a tool the model should use. Use to force the model to call a specific tool. +class AgentEvaluationResult(_Model): + """Result for the agent evaluation evaluator run. - :ivar type: the type of tool. If type is ``function``, the function name must be set. Required. - Known values are: "function", "code_interpreter", "file_search", "bing_grounding", - "fabric_dataagent", "sharepoint_grounding", "azure_ai_search", "bing_custom_search", and - "connected_agent". - :vartype type: str or ~azure.ai.projects.models.AgentsNamedToolChoiceType - :ivar function: The name of the function to call. - :vartype function: ~azure.ai.projects.models.FunctionName + :ivar evaluator: Evaluator's name. This is the name of the evaluator that was used to evaluate + the agent's completion. Required. + :vartype evaluator: str + :ivar score: Score of the given evaluator. No restriction on range. Required. + :vartype score: float + :ivar status: Status of the evaluator result. Options: Running, Completed, Failed, + NotApplicable. Required. + :vartype status: str + :ivar reason: Reasoning for the evaluation result. + :vartype reason: str + :ivar version: Version of the evaluator that was used to evaluate the agent's completion. + :vartype version: str + :ivar thread_id: The unique identifier of the thread. + :vartype thread_id: str + :ivar run_id: The unique identifier of the run. Required. + :vartype run_id: str + :ivar error: A string explaining why there was an error, if applicable. + :vartype error: str + :ivar additional_details: Additional properties relevant to the evaluator. These will differ + between evaluators. + :vartype additional_details: dict[str, str] """ - type: Union[str, "_models.AgentsNamedToolChoiceType"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] + evaluator: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Evaluator's name. This is the name of the evaluator that was used to evaluate the agent's + completion. Required.""" + score: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Score of the given evaluator. No restriction on range. Required.""" + status: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Status of the evaluator result. Options: Running, Completed, Failed, NotApplicable. Required.""" + reason: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Reasoning for the evaluation result.""" + version: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Version of the evaluator that was used to evaluate the agent's completion.""" + thread_id: Optional[str] = rest_field(name="threadId", visibility=["read", "create", "update", "delete", "query"]) + """The unique identifier of the thread.""" + run_id: str = rest_field(name="runId", visibility=["read", "create", "update", "delete", "query"]) + """The unique identifier of the run. Required.""" + error: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """A string explaining why there was an error, if applicable.""" + additional_details: Optional[Dict[str, str]] = rest_field( + name="additionalDetails", visibility=["read", "create", "update", "delete", "query"] ) - """the type of tool. If type is ``function``, the function name must be set. Required. Known - values are: \"function\", \"code_interpreter\", \"file_search\", \"bing_grounding\", - \"fabric_dataagent\", \"sharepoint_grounding\", \"azure_ai_search\", \"bing_custom_search\", - and \"connected_agent\".""" - function: Optional["_models.FunctionName"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the function to call.""" + """Additional properties relevant to the evaluator. These will differ between evaluators.""" @overload def __init__( self, *, - type: Union[str, "_models.AgentsNamedToolChoiceType"], - function: Optional["_models.FunctionName"] = None, + evaluator: str, + score: float, + status: str, + run_id: str, + reason: Optional[str] = None, + version: Optional[str] = None, + thread_id: Optional[str] = None, + error: Optional[str] = None, + additional_details: Optional[Dict[str, str]] = None, ) -> None: ... @overload @@ -263,55 +233,35 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AgentThread(_model_base.Model): - """Information about a single thread associated with an agent. +class AgentEvaluationSamplingConfiguration(_Model): + """Definition for sampling strategy. - :ivar id: The identifier, which can be referenced in API endpoints. Required. - :vartype id: str - :ivar object: The object type, which is always 'thread'. Required. Default value is "thread". - :vartype object: str - :ivar created_at: The Unix timestamp, in seconds, representing when this object was created. - Required. - :vartype created_at: ~datetime.datetime - :ivar tool_resources: A set of resources that are made available to the agent's tools in this - thread. The resources are specific to the type - of tool. For example, the ``code_interpreter`` tool requires a list of file IDs, while the - ``file_search`` tool requires a list - of vector store IDs. Required. - :vartype tool_resources: ~azure.ai.projects.models.ToolResources - :ivar metadata: A set of up to 16 key/value pairs that can be attached to an object, used for - storing additional information about that object in a structured format. Keys may be up to 64 - characters in length and values may be up to 512 characters in length. Required. - :vartype metadata: dict[str, str] + :ivar name: Name of the sampling strategy. Required. + :vartype name: str + :ivar sampling_percent: Percentage of sampling per hour (0-100). Required. + :vartype sampling_percent: float + :ivar max_request_rate: Maximum request rate per hour (0 to 1000). Required. + :vartype max_request_rate: float """ - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The identifier, which can be referenced in API endpoints. Required.""" - object: Literal["thread"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always 'thread'. Required. Default value is \"thread\".""" - created_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" + name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Name of the sampling strategy. Required.""" + sampling_percent: float = rest_field( + name="samplingPercent", visibility=["read", "create", "update", "delete", "query"] ) - """The Unix timestamp, in seconds, representing when this object was created. Required.""" - tool_resources: "_models.ToolResources" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A set of resources that are made available to the agent's tools in this thread. The resources - are specific to the type - of tool. For example, the ``code_interpreter`` tool requires a list of file IDs, while the - ``file_search`` tool requires a list - of vector store IDs. Required.""" - metadata: Dict[str, str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A set of up to 16 key/value pairs that can be attached to an object, used for storing - additional information about that object in a structured format. Keys may be up to 64 - characters in length and values may be up to 512 characters in length. Required.""" + """Percentage of sampling per hour (0-100). Required.""" + max_request_rate: float = rest_field( + name="maxRequestRate", visibility=["read", "create", "update", "delete", "query"] + ) + """Maximum request rate per hour (0 to 1000). Required.""" @overload def __init__( self, *, - id: str, # pylint: disable=redefined-builtin - created_at: datetime.datetime, - tool_resources: "_models.ToolResources", - metadata: Dict[str, str], + name: str, + sampling_percent: float, + max_request_rate: float, ) -> None: ... @overload @@ -323,50 +273,30 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.object: Literal["thread"] = "thread" - - -class AgentThreadCreationOptions(_model_base.Model): - """The details used to create a new agent thread. - - :ivar messages: The initial messages to associate with the new thread. - :vartype messages: list[~azure.ai.projects.models.ThreadMessageOptions] - :ivar tool_resources: A set of resources that are made available to the agent's tools in this - thread. The resources are specific to the - type of tool. For example, the ``code_interpreter`` tool requires a list of file IDs, while the - ``file_search`` tool requires - a list of vector store IDs. - :vartype tool_resources: ~azure.ai.projects.models.ToolResources - :ivar metadata: A set of up to 16 key/value pairs that can be attached to an object, used for - storing additional information about that object in a structured format. Keys may be up to 64 - characters in length and values may be up to 512 characters in length. - :vartype metadata: dict[str, str] + + +class BaseCredentials(_Model): + """A base class for connection credentials. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + EntraIDCredentials, ApiKeyCredentials, CustomCredential, NoAuthenticationCredentials, + SASCredentials + + :ivar type: The type of credential used by the connection. Required. Known values are: + "ApiKey", "AAD", "SAS", "CustomKeys", and "None". + :vartype type: str or ~azure.ai.projects.models.CredentialType """ - messages: Optional[List["_models.ThreadMessageOptions"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The initial messages to associate with the new thread.""" - tool_resources: Optional["_models.ToolResources"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """A set of resources that are made available to the agent's tools in this thread. The resources - are specific to the - type of tool. For example, the ``code_interpreter`` tool requires a list of file IDs, while the - ``file_search`` tool requires - a list of vector store IDs.""" - metadata: Optional[Dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A set of up to 16 key/value pairs that can be attached to an object, used for storing - additional information about that object in a structured format. Keys may be up to 64 - characters in length and values may be up to 512 characters in length.""" + __mapping__: Dict[str, _Model] = {} + type: str = rest_discriminator(name="type", visibility=["read"]) + """The type of credential used by the connection. Required. Known values are: \"ApiKey\", \"AAD\", + \"SAS\", \"CustomKeys\", and \"None\".""" @overload def __init__( self, *, - messages: Optional[List["_models.ThreadMessageOptions"]] = None, - tool_resources: Optional["_models.ToolResources"] = None, - metadata: Optional[Dict[str, str]] = None, + type: str, ) -> None: ... @overload @@ -380,46 +310,23 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AISearchIndexResource(_model_base.Model): - """A AI Search Index resource. +class ApiKeyCredentials(BaseCredentials, discriminator="ApiKey"): + """API Key Credential definition. - :ivar index_connection_id: An index connection id in an IndexResource attached to this agent. - Required. - :vartype index_connection_id: str - :ivar index_name: The name of an index in an IndexResource attached to this agent. Required. - :vartype index_name: str - :ivar query_type: Type of query in an AIIndexResource attached to this agent. Known values are: - "simple", "semantic", "vector", "vector_simple_hybrid", and "vector_semantic_hybrid". - :vartype query_type: str or ~azure.ai.projects.models.AzureAISearchQueryType - :ivar top_k: Number of documents to retrieve from search and present to the model. - :vartype top_k: int - :ivar filter: Odata filter string for search resource. - :vartype filter: str + :ivar type: The credentail type. Required. API Key credential + :vartype type: str or ~azure.ai.projects.models.API_KEY + :ivar api_key: API Key. + :vartype api_key: str """ - index_connection_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """An index connection id in an IndexResource attached to this agent. Required.""" - index_name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of an index in an IndexResource attached to this agent. Required.""" - query_type: Optional[Union[str, "_models.AzureAISearchQueryType"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Type of query in an AIIndexResource attached to this agent. Known values are: \"simple\", - \"semantic\", \"vector\", \"vector_simple_hybrid\", and \"vector_semantic_hybrid\".""" - top_k: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Number of documents to retrieve from search and present to the model.""" - filter: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Odata filter string for search resource.""" + type: Literal[CredentialType.API_KEY] = rest_discriminator(name="type", visibility=["read"]) # type: ignore + """The credentail type. Required. API Key credential""" + api_key: Optional[str] = rest_field(name="key", visibility=["read"]) + """API Key.""" @overload def __init__( self, - *, - index_connection_id: str, - index_name: str, - query_type: Optional[Union[str, "_models.AzureAISearchQueryType"]] = None, - top_k: Optional[int] = None, - filter: Optional[str] = None, # pylint: disable=redefined-builtin ) -> None: ... @overload @@ -430,28 +337,26 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: """ def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) + super().__init__(*args, type=CredentialType.API_KEY, **kwargs) -class TargetModelConfig(_model_base.Model): - """Abstract class for model configuration. +class AssetCredentialResponse(_Model): + """Represents a reference to a blob for consumption. - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - AOAIModelConfig, MAASModelConfig - - :ivar type: Type of the model configuration. Required. Default value is None. - :vartype type: str + :ivar blob_reference: Credential info to access the storage account. Required. + :vartype blob_reference: ~azure.ai.projects.models.BlobReference """ - __mapping__: Dict[str, _model_base.Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Type of the model configuration. Required. Default value is None.""" + blob_reference: "_models.BlobReference" = rest_field( + name="blobReference", visibility=["read", "create", "update", "delete", "query"] + ) + """Credential info to access the storage account. Required.""" @overload def __init__( self, *, - type: str, + blob_reference: "_models.BlobReference", ) -> None: ... @overload @@ -465,38 +370,49 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AOAIModelConfig(TargetModelConfig, discriminator="AOAI"): - """Azure OpenAI model configuration. The API version would be selected by the service for querying - the model. +class Index(_Model): + """Index resource Definition. - :ivar type: Required. Default value is "AOAI". - :vartype type: str - :ivar azure_endpoint: Endpoint targetURI for AOAI model. Required. - :vartype azure_endpoint: str - :ivar api_key: API Key for AOAI model. Required. - :vartype api_key: str - :ivar azure_deployment: Deployment name for AOAI model. Required. - :vartype azure_deployment: str + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + AzureAISearchIndex, CosmosDBIndex, ManagedAzureAISearchIndex + + :ivar type: Type of index. Required. Known values are: "AzureSearch", + "CosmosDBNoSqlVectorStore", and "ManagedAzureSearch". + :vartype type: str or ~azure.ai.projects.models.IndexType + :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] """ - type: Literal["AOAI"] = rest_discriminator(name="type", visibility=["read"]) # type: ignore - """Required. Default value is \"AOAI\".""" - azure_endpoint: str = rest_field(name="azureEndpoint", visibility=["read", "create", "update", "delete", "query"]) - """Endpoint targetURI for AOAI model. Required.""" - api_key: str = rest_field(name="apiKey", visibility=["read", "create", "update", "delete", "query"]) - """API Key for AOAI model. Required.""" - azure_deployment: str = rest_field( - name="azureDeployment", visibility=["read", "create", "update", "delete", "query"] - ) - """Deployment name for AOAI model. Required.""" + __mapping__: Dict[str, _Model] = {} + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """Type of index. Required. Known values are: \"AzureSearch\", \"CosmosDBNoSqlVectorStore\", and + \"ManagedAzureSearch\".""" + 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=["create", "update"]) + """The asset description text.""" + tags: Optional[Dict[str, str]] = rest_field(visibility=["create", "update"]) + """Tag dictionary. Tags can be added, removed, and updated.""" @overload def __init__( self, *, - azure_endpoint: str, - api_key: str, - azure_deployment: str, + type: str, + description: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, ) -> None: ... @overload @@ -507,26 +423,45 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: """ def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="AOAI", **kwargs) + super().__init__(*args, **kwargs) -class AppInsightsProperties(_model_base.Model): - """The properties of the Application Insights resource. +class AzureAISearchIndex(Index, discriminator="AzureSearch"): + """Azure AI Search Index Definition. - :ivar connection_string: Authentication type of the connection target. Required. - :vartype connection_string: str + :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. Azure search + :vartype type: str or ~azure.ai.projects.models.AZURE_SEARCH + :ivar connection_name: Name of connection to Azure AI Search. Required. + :vartype connection_name: str + :ivar index_name: Name of index in Azure AI Search resource to attach. Required. + :vartype index_name: str """ - connection_string: str = rest_field( - name="ConnectionString", visibility=["read", "create", "update", "delete", "query"] - ) - """Authentication type of the connection target. Required.""" + type: Literal[IndexType.AZURE_SEARCH] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Type of index. Required. Azure search""" + connection_name: str = rest_field(name="connectionName", visibility=["create"]) + """Name of connection to Azure AI Search. Required.""" + index_name: str = rest_field(name="indexName", visibility=["create"]) + """Name of index in Azure AI Search resource to attach. Required.""" @overload def __init__( self, *, - connection_string: str, + connection_name: str, + index_name: str, + description: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, ) -> None: ... @overload @@ -537,22 +472,22 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: """ def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) + super().__init__(*args, type=IndexType.AZURE_SEARCH, **kwargs) -class InputData(_model_base.Model): - """Abstract data class for input data configuration. +class TargetConfig(_Model): + """Abstract class for target configuration. You probably want to use the sub-classes and not this class directly. Known sub-classes are: - ApplicationInsightsConfiguration, Dataset + AzureOpenAIModelConfiguration - :ivar type: Type of the data. Required. Default value is None. + :ivar type: Type of the model configuration. Required. Default value is None. :vartype type: str """ - __mapping__: Dict[str, _model_base.Model] = {} + __mapping__: Dict[str, _Model] = {} type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Type of the data. Required. Default value is None.""" + """Type of the model configuration. Required. Default value is None.""" @overload def __init__( @@ -572,45 +507,31 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ApplicationInsightsConfiguration(InputData, discriminator="app_insights"): - """Data Source for Application Insights. +class AzureOpenAIModelConfiguration(TargetConfig, discriminator="AzureOpenAIModel"): + """Azure OpenAI model configuration. The API version would be selected by the service for querying + the model. - :ivar type: Required. Default value is "app_insights". + :ivar type: Required. Default value is "AzureOpenAIModel". :vartype type: str - :ivar resource_id: LogAnalytic Workspace resourceID associated with ApplicationInsights. + :ivar model_deployment_name: Deployment name for AOAI model. Example: gpt-4o if in AIServices + or connection based ``connection_name/deployment_name`` (i.e. ``my-aoai-connection/gpt-4o``. Required. - :vartype resource_id: str - :ivar query: Query to fetch the data. Required. - :vartype query: str - :ivar service_name: Service name. - :vartype service_name: str - :ivar connection_string: Connection String to connect to ApplicationInsights. - :vartype connection_string: str + :vartype model_deployment_name: str """ - type: Literal["app_insights"] = rest_discriminator(name="type", visibility=["read"]) # type: ignore - """Required. Default value is \"app_insights\".""" - resource_id: str = rest_field(name="resourceId", visibility=["read", "create", "update", "delete", "query"]) - """LogAnalytic Workspace resourceID associated with ApplicationInsights. Required.""" - query: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Query to fetch the data. Required.""" - service_name: Optional[str] = rest_field( - name="serviceName", visibility=["read", "create", "update", "delete", "query"] + type: Literal["AzureOpenAIModel"] = rest_discriminator(name="type", visibility=["read"]) # type: ignore + """Required. Default value is \"AzureOpenAIModel\".""" + model_deployment_name: str = rest_field( + name="modelDeploymentName", visibility=["read", "create", "update", "delete", "query"] ) - """Service name.""" - connection_string: Optional[str] = rest_field( - name="connectionString", visibility=["read", "create", "update", "delete", "query"] - ) - """Connection String to connect to ApplicationInsights.""" + """Deployment name for AOAI model. Example: gpt-4o if in AIServices or connection based + ``connection_name/deployment_name`` (i.e. ``my-aoai-connection/gpt-4o``. Required.""" @overload def __init__( self, *, - resource_id: str, - query: str, - service_name: Optional[str] = None, - connection_string: Optional[str] = None, + model_deployment_name: str, ) -> None: ... @overload @@ -621,28 +542,39 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: """ def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="app_insights", **kwargs) + super().__init__(*args, type="AzureOpenAIModel", **kwargs) -class AzureAISearchResource(_model_base.Model): - """A set of index resources used by the ``azure_ai_search`` tool. +class BlobReference(_Model): + """Blob reference details. - :ivar index_list: The indices attached to this agent. There can be a maximum of 1 index - resource attached to the agent. - :vartype index_list: list[~azure.ai.projects.models.AISearchIndexResource] + :ivar blob_uri: Blob URI path for client to upload data. Example: + `https://blob.windows.core.net/Container/Path `_. + Required. + :vartype blob_uri: str + :ivar storage_account_arm_id: ARM ID of the storage account to use. Required. + :vartype storage_account_arm_id: str + :ivar credential: Credential info to access the storage account. Required. + :vartype credential: ~azure.ai.projects.models.SasCredential """ - index_list: Optional[List["_models.AISearchIndexResource"]] = rest_field( - name="indexes", visibility=["read", "create", "update", "delete", "query"] + blob_uri: str = rest_field(name="blobUri", visibility=["read", "create", "update", "delete", "query"]) + """Blob URI path for client to upload data. Example: `https://blob.windows.core.net/Container/Path + `_. Required.""" + storage_account_arm_id: str = rest_field( + name="storageAccountArmId", visibility=["read", "create", "update", "delete", "query"] ) - """The indices attached to this agent. There can be a maximum of 1 index - resource attached to the agent.""" + """ARM ID of the storage account to use. Required.""" + credential: "_models.SasCredential" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Credential info to access the storage account. Required.""" @overload def __init__( self, *, - index_list: Optional[List["_models.AISearchIndexResource"]] = None, + blob_uri: str, + storage_account_arm_id: str, + credential: "_models.SasCredential", ) -> None: ... @overload @@ -656,28 +588,90 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ToolDefinition(_model_base.Model): - """An abstract representation of an input tool definition that an agent can use. +class Connection(_Model): + """Response from the list and get connections operations. - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - AzureAISearchToolDefinition, AzureFunctionToolDefinition, BingCustomSearchToolDefinition, - BingGroundingToolDefinition, CodeInterpreterToolDefinition, ConnectedAgentToolDefinition, - MicrosoftFabricToolDefinition, FileSearchToolDefinition, FunctionToolDefinition, - OpenApiToolDefinition, SharepointToolDefinition + :ivar name: The name of the resource. Required. + :vartype name: str + :ivar type: Category of the connection. Required. Known values are: "AzureOpenAI", "AzureBlob", + "AzureStorageAccount", "CognitiveSearch", "CosmosDB", "ApiKey", "AppConfig", "AppInsights", and + "CustomKeys". + :vartype type: str or ~azure.ai.projects.models.ConnectionType + :ivar target: The connection URL to be used for this service. Required. + :vartype target: str + :ivar is_default: Whether the connection is tagged as the default connection of its type. + Required. + :vartype is_default: bool + :ivar credentials: The credentials used by the connection. Required. + :vartype credentials: ~azure.ai.projects.models.BaseCredentials + :ivar metadata: Metadata of the connection. Required. + :vartype metadata: dict[str, str] + """ - :ivar type: The object type. Required. Default value is None. - :vartype type: str + name: str = rest_field(visibility=["read"]) + """The name of the resource. Required.""" + type: Union[str, "_models.ConnectionType"] = rest_field(visibility=["read"]) + """Category of the connection. Required. Known values are: \"AzureOpenAI\", \"AzureBlob\", + \"AzureStorageAccount\", \"CognitiveSearch\", \"CosmosDB\", \"ApiKey\", \"AppConfig\", + \"AppInsights\", and \"CustomKeys\".""" + target: str = rest_field(visibility=["read"]) + """The connection URL to be used for this service. Required.""" + is_default: bool = rest_field(name="isDefault", visibility=["read"]) + """Whether the connection is tagged as the default connection of its type. Required.""" + credentials: "_models.BaseCredentials" = rest_field(visibility=["read"]) + """The credentials used by the connection. Required.""" + metadata: Dict[str, str] = rest_field(visibility=["read"]) + """Metadata of the connection. Required.""" + + +class CosmosDBIndex(Index, discriminator="CosmosDBNoSqlVectorStore"): + """CosmosDB Vector Store Index Definition. + + :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. CosmosDB + :vartype type: str or ~azure.ai.projects.models.COSMOS_DB + :ivar connection_name: Name of connection to CosmosDB. Required. + :vartype connection_name: str + :ivar database_name: Name of the CosmosDB Database. Required. + :vartype database_name: str + :ivar container_name: Name of CosmosDB Container. Required. + :vartype container_name: str + :ivar embedding_configuration: Embedding model configuration. Required. + :vartype embedding_configuration: ~azure.ai.projects.models.EmbeddingConfiguration """ - __mapping__: Dict[str, _model_base.Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The object type. Required. Default value is None.""" + type: Literal[IndexType.COSMOS_DB] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Type of index. Required. CosmosDB""" + connection_name: str = rest_field(name="connectionName", visibility=["create"]) + """Name of connection to CosmosDB. Required.""" + database_name: str = rest_field(name="databaseName", visibility=["create"]) + """Name of the CosmosDB Database. Required.""" + container_name: str = rest_field(name="containerName", visibility=["create"]) + """Name of CosmosDB Container. Required.""" + embedding_configuration: "_models.EmbeddingConfiguration" = rest_field( + name="embeddingConfiguration", visibility=["create"] + ) + """Embedding model configuration. Required.""" @overload def __init__( self, *, - type: str, + connection_name: str, + database_name: str, + container_name: str, + embedding_configuration: "_models.EmbeddingConfiguration", + description: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, ) -> None: ... @overload @@ -688,20 +682,22 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: """ def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) + super().__init__(*args, type=IndexType.COSMOS_DB, **kwargs) -class AzureAISearchToolDefinition(ToolDefinition, discriminator="azure_ai_search"): - """The input definition information for an Azure AI search tool as used to configure an agent. +class CustomCredential(BaseCredentials, discriminator="CustomKeys"): + """Custom credential definition. - :ivar type: The object type, which is always 'azure_ai_search'. Required. Default value is - "azure_ai_search". - :vartype type: str + :ivar type: The credential type. Required. Custom credential + :vartype type: str or ~azure.ai.projects.models.CUSTOM + :ivar credential_keys: The credential type. Required. + :vartype credential_keys: dict[str, str] """ - type: Literal["azure_ai_search"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'azure_ai_search'. Required. Default value is - \"azure_ai_search\".""" + type: Literal[CredentialType.CUSTOM] = rest_discriminator(name="type", visibility=["read"]) # type: ignore + """The credential type. Required. Custom credential""" + credential_keys: Dict[str, str] = rest_field(name="keys", visibility=["read"]) + """The credential type. Required.""" @overload def __init__( @@ -716,32 +712,63 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: """ def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="azure_ai_search", **kwargs) + super().__init__(*args, type=CredentialType.CUSTOM, **kwargs) -class AzureFunctionBinding(_model_base.Model): - """The structure for keeping storage queue name and URI. +class DatasetVersion(_Model): + """DatasetVersion Definition. - :ivar type: The type of binding, which is always 'storage_queue'. Required. Default value is - "storage_queue". - :vartype type: str - :ivar storage_queue: Storage queue. Required. - :vartype storage_queue: ~azure.ai.projects.models.AzureFunctionStorageQueue + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + FileDatasetVersion, FolderDatasetVersion + + :ivar data_uri: URI of the data. Example: `https://go.microsoft.com/fwlink/?linkid=2202330 + `_. Required. + :vartype data_uri: str + :ivar type: Dataset type. Required. Known values are: "uri_file" and "uri_folder". + :vartype type: str or ~azure.ai.projects.models.DatasetType + :ivar is_reference: Indicates if dataset is reference only or managed by dataset service. If + true, the underlying data will be deleted when the dataset version is deleted. + :vartype is_reference: bool + :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] """ - type: Literal["storage_queue"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The type of binding, which is always 'storage_queue'. Required. Default value is - \"storage_queue\".""" - storage_queue: "_models.AzureFunctionStorageQueue" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Storage queue. Required.""" + __mapping__: Dict[str, _Model] = {} + data_uri: str = rest_field(name="dataUri", visibility=["read", "create"]) + """URI of the data. Example: `https://go.microsoft.com/fwlink/?linkid=2202330 + `_. Required.""" + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """Dataset type. Required. Known values are: \"uri_file\" and \"uri_folder\".""" + is_reference: Optional[bool] = rest_field(name="isReference", visibility=["read"]) + """Indicates if dataset is reference only or managed by dataset service. If true, the underlying + data will be deleted when the dataset version is deleted.""" + 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=["create", "update"]) + """The asset description text.""" + tags: Optional[Dict[str, str]] = rest_field(visibility=["create", "update"]) + """Tag dictionary. Tags can be added, removed, and updated.""" @overload def __init__( self, *, - storage_queue: "_models.AzureFunctionStorageQueue", + data_uri: str, + type: str, + description: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, ) -> None: ... @overload @@ -753,42 +780,31 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.type: Literal["storage_queue"] = "storage_queue" -class AzureFunctionDefinition(_model_base.Model): - """The definition of Azure function. +class Deployment(_Model): + """Model Deployment Definition. - :ivar function: The definition of azure function and its parameters. Required. - :vartype function: ~azure.ai.projects.models.FunctionDefinition - :ivar input_binding: Input storage queue. The queue storage trigger runs a function as messages - are added to it. Required. - :vartype input_binding: ~azure.ai.projects.models.AzureFunctionBinding - :ivar output_binding: Output storage queue. The function writes output to this queue when the - input items are processed. Required. - :vartype output_binding: ~azure.ai.projects.models.AzureFunctionBinding + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + ModelDeployment + + :ivar type: The type of the deployment. Required. "ModelDeployment" + :vartype type: str or ~azure.ai.projects.models.DeploymentType + :ivar name: Name of the deployment. Required. + :vartype name: str """ - function: "_models.FunctionDefinition" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The definition of azure function and its parameters. Required.""" - input_binding: "_models.AzureFunctionBinding" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Input storage queue. The queue storage trigger runs a function as messages are added to it. - Required.""" - output_binding: "_models.AzureFunctionBinding" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Output storage queue. The function writes output to this queue when the input items are - processed. Required.""" + __mapping__: Dict[str, _Model] = {} + type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) + """The type of the deployment. Required. \"ModelDeployment\"""" + name: str = rest_field(visibility=["read"]) + """Name of the deployment. Required.""" @overload def __init__( self, *, - function: "_models.FunctionDefinition", - input_binding: "_models.AzureFunctionBinding", - output_binding: "_models.AzureFunctionBinding", + type: str, ) -> None: ... @overload @@ -802,29 +818,28 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AzureFunctionStorageQueue(_model_base.Model): - """The structure for keeping storage queue name and URI. +class EmbeddingConfiguration(_Model): + """Embedding configuration class. - :ivar storage_service_endpoint: URI to the Azure Storage Queue service allowing you to - manipulate a queue. Required. - :vartype storage_service_endpoint: str - :ivar queue_name: The name of an Azure function storage queue. Required. - :vartype queue_name: str + :ivar model_deployment_name: Deployment name of embedding model. It can point to a model + deployment either in the parent AIServices or a connection. Required. + :vartype model_deployment_name: str + :ivar embedding_field: Embedding field. Required. + :vartype embedding_field: str """ - storage_service_endpoint: str = rest_field( - name="queue_service_endpoint", visibility=["read", "create", "update", "delete", "query"] - ) - """URI to the Azure Storage Queue service allowing you to manipulate a queue. Required.""" - queue_name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of an Azure function storage queue. Required.""" + model_deployment_name: str = rest_field(name="modelDeploymentName", visibility=["create"]) + """Deployment name of embedding model. It can point to a model deployment either in the parent + AIServices or a connection. Required.""" + embedding_field: str = rest_field(name="embeddingField", visibility=["create"]) + """Embedding field. Required.""" @overload def __init__( self, *, - storage_service_endpoint: str, - queue_name: str, + model_deployment_name: str, + embedding_field: str, ) -> None: ... @overload @@ -838,30 +853,19 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class AzureFunctionToolDefinition(ToolDefinition, discriminator="azure_function"): - """The input definition information for a azure function tool as used to configure an agent. +class EntraIDCredentials(BaseCredentials, discriminator="AAD"): + """Entra ID credential definition. - :ivar type: The object type, which is always 'azure_function'. Required. Default value is - "azure_function". - :vartype type: str - :ivar azure_function: The definition of the concrete function that the function tool should - call. Required. - :vartype azure_function: ~azure.ai.projects.models.AzureFunctionDefinition + :ivar type: The credential type. Required. Entra ID credential (formerly known as AAD) + :vartype type: str or ~azure.ai.projects.models.ENTRA_ID """ - type: Literal["azure_function"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'azure_function'. Required. Default value is - \"azure_function\".""" - azure_function: "_models.AzureFunctionDefinition" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The definition of the concrete function that the function tool should call. Required.""" + type: Literal[CredentialType.ENTRA_ID] = rest_discriminator(name="type", visibility=["read"]) # type: ignore + """The credential type. Required. Entra ID credential (formerly known as AAD)""" @overload def __init__( self, - *, - azure_function: "_models.AzureFunctionDefinition", ) -> None: ... @overload @@ -872,33 +876,67 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: """ def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="azure_function", **kwargs) + super().__init__(*args, type=CredentialType.ENTRA_ID, **kwargs) -class BingCustomSearchToolDefinition(ToolDefinition, discriminator="bing_custom_search"): - """The input definition information for a Bing custom search tool as used to configure an agent. +class Evaluation(_Model): + """Evaluation Definition. - :ivar type: The object type, which is always 'bing_custom_search'. Required. Default value is - "bing_custom_search". - :vartype type: str - :ivar bing_custom_search: The list of search configurations used by the bing custom search - tool. Required. - :vartype bing_custom_search: ~azure.ai.projects.models.SearchConfigurationList + :ivar name: Identifier of the evaluation. Required. + :vartype name: str + :ivar data: Data for evaluation. Required. + :vartype data: ~azure.ai.projects.models.InputData + :ivar display_name: Display Name for evaluation. It helps to find the evaluation easily in AI + Foundry. It does not need to be unique. + :vartype display_name: str + :ivar description: Description of the evaluation. It can be used to store additional + information about the evaluation and is mutable. + :vartype description: str + :ivar status: Status of the evaluation. It is set by service and is read-only. + :vartype status: str + :ivar tags: Evaluation's tags. Unlike properties, tags are fully mutable. + :vartype tags: dict[str, str] + :ivar properties: Evaluation's properties. Unlike tags, properties are add-only. Once added, a + property cannot be removed. + :vartype properties: dict[str, str] + :ivar evaluators: Evaluators to be used for the evaluation. Required. + :vartype evaluators: dict[str, ~azure.ai.projects.models.EvaluatorConfiguration] """ - type: Literal["bing_custom_search"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'bing_custom_search'. Required. Default value is - \"bing_custom_search\".""" - bing_custom_search: "_models.SearchConfigurationList" = rest_field( + name: str = rest_field(name="id", visibility=["read"]) + """Identifier of the evaluation. Required.""" + data: "_models.InputData" = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Data for evaluation. Required.""" + display_name: Optional[str] = rest_field( + name="displayName", visibility=["read", "create", "update", "delete", "query"] + ) + """Display Name for evaluation. It helps to find the evaluation easily in AI Foundry. It does not + need to be unique.""" + description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Description of the evaluation. It can be used to store additional information about the + evaluation and is mutable.""" + status: Optional[str] = rest_field(visibility=["read"]) + """Status of the evaluation. It is set by service and is read-only.""" + tags: Optional[Dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Evaluation's tags. Unlike properties, tags are fully mutable.""" + properties: Optional[Dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Evaluation's properties. Unlike tags, properties are add-only. Once added, a property cannot be + removed.""" + evaluators: Dict[str, "_models.EvaluatorConfiguration"] = rest_field( visibility=["read", "create", "update", "delete", "query"] ) - """The list of search configurations used by the bing custom search tool. Required.""" + """Evaluators to be used for the evaluation. Required.""" @overload def __init__( self, *, - bing_custom_search: "_models.SearchConfigurationList", + data: "_models.InputData", + evaluators: Dict[str, "_models.EvaluatorConfiguration"], + display_name: Optional[str] = None, + description: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + properties: Optional[Dict[str, str]] = None, ) -> None: ... @overload @@ -909,33 +947,38 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: """ def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="bing_custom_search", **kwargs) + super().__init__(*args, **kwargs) -class BingGroundingToolDefinition(ToolDefinition, discriminator="bing_grounding"): - """The input definition information for a bing grounding search tool as used to configure an - agent. +class EvaluatorConfiguration(_Model): + """Evaluator Configuration. - :ivar type: The object type, which is always 'bing_grounding'. Required. Default value is - "bing_grounding". - :vartype type: str - :ivar bing_grounding: The list of connections used by the bing grounding tool. Required. - :vartype bing_grounding: ~azure.ai.projects.models.ToolConnectionList + :ivar id: Identifier of the evaluator. Required. + :vartype id: str + :ivar init_params: Initialization parameters of the evaluator. + :vartype init_params: dict[str, any] + :ivar data_mapping: Data parameters of the evaluator. + :vartype data_mapping: dict[str, str] """ - type: Literal["bing_grounding"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'bing_grounding'. Required. Default value is - \"bing_grounding\".""" - bing_grounding: "_models.ToolConnectionList" = rest_field( - visibility=["read", "create", "update", "delete", "query"] + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Identifier of the evaluator. Required.""" + init_params: Optional[Dict[str, Any]] = rest_field( + name="initParams", visibility=["read", "create", "update", "delete", "query"] + ) + """Initialization parameters of the evaluator.""" + data_mapping: Optional[Dict[str, str]] = rest_field( + name="dataMapping", visibility=["read", "create", "update", "delete", "query"] ) - """The list of connections used by the bing grounding tool. Required.""" + """Data parameters of the evaluator.""" @overload def __init__( self, *, - bing_grounding: "_models.ToolConnectionList", + id: str, # pylint: disable=redefined-builtin + init_params: Optional[Dict[str, Any]] = None, + data_mapping: Optional[Dict[str, str]] = None, ) -> None: ... @overload @@ -946,24 +989,42 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: """ def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="bing_grounding", **kwargs) + super().__init__(*args, **kwargs) -class CodeInterpreterToolDefinition(ToolDefinition, discriminator="code_interpreter"): - """The input definition information for a code interpreter tool as used to configure an agent. +class FileDatasetVersion(DatasetVersion, discriminator="uri_file"): + """FileDatasetVersion Definition. - :ivar type: The object type, which is always 'code_interpreter'. Required. Default value is - "code_interpreter". - :vartype type: str + :ivar data_uri: URI of the data. Example: `https://go.microsoft.com/fwlink/?linkid=2202330 + `_. Required. + :vartype data_uri: str + :ivar is_reference: Indicates if dataset is reference only or managed by dataset service. If + true, the underlying data will be deleted when the dataset version is deleted. + :vartype is_reference: bool + :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: Dataset type. Required. URI file. + :vartype type: str or ~azure.ai.projects.models.URI_FILE """ - type: Literal["code_interpreter"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'code_interpreter'. Required. Default value is - \"code_interpreter\".""" + type: Literal[DatasetType.URI_FILE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Dataset type. Required. URI file.""" @overload def __init__( self, + *, + data_uri: str, + description: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, ) -> None: ... @overload @@ -974,36 +1035,42 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: """ def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="code_interpreter", **kwargs) + super().__init__(*args, type=DatasetType.URI_FILE, **kwargs) -class CodeInterpreterToolResource(_model_base.Model): - """A set of resources that are used by the ``code_interpreter`` tool. +class FolderDatasetVersion(DatasetVersion, discriminator="uri_folder"): + """FileDatasetVersion Definition. - :ivar file_ids: A list of file IDs made available to the ``code_interpreter`` tool. There can - be a maximum of 20 files - associated with the tool. - :vartype file_ids: list[str] - :ivar data_sources: The data sources to be used. This option is mutually exclusive with the - ``fileIds`` property. - :vartype data_sources: list[~azure.ai.projects.models.VectorStoreDataSource] + :ivar data_uri: URI of the data. Example: `https://go.microsoft.com/fwlink/?linkid=2202330 + `_. Required. + :vartype data_uri: str + :ivar is_reference: Indicates if dataset is reference only or managed by dataset service. If + true, the underlying data will be deleted when the dataset version is deleted. + :vartype is_reference: bool + :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: Dataset type. Required. URI folder. + :vartype type: str or ~azure.ai.projects.models.URI_FOLDER """ - file_ids: Optional[List[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A list of file IDs made available to the ``code_interpreter`` tool. There can be a maximum of - 20 files - associated with the tool.""" - data_sources: Optional[List["_models.VectorStoreDataSource"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The data sources to be used. This option is mutually exclusive with the ``fileIds`` property.""" + type: Literal[DatasetType.URI_FOLDER] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore + """Dataset type. Required. URI folder.""" @overload def __init__( self, *, - file_ids: Optional[List[str]] = None, - data_sources: Optional[List["_models.VectorStoreDataSource"]] = None, + data_uri: str, + description: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, ) -> None: ... @overload @@ -1014,155 +1081,22 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: """ def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) + super().__init__(*args, type=DatasetType.URI_FOLDER, **kwargs) -class ConnectedAgentDetails(_model_base.Model): - """Information for connecting one agent to another as a tool. +class InputData(_Model): + """Abstract data class. - :ivar id: The identifier of the child agent. Required. - :vartype id: str - :ivar name: The name of the agent to be called. Required. - :vartype name: str - :ivar description: A description of what the agent does, used by the model to choose when and - how to call the agent. Required. - :vartype description: str + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + InputDataset + + :ivar type: Type of the data. Required. Default value is None. + :vartype type: str """ - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The identifier of the child agent. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the agent to be called. Required.""" - description: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A description of what the agent does, used by the model to choose when and how to call the - agent. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - name: str, - description: 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 ConnectedAgentToolDefinition(ToolDefinition, discriminator="connected_agent"): - """The input definition information for a connected agent tool which defines a domain specific - sub-agent. - - :ivar type: The object type, which is always 'connected_agent'. Required. Default value is - "connected_agent". - :vartype type: str - :ivar connected_agent: The sub-agent to connect. Required. - :vartype connected_agent: ~azure.ai.projects.models.ConnectedAgentDetails - """ - - type: Literal["connected_agent"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'connected_agent'. Required. Default value is - \"connected_agent\".""" - connected_agent: "_models.ConnectedAgentDetails" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The sub-agent to connect. Required.""" - - @overload - def __init__( - self, - *, - connected_agent: "_models.ConnectedAgentDetails", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="connected_agent", **kwargs) - - -class CredentialsApiKeyAuth(_model_base.Model): - """The credentials needed for API key authentication. - - :ivar key: The API key. Required. - :vartype key: str - """ - - key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The API key. Required.""" - - @overload - def __init__( - self, - *, - key: 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 CredentialsSASAuth(_model_base.Model): - """The credentials needed for Shared Access Signatures (SAS) authentication. - - :ivar sas: The Shared Access Signatures (SAS) token. Required. - :vartype sas: str - """ - - sas: str = rest_field(name="SAS", visibility=["read", "create", "update", "delete", "query"]) - """The Shared Access Signatures (SAS) token. Required.""" - - @overload - def __init__( - self, - *, - sas: 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 Trigger(_model_base.Model): - """Abstract data class for input data configuration. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - CronTrigger, RecurrenceTrigger - - :ivar type: Type of the trigger. Required. Default value is None. - :vartype type: str - """ - - __mapping__: Dict[str, _model_base.Model] = {} + __mapping__: Dict[str, _Model] = {} type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Type of the trigger. Required. Default value is None.""" + """Type of the data. Required. Default value is None.""" @overload def __init__( @@ -1182,39 +1116,7 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class CronTrigger(Trigger, discriminator="Cron"): - """Cron Trigger Definition. - - :ivar type: Required. Default value is "Cron". - :vartype type: str - :ivar expression: Cron expression for the trigger. Required. - :vartype expression: str - """ - - type: Literal["Cron"] = rest_discriminator(name="type", visibility=["read"]) # type: ignore - """Required. Default value is \"Cron\".""" - expression: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Cron expression for the trigger. Required.""" - - @overload - def __init__( - self, - *, - expression: 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, type="Cron", **kwargs) - - -class Dataset(InputData, discriminator="dataset"): +class InputDataset(InputData, discriminator="dataset"): """Dataset as source for evaluation. :ivar type: Required. Default value is "dataset". @@ -1223,7 +1125,7 @@ class Dataset(InputData, discriminator="dataset"): :vartype id: str """ - type: Literal["dataset"] = rest_discriminator(name="type", visibility=["read"]) # type: ignore + type: Literal["dataset"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """Required. Default value is \"dataset\".""" id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Evaluation input data. Required.""" @@ -1246,71 +1148,37 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, type="dataset", **kwargs) -class Evaluation(_model_base.Model): - """Evaluation Definition. +class ManagedAzureAISearchIndex(Index, discriminator="ManagedAzureSearch"): + """Managed Azure AI Search Index Definition. - :ivar id: Identifier of the evaluation. Required. + :ivar id: Asset ID, a unique identifier for the asset. :vartype id: str - :ivar data: Data for evaluation. Required. - :vartype data: ~azure.ai.projects.models.InputData - :ivar target: Evaluation target specifying the model config and parameters. - :vartype target: ~azure.ai.projects.models.EvaluationTarget - :ivar display_name: Display Name for evaluation. It helps to find the evaluation easily in AI - Foundry. It does not need to be unique. - :vartype display_name: str - :ivar description: Description of the evaluation. It can be used to store additional - information about the evaluation and is mutable. + :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 system_data: Metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.ai.projects.models.SystemData - :ivar status: Status of the evaluation. It is set by service and is read-only. - :vartype status: str - :ivar tags: Evaluation's tags. Unlike properties, tags are fully mutable. + :ivar tags: Tag dictionary. Tags can be added, removed, and updated. :vartype tags: dict[str, str] - :ivar properties: Evaluation's properties. Unlike tags, properties are add-only. Once added, a - property cannot be removed. - :vartype properties: dict[str, str] - :ivar evaluators: Evaluators to be used for the evaluation. Required. - :vartype evaluators: dict[str, ~azure.ai.projects.models.EvaluatorConfiguration] + :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 """ - id: str = rest_field(visibility=["read"]) - """Identifier of the evaluation. Required.""" - data: "_models.InputData" = rest_field(visibility=["read", "create"]) - """Data for evaluation. Required.""" - target: Optional["_models.EvaluationTarget"] = rest_field(visibility=["read", "create"]) - """Evaluation target specifying the model config and parameters.""" - display_name: Optional[str] = rest_field( - name="displayName", visibility=["read", "create", "update", "delete", "query"] - ) - """Display Name for evaluation. It helps to find the evaluation easily in AI Foundry. It does not - need to be unique.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Description of the evaluation. It can be used to store additional information about the - evaluation and is mutable.""" - system_data: Optional["_models.SystemData"] = rest_field(name="systemData", visibility=["read"]) - """Metadata containing createdBy and modifiedBy information.""" - status: Optional[str] = rest_field(visibility=["read"]) - """Status of the evaluation. It is set by service and is read-only.""" - tags: Optional[Dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Evaluation's tags. Unlike properties, tags are fully mutable.""" - properties: Optional[Dict[str, str]] = rest_field(visibility=["read", "create"]) - """Evaluation's properties. Unlike tags, properties are add-only. Once added, a property cannot be - removed.""" - evaluators: Dict[str, "_models.EvaluatorConfiguration"] = rest_field(visibility=["read", "create"]) - """Evaluators to be used for the evaluation. Required.""" + 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, *, - data: "_models.InputData", - evaluators: Dict[str, "_models.EvaluatorConfiguration"], - target: Optional["_models.EvaluationTarget"] = None, - display_name: Optional[str] = None, + vector_store_id: str, description: Optional[str] = None, tags: Optional[Dict[str, str]] = None, - properties: Optional[Dict[str, str]] = None, ) -> None: ... @overload @@ -1321,71 +1189,48 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: """ def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) + super().__init__(*args, type=IndexType.MANAGED_AZURE_SEARCH, **kwargs) -class EvaluationSchedule(_model_base.Model): - """Evaluation Schedule Definition. +class ModelDeployment(Deployment, discriminator="ModelDeployment"): + """Model Deployment Definition. - :ivar name: Name of the schedule, which also serves as the unique identifier for the - evaluation. Required. + :ivar name: Name of the deployment. Required. :vartype name: str - :ivar data: Data for evaluation. Required. - :vartype data: ~azure.ai.projects.models.ApplicationInsightsConfiguration - :ivar description: Description of the evaluation. It can be used to store additional - information about the evaluation and is mutable. - :vartype description: str - :ivar system_data: Metadata containing createdBy and modifiedBy information. - :vartype system_data: ~azure.ai.projects.models.SystemData - :ivar provisioning_state: Provisioning State of the evaluation. It is set by service and is - read-only. - :vartype provisioning_state: str - :ivar tags: Evaluation's tags. Unlike properties, tags are fully mutable. - :vartype tags: dict[str, str] - :ivar properties: Evaluation's properties. Unlike tags, properties are add-only. Once added, a - property cannot be removed. - :vartype properties: dict[str, str] - :ivar is_enabled: Enabled status of the evaluation. It is set by service and is read-only. - :vartype is_enabled: str - :ivar evaluators: Evaluators to be used for the evaluation. Required. - :vartype evaluators: dict[str, ~azure.ai.projects.models.EvaluatorConfiguration] - :ivar trigger: Trigger for the evaluation. Required. - :vartype trigger: ~azure.ai.projects.models.Trigger + :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.Sku + :ivar connection_name: Name of the connection the deployment comes from. + :vartype connection_name: str """ - name: str = rest_field(visibility=["read"]) - """Name of the schedule, which also serves as the unique identifier for the evaluation. Required.""" - data: "_models.ApplicationInsightsConfiguration" = rest_field(visibility=["read", "create"]) - """Data for evaluation. Required.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Description of the evaluation. It can be used to store additional information about the - evaluation and is mutable.""" - system_data: Optional["_models.SystemData"] = rest_field(name="systemData", visibility=["read"]) - """Metadata containing createdBy and modifiedBy information.""" - provisioning_state: Optional[str] = rest_field(name="provisioningState", visibility=["read"]) - """Provisioning State of the evaluation. It is set by service and is read-only.""" - tags: Optional[Dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Evaluation's tags. Unlike properties, tags are fully mutable.""" - properties: Optional[Dict[str, str]] = rest_field(visibility=["read", "create"]) - """Evaluation's properties. Unlike tags, properties are add-only. Once added, a property cannot be - removed.""" - is_enabled: Optional[str] = rest_field(name="isEnabled", visibility=["read"]) - """Enabled status of the evaluation. It is set by service and is read-only.""" - evaluators: Dict[str, "_models.EvaluatorConfiguration"] = rest_field(visibility=["read", "create"]) - """Evaluators to be used for the evaluation. Required.""" - trigger: "_models.Trigger" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Trigger for the evaluation. Required.""" + 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.Sku" = 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, - *, - data: "_models.ApplicationInsightsConfiguration", - evaluators: Dict[str, "_models.EvaluatorConfiguration"], - trigger: "_models.Trigger", - description: Optional[str] = None, - tags: Optional[Dict[str, str]] = None, - properties: Optional[Dict[str, str]] = None, ) -> None: ... @overload @@ -1396,38 +1241,22 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: """ def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) + super().__init__(*args, type=DeploymentType.MODEL_DEPLOYMENT, **kwargs) -class EvaluationTarget(_model_base.Model): - """Target for the evaluation process. +class NoAuthenticationCredentials(BaseCredentials, discriminator="None"): + """Credentials that do not require authentication. - :ivar system_message: System message related to the evaluation target. Required. - :vartype system_message: str - :ivar model_config: Model configuration for the evaluation. Required. - :vartype model_config: ~azure.ai.projects.models.TargetModelConfig - :ivar model_params: A dictionary of parameters for the model. - :vartype model_params: dict[str, any] + :ivar type: The credential type. Required. No credential + :vartype type: str or ~azure.ai.projects.models.NONE """ - system_message: str = rest_field(name="systemMessage", visibility=["read", "create", "update", "delete", "query"]) - """System message related to the evaluation target. Required.""" - model_config: "_models.TargetModelConfig" = rest_field( - name="modelConfig", visibility=["read", "create", "update", "delete", "query"] - ) - """Model configuration for the evaluation. Required.""" - model_params: Optional[Dict[str, Any]] = rest_field( - name="modelParams", visibility=["read", "create", "update", "delete", "query"] - ) - """A dictionary of parameters for the model.""" + type: Literal[CredentialType.NONE] = rest_discriminator(name="type", visibility=["read"]) # type: ignore + """The credential type. Required. No credential""" @overload def __init__( self, - *, - system_message: str, - model_config: "_models.TargetModelConfig", - model_params: Optional[Dict[str, Any]] = None, ) -> None: ... @overload @@ -1438,38 +1267,42 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: """ def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) + super().__init__(*args, type=CredentialType.NONE, **kwargs) -class EvaluatorConfiguration(_model_base.Model): - """Evaluator Configuration. +class PendingUploadRequest(_Model): + """Represents a request for a pending upload. - :ivar id: Identifier of the evaluator. Required. - :vartype id: str - :ivar init_params: Initialization parameters of the evaluator. - :vartype init_params: dict[str, any] - :ivar data_mapping: Data parameters of the evaluator. - :vartype data_mapping: dict[str, str] + :ivar pending_upload_id: If PendingUploadId is not provided, a random GUID will be used. + :vartype pending_upload_id: str + :ivar connection_name: Name of Azure blob storage connection 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. + :vartype pending_upload_type: str or ~azure.ai.projects.models.BLOB_REFERENCE """ - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Identifier of the evaluator. Required.""" - init_params: Optional[Dict[str, Any]] = rest_field( - name="initParams", visibility=["read", "create", "update", "delete", "query"] + pending_upload_id: Optional[str] = rest_field( + name="pendingUploadId", visibility=["read", "create", "update", "delete", "query"] ) - """Initialization parameters of the evaluator.""" - data_mapping: Optional[Dict[str, str]] = rest_field( - name="dataMapping", 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"] ) - """Data parameters of the evaluator.""" + """Name of Azure blob storage connection to use for generating temporary SAS token.""" + 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.""" @overload def __init__( self, *, - id: str, # pylint: disable=redefined-builtin - init_params: Optional[Dict[str, Any]] = None, - data_mapping: Optional[Dict[str, str]] = None, + pending_upload_type: Literal[PendingUploadType.BLOB_REFERENCE], + pending_upload_id: Optional[str] = None, + connection_name: Optional[str] = None, ) -> None: ... @overload @@ -1483,30 +1316,44 @@ def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class FileDeletionStatus(_model_base.Model): - """A status response from a file deletion operation. +class PendingUploadResponse(_Model): + """Represents the response for a pending upload request. - :ivar id: The ID of the resource specified for deletion. Required. - :vartype id: str - :ivar deleted: A value indicating whether deletion was successful. Required. - :vartype deleted: bool - :ivar object: The object type, which is always 'file'. Required. Default value is "file". - :vartype object: str + :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: BlobReference is the only supported type. Required. Blob Reference + is the only supported type. + :vartype pending_upload_type: str or ~azure.ai.projects.models.BLOB_REFERENCE """ - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the resource specified for deletion. Required.""" - deleted: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A value indicating whether deletion was successful. Required.""" - object: Literal["file"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always 'file'. Required. Default value is \"file\".""" + 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.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.""" @overload def __init__( self, *, - id: str, # pylint: disable=redefined-builtin - deleted: bool, + blob_reference: "_models.BlobReference", + pending_upload_id: str, + pending_upload_type: Literal[PendingUploadType.BLOB_REFERENCE], + version: Optional[str] = None, ) -> None: ... @overload @@ -1518,28 +1365,87 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.object: Literal["file"] = "file" -class FileListResponse(_model_base.Model): - """The response data from a file list operation. +class RedTeam(_Model): + """Red team details. - :ivar object: The object type, which is always 'list'. Required. Default value is "list". - :vartype object: str - :ivar data: The files returned for the request. Required. - :vartype data: list[~azure.ai.projects.models.OpenAIFile] + :ivar id: Identifier of the red team. Required. + :vartype id: str + :ivar scan_name: Name of the red-team scan. + :vartype scan_name: str + :ivar num_turns: Number of simulation rounds. Required. + :vartype num_turns: int + :ivar attack_strategies: List of attack strategies or nested lists of attack strategies. + Required. + :vartype attack_strategies: list[str or ~azure.ai.projects.models.AttackStrategy] + :ivar simulation_only: Simulation-only or Simulation + Evaluation. Default false, if true the + scan outputs conversation not evaluation result. Required. + :vartype simulation_only: bool + :ivar risk_categories: List of risk categories to generate attack objectives for. Required. + :vartype risk_categories: list[str or ~azure.ai.projects.models.RiskCategory] + :ivar application_scenario: Application scenario for the red team operation, to generate + scenario specific attacks. + :vartype application_scenario: str + :ivar tags: Red team's tags. Unlike properties, tags are fully mutable. + :vartype tags: dict[str, str] + :ivar properties: Red team's properties. Unlike tags, properties are add-only. Once added, a + property cannot be removed. + :vartype properties: dict[str, str] + :ivar status: Status of the red-team. It is set by service and is read-only. + :vartype status: str + :ivar target_config: Target configuration for the red-team run. Required. + :vartype target_config: ~azure.ai.projects.models.TargetConfig """ - object: Literal["list"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always 'list'. Required. Default value is \"list\".""" - data: List["_models.OpenAIFile"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The files returned for the request. Required.""" + id: str = rest_field(visibility=["read"]) + """Identifier of the red team. Required.""" + scan_name: Optional[str] = rest_field(name="scanName", visibility=["read", "create", "update", "delete", "query"]) + """Name of the red-team scan.""" + num_turns: int = rest_field(name="numTurns", visibility=["read", "create", "update", "delete", "query"]) + """Number of simulation rounds. Required.""" + attack_strategies: List[Union[str, "_models.AttackStrategy"]] = rest_field( + name="attackStrategies", visibility=["read", "create", "update", "delete", "query"] + ) + """List of attack strategies or nested lists of attack strategies. Required.""" + simulation_only: bool = rest_field( + name="simulationOnly", visibility=["read", "create", "update", "delete", "query"] + ) + """Simulation-only or Simulation + Evaluation. Default false, if true the scan outputs + conversation not evaluation result. Required.""" + risk_categories: List[Union[str, "_models.RiskCategory"]] = rest_field( + name="riskCategories", visibility=["read", "create", "update", "delete", "query"] + ) + """List of risk categories to generate attack objectives for. Required.""" + application_scenario: Optional[str] = rest_field( + name="applicationScenario", visibility=["read", "create", "update", "delete", "query"] + ) + """Application scenario for the red team operation, to generate scenario specific attacks.""" + tags: Optional[Dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Red team's tags. Unlike properties, tags are fully mutable.""" + properties: Optional[Dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Red team's properties. Unlike tags, properties are add-only. Once added, a property cannot be + removed.""" + status: Optional[str] = rest_field(visibility=["read"]) + """Status of the red-team. It is set by service and is read-only.""" + target_config: "_models.TargetConfig" = rest_field( + name="targetConfig", visibility=["read", "create", "update", "delete", "query"] + ) + """Target configuration for the red-team run. Required.""" @overload def __init__( self, *, - data: List["_models.OpenAIFile"], + num_turns: int, + attack_strategies: List[Union[str, "_models.AttackStrategy"]], + simulation_only: bool, + risk_categories: List[Union[str, "_models.RiskCategory"]], + target_config: "_models.TargetConfig", + scan_name: Optional[str] = None, + application_scenario: Optional[str] = None, + tags: Optional[Dict[str, str]] = None, + properties: Optional[Dict[str, str]] = None, ) -> None: ... @overload @@ -1551,61 +1457,44 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) - self.object: Literal["list"] = "list" -class FileSearchRankingOptions(_model_base.Model): - """Ranking options for file search. +class SasCredential(_Model): + """SAS Credential definition. - :ivar ranker: File search ranker. Required. - :vartype ranker: str - :ivar score_threshold: Ranker search threshold. Required. - :vartype score_threshold: float + :ivar sas_uri: SAS uri. Required. + :vartype sas_uri: str + :ivar type: Type of credential. Required. Default value is "SAS". + :vartype type: str """ - ranker: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """File search ranker. Required.""" - score_threshold: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Ranker search threshold. Required.""" - - @overload - def __init__( - self, - *, - ranker: str, - score_threshold: float, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ + sas_uri: str = rest_field(name="sasUri", visibility=["read"]) + """SAS uri. Required.""" + type: Literal["SAS"] = rest_field(visibility=["read"]) + """Type of credential. Required. Default value is \"SAS\".""" def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) + self.type: Literal["SAS"] = "SAS" -class FileSearchToolCallContent(_model_base.Model): - """The file search result content object. +class SASCredentials(BaseCredentials, discriminator="SAS"): + """Shared Access Signature (SAS) credential definition. - :ivar type: The type of the content. Required. Default value is "text". - :vartype type: str - :ivar text: The text content of the file. Required. - :vartype text: str + :ivar type: The credential type. Required. Shared Access Signature (SAS) credential + :vartype type: str or ~azure.ai.projects.models.SAS + :ivar sas_token: SAS token. + :vartype sas_token: str """ - type: Literal["text"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The type of the content. Required. Default value is \"text\".""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The text content of the file. Required.""" + type: Literal[CredentialType.SAS] = rest_discriminator(name="type", visibility=["read"]) # type: ignore + """The credential type. Required. Shared Access Signature (SAS) credential""" + sas_token: Optional[str] = rest_field(name="SAS", visibility=["read"]) + """SAS token.""" @overload def __init__( self, - *, - text: str, ) -> None: ... @overload @@ -1616,6529 +1505,44 @@ def __init__(self, mapping: Mapping[str, Any]) -> None: """ def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["text"] = "text" + super().__init__(*args, type=CredentialType.SAS, **kwargs) -class FileSearchToolDefinition(ToolDefinition, discriminator="file_search"): - """The input definition information for a file search tool as used to configure an agent. +class Sku(_Model): + """Sku information. - :ivar type: The object type, which is always 'file_search'. Required. Default value is - "file_search". - :vartype type: str - :ivar file_search: Options overrides for the file search tool. - :vartype file_search: ~azure.ai.projects.models.FileSearchToolDefinitionDetails + :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 """ - type: Literal["file_search"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'file_search'. Required. Default value is \"file_search\".""" - file_search: Optional["_models.FileSearchToolDefinitionDetails"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Options overrides for the file search tool.""" + 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, *, - file_search: Optional["_models.FileSearchToolDefinitionDetails"] = 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, type="file_search", **kwargs) - - -class FileSearchToolDefinitionDetails(_model_base.Model): - """Options overrides for the file search tool. - - :ivar max_num_results: The maximum number of results the file search tool should output. The - default is 20 for gpt-4* models and 5 for gpt-3.5-turbo. This number should be between 1 and 50 - inclusive. - - Note that the file search tool may output fewer than ``max_num_results`` results. See the file - search tool documentation for more information. - :vartype max_num_results: int - :ivar ranking_options: Ranking options for file search. - :vartype ranking_options: ~azure.ai.projects.models.FileSearchRankingOptions - """ - - max_num_results: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The maximum number of results the file search tool should output. The default is 20 for gpt-4* - models and 5 for gpt-3.5-turbo. This number should be between 1 and 50 inclusive. - - Note that the file search tool may output fewer than ``max_num_results`` results. See the file - search tool documentation for more information.""" - ranking_options: Optional["_models.FileSearchRankingOptions"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Ranking options for file search.""" - - @overload - def __init__( - self, - *, - max_num_results: Optional[int] = None, - ranking_options: Optional["_models.FileSearchRankingOptions"] = 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 FileSearchToolResource(_model_base.Model): - """A set of resources that are used by the ``file_search`` tool. - - :ivar vector_store_ids: The ID of the vector store attached to this agent. There can be a - maximum of 1 vector - store attached to the agent. - :vartype vector_store_ids: list[str] - :ivar vector_stores: The list of vector store configuration objects from Azure. - This list is limited to one element. - The only element of this list contains the list of azure asset IDs used by the search tool. - :vartype vector_stores: list[~azure.ai.projects.models.VectorStoreConfigurations] - """ - - vector_store_ids: Optional[List[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the vector store attached to this agent. There can be a maximum of 1 vector - store attached to the agent.""" - vector_stores: Optional[List["_models.VectorStoreConfigurations"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The list of vector store configuration objects from Azure. - This list is limited to one element. - The only element of this list contains the list of azure asset IDs used by the search tool.""" - - @overload - def __init__( - self, - *, - vector_store_ids: Optional[List[str]] = None, - vector_stores: Optional[List["_models.VectorStoreConfigurations"]] = 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 FunctionDefinition(_model_base.Model): - """The input definition information for a function. - - :ivar name: The name of the function to be called. Required. - :vartype name: str - :ivar description: A description of what the function does, used by the model to choose when - and how to call the function. - :vartype description: str - :ivar parameters: The parameters the functions accepts, described as a JSON Schema object. - Required. - :vartype parameters: any - """ - - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the function to be called. Required.""" - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A description of what the function does, used by the model to choose when and how to call the - function.""" - parameters: Any = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The parameters the functions accepts, described as a JSON Schema object. Required.""" - - @overload - def __init__( - self, - *, - name: str, - parameters: Any, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class FunctionName(_model_base.Model): - """The function name that will be used, if using the ``function`` tool. - - :ivar name: The name of the function to call. Required. - :vartype name: str - """ - - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the function to call. Required.""" - - @overload - def __init__( - self, - *, - name: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class FunctionToolDefinition(ToolDefinition, discriminator="function"): - """The input definition information for a function tool as used to configure an agent. - - :ivar type: The object type, which is always 'function'. Required. Default value is "function". - :vartype type: str - :ivar function: The definition of the concrete function that the function tool should call. - Required. - :vartype function: ~azure.ai.projects.models.FunctionDefinition - """ - - type: Literal["function"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'function'. Required. Default value is \"function\".""" - function: "_models.FunctionDefinition" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The definition of the concrete function that the function tool should call. Required.""" - - @overload - def __init__( - self, - *, - function: "_models.FunctionDefinition", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="function", **kwargs) - - -class GetAppInsightsResponse(_model_base.Model): - """Response from getting properties of the Application Insights resource. - - :ivar id: A unique identifier for the resource. Required. - :vartype id: str - :ivar name: The name of the resource. Required. - :vartype name: str - :ivar properties: The properties of the resource. Required. - :vartype properties: ~azure.ai.projects.models._models.AppInsightsProperties - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A unique identifier for the resource. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the resource. Required.""" - properties: "_models._models.AppInsightsProperties" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The properties of the resource. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - name: str, - properties: "_models._models.AppInsightsProperties", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param 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 GetConnectionResponse(_model_base.Model): - """Response from the listSecrets operation. - - :ivar id: A unique identifier for the connection. Required. - :vartype id: str - :ivar name: The name of the resource. Required. - :vartype name: str - :ivar properties: The properties of the resource. Required. - :vartype properties: ~azure.ai.projects.models._models.InternalConnectionProperties - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A unique identifier for the connection. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the resource. Required.""" - properties: "_models._models.InternalConnectionProperties" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The properties of the resource. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - name: str, - properties: "_models._models.InternalConnectionProperties", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param 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 GetWorkspaceResponse(_model_base.Model): - """Response from the Workspace - Get operation. - - :ivar id: A unique identifier for the resource. Required. - :vartype id: str - :ivar name: The name of the resource. Required. - :vartype name: str - :ivar properties: The properties of the resource. Required. - :vartype properties: ~azure.ai.projects.models._models.WorkspaceProperties - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A unique identifier for the resource. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the resource. Required.""" - properties: "_models._models.WorkspaceProperties" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The properties of the resource. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin + capacity: int, + family: str, name: str, - properties: "_models._models.WorkspaceProperties", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param 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 IncompleteRunDetails(_model_base.Model): - """Details on why the run is incomplete. Will be ``null`` if the run is not incomplete. - - :ivar reason: The reason why the run is incomplete. This indicates which specific token limit - was reached during the run. Required. Known values are: "max_completion_tokens" and - "max_prompt_tokens". - :vartype reason: str or ~azure.ai.projects.models.IncompleteDetailsReason - """ - - reason: Union[str, "_models.IncompleteDetailsReason"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The reason why the run is incomplete. This indicates which specific token limit was reached - during the run. Required. Known values are: \"max_completion_tokens\" and - \"max_prompt_tokens\".""" - - @overload - def __init__( - self, - *, - reason: Union[str, "_models.IncompleteDetailsReason"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param 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 InternalConnectionProperties(_model_base.Model): - """Connection properties. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - InternalConnectionPropertiesAADAuth, InternalConnectionPropertiesApiKeyAuth, - InternalConnectionPropertiesCustomAuth, InternalConnectionPropertiesNoAuth, - InternalConnectionPropertiesSASAuth - - :ivar auth_type: Authentication type of the connection target. Required. Known values are: - "ApiKey", "AAD", "SAS", "CustomKeys", and "None". - :vartype auth_type: str or ~azure.ai.projects.models.AuthenticationType - :ivar category: Category of the connection. Required. Known values are: "AzureOpenAI", - "Serverless", "AzureBlob", "AIServices", "CognitiveSearch", "ApiKey", "CustomKeys", and - "CognitiveService". - :vartype category: str or ~azure.ai.projects.models.ConnectionType - :ivar target: The connection URL to be used for this service. Required. - :vartype target: str - """ - - __mapping__: Dict[str, _model_base.Model] = {} - auth_type: str = rest_discriminator(name="authType", visibility=["read", "create", "update", "delete", "query"]) - """Authentication type of the connection target. Required. Known values are: \"ApiKey\", \"AAD\", - \"SAS\", \"CustomKeys\", and \"None\".""" - category: Union[str, "_models.ConnectionType"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Category of the connection. Required. Known values are: \"AzureOpenAI\", \"Serverless\", - \"AzureBlob\", \"AIServices\", \"CognitiveSearch\", \"ApiKey\", \"CustomKeys\", and - \"CognitiveService\".""" - target: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The connection URL to be used for this service. Required.""" - - @overload - def __init__( - self, - *, - auth_type: str, - category: Union[str, "_models.ConnectionType"], - target: 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 InternalConnectionPropertiesAADAuth(InternalConnectionProperties, discriminator="AAD"): - """Connection properties for connections with AAD authentication (aka ``Entra ID passthrough``). - - :ivar category: Category of the connection. Required. Known values are: "AzureOpenAI", - "Serverless", "AzureBlob", "AIServices", "CognitiveSearch", "ApiKey", "CustomKeys", and - "CognitiveService". - :vartype category: str or ~azure.ai.projects.models.ConnectionType - :ivar target: The connection URL to be used for this service. Required. - :vartype target: str - :ivar auth_type: Authentication type of the connection target. Required. Entra ID - authentication (formerly known as AAD) - :vartype auth_type: str or ~azure.ai.projects.models.ENTRA_ID - """ - - auth_type: Literal[AuthenticationType.ENTRA_ID] = rest_discriminator(name="authType", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Authentication type of the connection target. Required. Entra ID authentication (formerly known - as AAD)""" - - @overload - def __init__( - self, - *, - category: Union[str, "_models.ConnectionType"], - target: 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, auth_type=AuthenticationType.ENTRA_ID, **kwargs) - - -class InternalConnectionPropertiesApiKeyAuth(InternalConnectionProperties, discriminator="ApiKey"): - """Connection properties for connections with API key authentication. - - :ivar category: Category of the connection. Required. Known values are: "AzureOpenAI", - "Serverless", "AzureBlob", "AIServices", "CognitiveSearch", "ApiKey", "CustomKeys", and - "CognitiveService". - :vartype category: str or ~azure.ai.projects.models.ConnectionType - :ivar target: The connection URL to be used for this service. Required. - :vartype target: str - :ivar auth_type: Authentication type of the connection target. Required. API Key authentication - :vartype auth_type: str or ~azure.ai.projects.models.API_KEY - :ivar credentials: Credentials will only be present for authType=ApiKey. Required. - :vartype credentials: ~azure.ai.projects.models._models.CredentialsApiKeyAuth - """ - - auth_type: Literal[AuthenticationType.API_KEY] = rest_discriminator(name="authType", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Authentication type of the connection target. Required. API Key authentication""" - credentials: "_models._models.CredentialsApiKeyAuth" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Credentials will only be present for authType=ApiKey. Required.""" - - @overload - def __init__( - self, - *, - category: Union[str, "_models.ConnectionType"], - target: str, - credentials: "_models._models.CredentialsApiKeyAuth", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, auth_type=AuthenticationType.API_KEY, **kwargs) - - -class InternalConnectionPropertiesCustomAuth(InternalConnectionProperties, discriminator="CustomKeys"): - """Connection properties for connections with Custom authentication. - - :ivar category: Category of the connection. Required. Known values are: "AzureOpenAI", - "Serverless", "AzureBlob", "AIServices", "CognitiveSearch", "ApiKey", "CustomKeys", and - "CognitiveService". - :vartype category: str or ~azure.ai.projects.models.ConnectionType - :ivar target: The connection URL to be used for this service. Required. - :vartype target: str - :ivar auth_type: Authentication type of the connection target. Required. Custom authentication - :vartype auth_type: str or ~azure.ai.projects.models.CUSTOM - """ - - auth_type: Literal[AuthenticationType.CUSTOM] = rest_discriminator(name="authType", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Authentication type of the connection target. Required. Custom authentication""" - - @overload - def __init__( - self, - *, - category: Union[str, "_models.ConnectionType"], - target: 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, auth_type=AuthenticationType.CUSTOM, **kwargs) - - -class InternalConnectionPropertiesNoAuth(InternalConnectionProperties, discriminator="None"): - """Connection properties for connections with no authentication. - - :ivar category: Category of the connection. Required. Known values are: "AzureOpenAI", - "Serverless", "AzureBlob", "AIServices", "CognitiveSearch", "ApiKey", "CustomKeys", and - "CognitiveService". - :vartype category: str or ~azure.ai.projects.models.ConnectionType - :ivar target: The connection URL to be used for this service. Required. - :vartype target: str - :ivar auth_type: Authentication type of the connection target. Required. No authentication - :vartype auth_type: str or ~azure.ai.projects.models.NONE - """ - - auth_type: Literal[AuthenticationType.NONE] = rest_discriminator(name="authType", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Authentication type of the connection target. Required. No authentication""" - - @overload - def __init__( - self, - *, - category: Union[str, "_models.ConnectionType"], - target: 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, auth_type=AuthenticationType.NONE, **kwargs) - - -class InternalConnectionPropertiesSASAuth(InternalConnectionProperties, discriminator="SAS"): - """Connection properties for connections with SAS authentication. - - :ivar category: Category of the connection. Required. Known values are: "AzureOpenAI", - "Serverless", "AzureBlob", "AIServices", "CognitiveSearch", "ApiKey", "CustomKeys", and - "CognitiveService". - :vartype category: str or ~azure.ai.projects.models.ConnectionType - :ivar target: The connection URL to be used for this service. Required. - :vartype target: str - :ivar auth_type: Authentication type of the connection target. Required. Shared Access - Signature (SAS) authentication - :vartype auth_type: str or ~azure.ai.projects.models.SAS - :ivar credentials: Credentials will only be present for authType=ApiKey. Required. - :vartype credentials: ~azure.ai.projects.models._models.CredentialsSASAuth - """ - - auth_type: Literal[AuthenticationType.SAS] = rest_discriminator(name="authType", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Authentication type of the connection target. Required. Shared Access Signature (SAS) - authentication""" - credentials: "_models._models.CredentialsSASAuth" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Credentials will only be present for authType=ApiKey. Required.""" - - @overload - def __init__( - self, - *, - category: Union[str, "_models.ConnectionType"], - target: str, - credentials: "_models._models.CredentialsSASAuth", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, auth_type=AuthenticationType.SAS, **kwargs) - - -class ListConnectionsResponse(_model_base.Model): - """Response from the list operation. - - :ivar value: A list of connection list secrets. Required. - :vartype value: list[~azure.ai.projects.models._models.GetConnectionResponse] - """ - - value: List["_models._models.GetConnectionResponse"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """A list of connection list secrets. Required.""" - - @overload - def __init__( - self, - *, - value: List["_models._models.GetConnectionResponse"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param 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 MAASModelConfig(TargetModelConfig, discriminator="MAAS"): - """MaaS model configuration. The API version would be selected by the service for querying the - model. - - :ivar type: Required. Default value is "MAAS". - :vartype type: str - :ivar azure_endpoint: Endpoint targetURI for MAAS model. Required. - :vartype azure_endpoint: str - :ivar api_key: API Key for MAAS model. Required. - :vartype api_key: str - """ - - type: Literal["MAAS"] = rest_discriminator(name="type", visibility=["read"]) # type: ignore - """Required. Default value is \"MAAS\".""" - azure_endpoint: str = rest_field(name="azureEndpoint", visibility=["read", "create", "update", "delete", "query"]) - """Endpoint targetURI for MAAS model. Required.""" - api_key: str = rest_field(name="apiKey", visibility=["read", "create", "update", "delete", "query"]) - """API Key for MAAS model. Required.""" - - @overload - def __init__( - self, - *, - azure_endpoint: str, - api_key: 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, type="MAAS", **kwargs) - - -class MessageAttachment(_model_base.Model): - """This describes to which tools a file has been attached. - - :ivar file_id: The ID of the file to attach to the message. - :vartype file_id: str - :ivar data_source: Azure asset ID. - :vartype data_source: ~azure.ai.projects.models.VectorStoreDataSource - :ivar tools: The tools to add to this file. Required. - :vartype tools: list[~azure.ai.projects.models.CodeInterpreterToolDefinition or - ~azure.ai.projects.models.FileSearchToolDefinition] - """ - - file_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the file to attach to the message.""" - data_source: Optional["_models.VectorStoreDataSource"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Azure asset ID.""" - tools: List["_types.MessageAttachmentToolDefinition"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The tools to add to this file. Required.""" - - @overload - def __init__( - self, - *, - tools: List["_types.MessageAttachmentToolDefinition"], - file_id: Optional[str] = None, - data_source: Optional["_models.VectorStoreDataSource"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class MessageContent(_model_base.Model): - """An abstract representation of a single item of thread message content. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - MessageImageFileContent, MessageTextContent - - :ivar type: The object type. Required. Default value is None. - :vartype type: str - """ - - __mapping__: Dict[str, _model_base.Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The object type. Required. Default value is None.""" - - @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 MessageDelta(_model_base.Model): - """Represents the typed 'delta' payload within a streaming message delta chunk. - - :ivar role: The entity that produced the message. Required. Known values are: "user" and - "assistant". - :vartype role: str or ~azure.ai.projects.models.MessageRole - :ivar content: The content of the message as an array of text and/or images. Required. - :vartype content: list[~azure.ai.projects.models.MessageDeltaContent] - """ - - role: Union[str, "_models.MessageRole"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The entity that produced the message. Required. Known values are: \"user\" and \"assistant\".""" - content: List["_models.MessageDeltaContent"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The content of the message as an array of text and/or images. Required.""" - - @overload - def __init__( - self, - *, - role: Union[str, "_models.MessageRole"], - content: List["_models.MessageDeltaContent"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param 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 MessageDeltaChunk(_model_base.Model): - """Represents a message delta i.e. any changed fields on a message during streaming. - - :ivar id: The identifier of the message, which can be referenced in API endpoints. Required. - :vartype id: str - :ivar object: The object type, which is always ``thread.message.delta``. Required. Default - value is "thread.message.delta". - :vartype object: str - :ivar delta: The delta containing the fields that have changed on the Message. Required. - :vartype delta: ~azure.ai.projects.models.MessageDelta - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The identifier of the message, which can be referenced in API endpoints. Required.""" - object: Literal["thread.message.delta"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always ``thread.message.delta``. Required. Default value is - \"thread.message.delta\".""" - delta: "_models.MessageDelta" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The delta containing the fields that have changed on the Message. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - delta: "_models.MessageDelta", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.object: Literal["thread.message.delta"] = "thread.message.delta" - - -class MessageDeltaContent(_model_base.Model): - """The abstract base representation of a partial streamed message content payload. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - MessageDeltaImageFileContent, MessageDeltaTextContent - - :ivar index: The index of the content part of the message. Required. - :vartype index: int - :ivar type: The type of content for this content part. Required. Default value is None. - :vartype type: str - """ - - __mapping__: Dict[str, _model_base.Model] = {} - index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the content part of the message. Required.""" - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The type of content for this content part. Required. Default value is None.""" - - @overload - def __init__( - self, - *, - index: int, - 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 MessageDeltaImageFileContent(MessageDeltaContent, discriminator="image_file"): - """Represents a streamed image file content part within a streaming message delta chunk. - - :ivar index: The index of the content part of the message. Required. - :vartype index: int - :ivar type: The type of content for this content part, which is always "image_file.". Required. - Default value is "image_file". - :vartype type: str - :ivar image_file: The image_file data. - :vartype image_file: ~azure.ai.projects.models.MessageDeltaImageFileContentObject - """ - - type: Literal["image_file"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of content for this content part, which is always \"image_file.\". Required. Default - value is \"image_file\".""" - image_file: Optional["_models.MessageDeltaImageFileContentObject"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The image_file data.""" - - @overload - def __init__( - self, - *, - index: int, - image_file: Optional["_models.MessageDeltaImageFileContentObject"] = 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, type="image_file", **kwargs) - - -class MessageDeltaImageFileContentObject(_model_base.Model): - """Represents the 'image_file' payload within streaming image file content. - - :ivar file_id: The file ID of the image in the message content. - :vartype file_id: str - """ - - file_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The file ID of the image in the message content.""" - - @overload - def __init__( - self, - *, - file_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class MessageDeltaTextAnnotation(_model_base.Model): - """The abstract base representation of a streamed text content part's text annotation. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - MessageDeltaTextFileCitationAnnotation, MessageDeltaTextFilePathAnnotation, - MessageDeltaTextUrlCitationAnnotation - - :ivar index: The index of the annotation within a text content part. Required. - :vartype index: int - :ivar type: The type of the text content annotation. Required. Default value is None. - :vartype type: str - """ - - __mapping__: Dict[str, _model_base.Model] = {} - index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the annotation within a text content part. Required.""" - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The type of the text content annotation. Required. Default value is None.""" - - @overload - def __init__( - self, - *, - index: int, - 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 MessageDeltaTextContent(MessageDeltaContent, discriminator="text"): - """Represents a streamed text content part within a streaming message delta chunk. - - :ivar index: The index of the content part of the message. Required. - :vartype index: int - :ivar type: The type of content for this content part, which is always "text.". Required. - Default value is "text". - :vartype type: str - :ivar text: The text content details. - :vartype text: ~azure.ai.projects.models.MessageDeltaTextContentObject - """ - - type: Literal["text"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of content for this content part, which is always \"text.\". Required. Default value - is \"text\".""" - text: Optional["_models.MessageDeltaTextContentObject"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The text content details.""" - - @overload - def __init__( - self, - *, - index: int, - text: Optional["_models.MessageDeltaTextContentObject"] = 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, type="text", **kwargs) - - -class MessageDeltaTextContentObject(_model_base.Model): - """Represents the data of a streamed text content part within a streaming message delta chunk. - - :ivar value: The data that makes up the text. - :vartype value: str - :ivar annotations: Annotations for the text. - :vartype annotations: list[~azure.ai.projects.models.MessageDeltaTextAnnotation] - """ - - value: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The data that makes up the text.""" - annotations: Optional[List["_models.MessageDeltaTextAnnotation"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Annotations for the text.""" - - @overload - def __init__( - self, - *, - value: Optional[str] = None, - annotations: Optional[List["_models.MessageDeltaTextAnnotation"]] = 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 MessageDeltaTextFileCitationAnnotation(MessageDeltaTextAnnotation, discriminator="file_citation"): - """Represents a streamed file citation applied to a streaming text content part. - - :ivar index: The index of the annotation within a text content part. Required. - :vartype index: int - :ivar type: The type of the text content annotation, which is always "file_citation.". - Required. Default value is "file_citation". - :vartype type: str - :ivar file_citation: The file citation information. - :vartype file_citation: ~azure.ai.projects.models.MessageDeltaTextFileCitationAnnotationObject - :ivar text: The text in the message content that needs to be replaced. - :vartype text: str - :ivar start_index: The start index of this annotation in the content text. - :vartype start_index: int - :ivar end_index: The end index of this annotation in the content text. - :vartype end_index: int - """ - - type: Literal["file_citation"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the text content annotation, which is always \"file_citation.\". Required. Default - value is \"file_citation\".""" - file_citation: Optional["_models.MessageDeltaTextFileCitationAnnotationObject"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The file citation information.""" - text: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The text in the message content that needs to be replaced.""" - start_index: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The start index of this annotation in the content text.""" - end_index: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The end index of this annotation in the content text.""" - - @overload - def __init__( - self, - *, - index: int, - file_citation: Optional["_models.MessageDeltaTextFileCitationAnnotationObject"] = None, - text: Optional[str] = None, - start_index: Optional[int] = None, - end_index: 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, type="file_citation", **kwargs) - - -class MessageDeltaTextFileCitationAnnotationObject(_model_base.Model): # pylint: disable=name-too-long - """Represents the data of a streamed file citation as applied to a streaming text content part. - - :ivar file_id: The ID of the specific file the citation is from. - :vartype file_id: str - :ivar quote: The specific quote in the cited file. - :vartype quote: str - """ - - file_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the specific file the citation is from.""" - quote: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The specific quote in the cited file.""" - - @overload - def __init__( - self, - *, - file_id: Optional[str] = None, - quote: 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 MessageDeltaTextFilePathAnnotation(MessageDeltaTextAnnotation, discriminator="file_path"): - """Represents a streamed file path annotation applied to a streaming text content part. - - :ivar index: The index of the annotation within a text content part. Required. - :vartype index: int - :ivar type: The type of the text content annotation, which is always "file_path.". Required. - Default value is "file_path". - :vartype type: str - :ivar file_path: The file path information. - :vartype file_path: ~azure.ai.projects.models.MessageDeltaTextFilePathAnnotationObject - :ivar start_index: The start index of this annotation in the content text. - :vartype start_index: int - :ivar end_index: The end index of this annotation in the content text. - :vartype end_index: int - :ivar text: The text in the message content that needs to be replaced. - :vartype text: str - """ - - type: Literal["file_path"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the text content annotation, which is always \"file_path.\". Required. Default - value is \"file_path\".""" - file_path: Optional["_models.MessageDeltaTextFilePathAnnotationObject"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The file path information.""" - start_index: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The start index of this annotation in the content text.""" - end_index: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The end index of this annotation in the content text.""" - text: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The text in the message content that needs to be replaced.""" - - @overload - def __init__( - self, - *, - index: int, - file_path: Optional["_models.MessageDeltaTextFilePathAnnotationObject"] = None, - start_index: Optional[int] = None, - end_index: Optional[int] = None, - 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, type="file_path", **kwargs) - - -class MessageDeltaTextFilePathAnnotationObject(_model_base.Model): - """Represents the data of a streamed file path annotation as applied to a streaming text content - part. - - :ivar file_id: The file ID for the annotation. - :vartype file_id: str - """ - - file_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The file ID for the annotation.""" - - @overload - def __init__( - self, - *, - file_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class MessageDeltaTextUrlCitationAnnotation(MessageDeltaTextAnnotation, discriminator="url_citation"): - """A citation within the message that points to a specific URL associated with the message. - Generated when the agent uses tools such as 'bing_grounding' to search the Internet. - - :ivar index: The index of the annotation within a text content part. Required. - :vartype index: int - :ivar type: The object type, which is always 'url_citation'. Required. Default value is - "url_citation". - :vartype type: str - :ivar url_citation: The details of the URL citation. Required. - :vartype url_citation: ~azure.ai.projects.models.MessageDeltaTextUrlCitationDetails - :ivar start_index: The first text index associated with this text annotation. - :vartype start_index: int - :ivar end_index: The last text index associated with this text annotation. - :vartype end_index: int - """ - - type: Literal["url_citation"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'url_citation'. Required. Default value is \"url_citation\".""" - url_citation: "_models.MessageDeltaTextUrlCitationDetails" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The details of the URL citation. Required.""" - start_index: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The first text index associated with this text annotation.""" - end_index: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The last text index associated with this text annotation.""" - - @overload - def __init__( - self, - *, - index: int, - url_citation: "_models.MessageDeltaTextUrlCitationDetails", - start_index: Optional[int] = None, - end_index: 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, type="url_citation", **kwargs) - - -class MessageDeltaTextUrlCitationDetails(_model_base.Model): - """A representation of a URL citation, as used in text thread message content. - - :ivar url: The URL associated with this citation. Required. - :vartype url: str - :ivar title: The title of the URL. - :vartype title: str - """ - - url: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The URL associated with this citation. Required.""" - title: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The title of the URL.""" - - @overload - def __init__( - self, - *, - url: str, - title: 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 MessageImageFileContent(MessageContent, discriminator="image_file"): - """A representation of image file content in a thread message. - - :ivar type: The object type, which is always 'image_file'. Required. Default value is - "image_file". - :vartype type: str - :ivar image_file: The image file for this thread message content item. Required. - :vartype image_file: ~azure.ai.projects.models.MessageImageFileDetails - """ - - type: Literal["image_file"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'image_file'. Required. Default value is \"image_file\".""" - image_file: "_models.MessageImageFileDetails" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The image file for this thread message content item. Required.""" - - @overload - def __init__( - self, - *, - image_file: "_models.MessageImageFileDetails", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="image_file", **kwargs) - - -class MessageImageFileDetails(_model_base.Model): - """An image reference, as represented in thread message content. - - :ivar file_id: The ID for the file associated with this image. Required. - :vartype file_id: str - """ - - file_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID for the file associated with this image. Required.""" - - @overload - def __init__( - self, - *, - file_id: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class MessageImageFileParam(_model_base.Model): - """Defines how an internally uploaded image file is referenced when creating an image-file block. - - :ivar file_id: The ID of the previously uploaded image file. Required. - :vartype file_id: str - :ivar detail: Optional detail level for the image (auto, low, or high). Known values are: - "auto", "low", and "high". - :vartype detail: str or ~azure.ai.projects.models.ImageDetailLevel - """ - - file_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the previously uploaded image file. Required.""" - detail: Optional[Union[str, "_models.ImageDetailLevel"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Optional detail level for the image (auto, low, or high). Known values are: \"auto\", \"low\", - and \"high\".""" - - @overload - def __init__( - self, - *, - file_id: str, - detail: Optional[Union[str, "_models.ImageDetailLevel"]] = 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 MessageImageUrlParam(_model_base.Model): - """Defines how an external image URL is referenced when creating an image-URL block. - - :ivar url: The publicly accessible URL of the external image. Required. - :vartype url: str - :ivar detail: Optional detail level for the image (auto, low, or high). Defaults to 'auto' if - not specified. Known values are: "auto", "low", and "high". - :vartype detail: str or ~azure.ai.projects.models.ImageDetailLevel - """ - - url: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The publicly accessible URL of the external image. Required.""" - detail: Optional[Union[str, "_models.ImageDetailLevel"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Optional detail level for the image (auto, low, or high). Defaults to 'auto' if not specified. - Known values are: \"auto\", \"low\", and \"high\".""" - - @overload - def __init__( - self, - *, - url: str, - detail: Optional[Union[str, "_models.ImageDetailLevel"]] = 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 MessageIncompleteDetails(_model_base.Model): - """Information providing additional detail about a message entering an incomplete status. - - :ivar reason: The provided reason describing why the message was marked as incomplete. - Required. Known values are: "content_filter", "max_tokens", "run_cancelled", "run_failed", and - "run_expired". - :vartype reason: str or ~azure.ai.projects.models.MessageIncompleteDetailsReason - """ - - reason: Union[str, "_models.MessageIncompleteDetailsReason"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The provided reason describing why the message was marked as incomplete. Required. Known values - are: \"content_filter\", \"max_tokens\", \"run_cancelled\", \"run_failed\", and - \"run_expired\".""" - - @overload - def __init__( - self, - *, - reason: Union[str, "_models.MessageIncompleteDetailsReason"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param 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 MessageInputContentBlock(_model_base.Model): - """Defines a single content block when creating a message. The 'type' field determines whether it - is text, an image file, or an external image URL, etc. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - MessageInputImageFileBlock, MessageInputImageUrlBlock, MessageInputTextBlock - - :ivar type: Specifies which kind of content block this is (text, image_file, image_url, etc.). - Required. Known values are: "text", "image_file", and "image_url". - :vartype type: str or ~azure.ai.projects.models.MessageBlockType - """ - - __mapping__: Dict[str, _model_base.Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """Specifies which kind of content block this is (text, image_file, image_url, etc.). Required. - Known values are: \"text\", \"image_file\", and \"image_url\".""" - - @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 MessageInputImageFileBlock(MessageInputContentBlock, discriminator="image_file"): - """An image-file block in a new message, referencing an internally uploaded image by file ID. - - :ivar type: Must be 'image_file' for an internally uploaded image block. Required. Indicates a - block referencing an internally uploaded image file. - :vartype type: str or ~azure.ai.projects.models.IMAGE_FILE - :ivar image_file: Information about the referenced image file, including file ID and optional - detail level. Required. - :vartype image_file: ~azure.ai.projects.models.MessageImageFileParam - """ - - type: Literal[MessageBlockType.IMAGE_FILE] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Must be 'image_file' for an internally uploaded image block. Required. Indicates a block - referencing an internally uploaded image file.""" - image_file: "_models.MessageImageFileParam" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Information about the referenced image file, including file ID and optional detail level. - Required.""" - - @overload - def __init__( - self, - *, - image_file: "_models.MessageImageFileParam", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type=MessageBlockType.IMAGE_FILE, **kwargs) - - -class MessageInputImageUrlBlock(MessageInputContentBlock, discriminator="image_url"): - """An image-URL block in a new message, referencing an external image by URL. - - :ivar type: Must be 'image_url' for an externally hosted image block. Required. Indicates a - block referencing an external image URL. - :vartype type: str or ~azure.ai.projects.models.IMAGE_URL - :ivar image_url: Information about the external image URL, including the URL and optional - detail level. Required. - :vartype image_url: ~azure.ai.projects.models.MessageImageUrlParam - """ - - type: Literal[MessageBlockType.IMAGE_URL] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Must be 'image_url' for an externally hosted image block. Required. Indicates a block - referencing an external image URL.""" - image_url: "_models.MessageImageUrlParam" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Information about the external image URL, including the URL and optional detail level. - Required.""" - - @overload - def __init__( - self, - *, - image_url: "_models.MessageImageUrlParam", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type=MessageBlockType.IMAGE_URL, **kwargs) - - -class MessageInputTextBlock(MessageInputContentBlock, discriminator="text"): - """A text block in a new message, containing plain text content. - - :ivar type: Must be 'text' for a text block. Required. Indicates a block containing text - content. - :vartype type: str or ~azure.ai.projects.models.TEXT - :ivar text: The plain text content for this block. Required. - :vartype text: str - """ - - type: Literal[MessageBlockType.TEXT] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """Must be 'text' for a text block. Required. Indicates a block containing text content.""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The plain text content for this block. Required.""" - - @overload - def __init__( - self, - *, - text: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type=MessageBlockType.TEXT, **kwargs) - - -class MessageTextAnnotation(_model_base.Model): - """An abstract representation of an annotation to text thread message content. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - MessageTextFileCitationAnnotation, MessageTextFilePathAnnotation, - MessageTextUrlCitationAnnotation - - :ivar type: The object type. Required. Default value is None. - :vartype type: str - :ivar text: The textual content associated with this text annotation item. Required. - :vartype text: str - """ - - __mapping__: Dict[str, _model_base.Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The object type. Required. Default value is None.""" - text: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The textual content associated with this text annotation item. Required.""" - - @overload - def __init__( - self, - *, - type: str, - text: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class MessageTextContent(MessageContent, discriminator="text"): - """A representation of a textual item of thread message content. - - :ivar type: The object type, which is always 'text'. Required. Default value is "text". - :vartype type: str - :ivar text: The text and associated annotations for this thread message content item. Required. - :vartype text: ~azure.ai.projects.models.MessageTextDetails - """ - - type: Literal["text"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'text'. Required. Default value is \"text\".""" - text: "_models.MessageTextDetails" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The text and associated annotations for this thread message content item. Required.""" - - @overload - def __init__( - self, - *, - text: "_models.MessageTextDetails", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="text", **kwargs) - - -class MessageTextDetails(_model_base.Model): - """The text and associated annotations for a single item of agent thread message content. - - :ivar value: The text data. Required. - :vartype value: str - :ivar annotations: A list of annotations associated with this text. Required. - :vartype annotations: list[~azure.ai.projects.models.MessageTextAnnotation] - """ - - value: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The text data. Required.""" - annotations: List["_models.MessageTextAnnotation"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """A list of annotations associated with this text. Required.""" - - @overload - def __init__( - self, - *, - value: str, - annotations: List["_models.MessageTextAnnotation"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param 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 MessageTextFileCitationAnnotation(MessageTextAnnotation, discriminator="file_citation"): - """A citation within the message that points to a specific quote from a specific File associated - with the agent or the message. Generated when the agent uses the 'file_search' tool to search - files. - - :ivar text: The textual content associated with this text annotation item. Required. - :vartype text: str - :ivar type: The object type, which is always 'file_citation'. Required. Default value is - "file_citation". - :vartype type: str - :ivar file_citation: A citation within the message that points to a specific quote from a - specific file. - Generated when the agent uses the "file_search" tool to search files. Required. - :vartype file_citation: ~azure.ai.projects.models.MessageTextFileCitationDetails - :ivar start_index: The first text index associated with this text annotation. - :vartype start_index: int - :ivar end_index: The last text index associated with this text annotation. - :vartype end_index: int - """ - - type: Literal["file_citation"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'file_citation'. Required. Default value is \"file_citation\".""" - file_citation: "_models.MessageTextFileCitationDetails" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """A citation within the message that points to a specific quote from a specific file. - Generated when the agent uses the \"file_search\" tool to search files. Required.""" - start_index: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The first text index associated with this text annotation.""" - end_index: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The last text index associated with this text annotation.""" - - @overload - def __init__( - self, - *, - text: str, - file_citation: "_models.MessageTextFileCitationDetails", - start_index: Optional[int] = None, - end_index: 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, type="file_citation", **kwargs) - - -class MessageTextFileCitationDetails(_model_base.Model): - """A representation of a file-based text citation, as used in a file-based annotation of text - thread message content. - - :ivar file_id: The ID of the file associated with this citation. Required. - :vartype file_id: str - :ivar quote: The specific quote cited in the associated file. Required. - :vartype quote: str - """ - - file_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the file associated with this citation. Required.""" - quote: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The specific quote cited in the associated file. Required.""" - - @overload - def __init__( - self, - *, - file_id: str, - quote: 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 MessageTextFilePathAnnotation(MessageTextAnnotation, discriminator="file_path"): - """A citation within the message that points to a file located at a specific path. - - :ivar text: The textual content associated with this text annotation item. Required. - :vartype text: str - :ivar type: The object type, which is always 'file_path'. Required. Default value is - "file_path". - :vartype type: str - :ivar file_path: A URL for the file that's generated when the agent used the code_interpreter - tool to generate a file. Required. - :vartype file_path: ~azure.ai.projects.models.MessageTextFilePathDetails - :ivar start_index: The first text index associated with this text annotation. - :vartype start_index: int - :ivar end_index: The last text index associated with this text annotation. - :vartype end_index: int - """ - - type: Literal["file_path"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'file_path'. Required. Default value is \"file_path\".""" - file_path: "_models.MessageTextFilePathDetails" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """A URL for the file that's generated when the agent used the code_interpreter tool to generate a - file. Required.""" - start_index: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The first text index associated with this text annotation.""" - end_index: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The last text index associated with this text annotation.""" - - @overload - def __init__( - self, - *, - text: str, - file_path: "_models.MessageTextFilePathDetails", - start_index: Optional[int] = None, - end_index: 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, type="file_path", **kwargs) - - -class MessageTextFilePathDetails(_model_base.Model): - """An encapsulation of an image file ID, as used by message image content. - - :ivar file_id: The ID of the specific file that the citation is from. Required. - :vartype file_id: str - """ - - file_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the specific file that the citation is from. Required.""" - - @overload - def __init__( - self, - *, - file_id: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class MessageTextUrlCitationAnnotation(MessageTextAnnotation, discriminator="url_citation"): - """A citation within the message that points to a specific URL associated with the message. - Generated when the agent uses tools such as 'bing_grounding' to search the Internet. - - :ivar text: The textual content associated with this text annotation item. Required. - :vartype text: str - :ivar type: The object type, which is always 'url_citation'. Required. Default value is - "url_citation". - :vartype type: str - :ivar url_citation: The details of the URL citation. Required. - :vartype url_citation: ~azure.ai.projects.models.MessageTextUrlCitationDetails - :ivar start_index: The first text index associated with this text annotation. - :vartype start_index: int - :ivar end_index: The last text index associated with this text annotation. - :vartype end_index: int - """ - - type: Literal["url_citation"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'url_citation'. Required. Default value is \"url_citation\".""" - url_citation: "_models.MessageTextUrlCitationDetails" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The details of the URL citation. Required.""" - start_index: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The first text index associated with this text annotation.""" - end_index: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The last text index associated with this text annotation.""" - - @overload - def __init__( - self, - *, - text: str, - url_citation: "_models.MessageTextUrlCitationDetails", - start_index: Optional[int] = None, - end_index: 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, type="url_citation", **kwargs) - - -class MessageTextUrlCitationDetails(_model_base.Model): - """A representation of a URL citation, as used in text thread message content. - - :ivar url: The URL associated with this citation. Required. - :vartype url: str - :ivar title: The title of the URL. - :vartype title: str - """ - - url: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The URL associated with this citation. Required.""" - title: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The title of the URL.""" - - @overload - def __init__( - self, - *, - url: str, - title: 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 MicrosoftFabricToolDefinition(ToolDefinition, discriminator="fabric_dataagent"): - """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'. Required. Default value is - "fabric_dataagent". - :vartype type: str - :ivar fabric_dataagent: The list of connections used by the Microsoft Fabric tool. Required. - :vartype fabric_dataagent: ~azure.ai.projects.models.ToolConnectionList - """ - - type: Literal["fabric_dataagent"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'fabric_dataagent'. Required. Default value is - \"fabric_dataagent\".""" - fabric_dataagent: "_models.ToolConnectionList" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The list of connections used by the Microsoft Fabric tool. Required.""" - - @overload - def __init__( - self, - *, - fabric_dataagent: "_models.ToolConnectionList", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="fabric_dataagent", **kwargs) - - -class OpenAIFile(_model_base.Model): - """Represents an agent that can call the model and use tools. - - :ivar object: The object type, which is always 'file'. Required. Default value is "file". - :vartype object: str - :ivar id: The identifier, which can be referenced in API endpoints. Required. - :vartype id: str - :ivar bytes: The size of the file, in bytes. Required. - :vartype bytes: int - :ivar filename: The name of the file. Required. - :vartype filename: str - :ivar created_at: The Unix timestamp, in seconds, representing when this object was created. - Required. - :vartype created_at: ~datetime.datetime - :ivar purpose: The intended purpose of a file. Required. Known values are: "fine-tune", - "fine-tune-results", "assistants", "assistants_output", "batch", "batch_output", and "vision". - :vartype purpose: str or ~azure.ai.projects.models.FilePurpose - :ivar status: The state of the file. This field is available in Azure OpenAI only. Known values - are: "uploaded", "pending", "running", "processed", "error", "deleting", and "deleted". - :vartype status: str or ~azure.ai.projects.models.FileState - :ivar status_details: The error message with details in case processing of this file failed. - This field is available in Azure OpenAI only. - :vartype status_details: str - """ - - object: Literal["file"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always 'file'. Required. Default value is \"file\".""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The identifier, which can be referenced in API endpoints. Required.""" - bytes: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The size of the file, in bytes. Required.""" - filename: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the file. Required.""" - created_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp, in seconds, representing when this object was created. Required.""" - purpose: Union[str, "_models.FilePurpose"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The intended purpose of a file. Required. Known values are: \"fine-tune\", - \"fine-tune-results\", \"assistants\", \"assistants_output\", \"batch\", \"batch_output\", and - \"vision\".""" - status: Optional[Union[str, "_models.FileState"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The state of the file. This field is available in Azure OpenAI only. Known values are: - \"uploaded\", \"pending\", \"running\", \"processed\", \"error\", \"deleting\", and - \"deleted\".""" - status_details: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The error message with details in case processing of this file failed. This field is available - in Azure OpenAI only.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - bytes: int, - filename: str, - created_at: datetime.datetime, - purpose: Union[str, "_models.FilePurpose"], - status: Optional[Union[str, "_models.FileState"]] = None, - status_details: 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.object: Literal["file"] = "file" - - -class OpenAIPageableListOfAgent(_model_base.Model): - """The response data for a requested list of items. - - :ivar object: The object type, which is always list. Required. Default value is "list". - :vartype object: str - :ivar data: The requested list of items. Required. - :vartype data: list[~azure.ai.projects.models.Agent] - :ivar first_id: The first ID represented in this list. Required. - :vartype first_id: str - :ivar last_id: The last ID represented in this list. Required. - :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 - """ - - object: Literal["list"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always list. Required. Default value is \"list\".""" - data: List["_models.Agent"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The requested list of items. Required.""" - first_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The first ID represented in this list. Required.""" - last_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The last ID represented in this list. Required.""" - 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.Agent"], - first_id: str, - last_id: str, - has_more: 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) - self.object: Literal["list"] = "list" - - -class OpenAIPageableListOfAgentThread(_model_base.Model): - """The response data for a requested list of items. - - :ivar object: The object type, which is always list. Required. Default value is "list". - :vartype object: str - :ivar data: The requested list of items. Required. - :vartype data: list[~azure.ai.projects.models.AgentThread] - :ivar first_id: The first ID represented in this list. Required. - :vartype first_id: str - :ivar last_id: The last ID represented in this list. Required. - :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 - """ - - object: Literal["list"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always list. Required. Default value is \"list\".""" - data: List["_models.AgentThread"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The requested list of items. Required.""" - first_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The first ID represented in this list. Required.""" - last_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The last ID represented in this list. Required.""" - 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.AgentThread"], - first_id: str, - last_id: str, - has_more: 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) - self.object: Literal["list"] = "list" - - -class OpenAIPageableListOfRunStep(_model_base.Model): - """The response data for a requested list of items. - - :ivar object: The object type, which is always list. Required. Default value is "list". - :vartype object: str - :ivar data: The requested list of items. Required. - :vartype data: list[~azure.ai.projects.models.RunStep] - :ivar first_id: The first ID represented in this list. Required. - :vartype first_id: str - :ivar last_id: The last ID represented in this list. Required. - :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 - """ - - object: Literal["list"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always list. Required. Default value is \"list\".""" - data: List["_models.RunStep"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The requested list of items. Required.""" - first_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The first ID represented in this list. Required.""" - last_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The last ID represented in this list. Required.""" - 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.RunStep"], - first_id: str, - last_id: str, - has_more: 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) - self.object: Literal["list"] = "list" - - -class OpenAIPageableListOfThreadMessage(_model_base.Model): - """The response data for a requested list of items. - - :ivar object: The object type, which is always list. Required. Default value is "list". - :vartype object: str - :ivar data: The requested list of items. Required. - :vartype data: list[~azure.ai.projects.models.ThreadMessage] - :ivar first_id: The first ID represented in this list. Required. - :vartype first_id: str - :ivar last_id: The last ID represented in this list. Required. - :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 - """ - - object: Literal["list"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always list. Required. Default value is \"list\".""" - data: List["_models.ThreadMessage"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The requested list of items. Required.""" - first_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The first ID represented in this list. Required.""" - last_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The last ID represented in this list. Required.""" - 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.ThreadMessage"], - first_id: str, - last_id: str, - has_more: 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) - self.object: Literal["list"] = "list" - - -class OpenAIPageableListOfThreadRun(_model_base.Model): - """The response data for a requested list of items. - - :ivar object: The object type, which is always list. Required. Default value is "list". - :vartype object: str - :ivar data: The requested list of items. Required. - :vartype data: list[~azure.ai.projects.models.ThreadRun] - :ivar first_id: The first ID represented in this list. Required. - :vartype first_id: str - :ivar last_id: The last ID represented in this list. Required. - :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 - """ - - object: Literal["list"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always list. Required. Default value is \"list\".""" - data: List["_models.ThreadRun"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The requested list of items. Required.""" - first_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The first ID represented in this list. Required.""" - last_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The last ID represented in this list. Required.""" - 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.ThreadRun"], - first_id: str, - last_id: str, - has_more: 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) - self.object: Literal["list"] = "list" - - -class OpenAIPageableListOfVectorStore(_model_base.Model): - """The response data for a requested list of items. - - :ivar object: The object type, which is always list. Required. Default value is "list". - :vartype object: str - :ivar data: The requested list of items. Required. - :vartype data: list[~azure.ai.projects.models.VectorStore] - :ivar first_id: The first ID represented in this list. Required. - :vartype first_id: str - :ivar last_id: The last ID represented in this list. Required. - :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 - """ - - object: Literal["list"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always list. Required. Default value is \"list\".""" - data: List["_models.VectorStore"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The requested list of items. Required.""" - first_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The first ID represented in this list. Required.""" - last_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The last ID represented in this list. Required.""" - 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.VectorStore"], - first_id: str, - last_id: str, - has_more: 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) - self.object: Literal["list"] = "list" - - -class OpenAIPageableListOfVectorStoreFile(_model_base.Model): - """The response data for a requested list of items. - - :ivar object: The object type, which is always list. Required. Default value is "list". - :vartype object: str - :ivar data: The requested list of items. Required. - :vartype data: list[~azure.ai.projects.models.VectorStoreFile] - :ivar first_id: The first ID represented in this list. Required. - :vartype first_id: str - :ivar last_id: The last ID represented in this list. Required. - :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 - """ - - object: Literal["list"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always list. Required. Default value is \"list\".""" - data: List["_models.VectorStoreFile"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The requested list of items. Required.""" - first_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The first ID represented in this list. Required.""" - last_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The last ID represented in this list. Required.""" - 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.VectorStoreFile"], - first_id: str, - last_id: str, - has_more: 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) - self.object: Literal["list"] = "list" - - -class OpenApiAuthDetails(_model_base.Model): - """authentication details for OpenApiFunctionDefinition. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - OpenApiAnonymousAuthDetails, OpenApiConnectionAuthDetails, OpenApiManagedAuthDetails - - :ivar type: The type of authentication, must be anonymous/connection/managed_identity. - Required. Known values are: "anonymous", "connection", and "managed_identity". - :vartype type: str or ~azure.ai.projects.models.OpenApiAuthType - """ - - __mapping__: Dict[str, _model_base.Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The type of authentication, must be anonymous/connection/managed_identity. Required. Known - values are: \"anonymous\", \"connection\", and \"managed_identity\".""" - - @overload - def __init__( - self, - *, - type: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class OpenApiAnonymousAuthDetails(OpenApiAuthDetails, discriminator="anonymous"): - """Security details for OpenApi anonymous authentication. - - :ivar type: The object type, which is always 'anonymous'. Required. - :vartype type: str or ~azure.ai.projects.models.ANONYMOUS - """ - - type: Literal[OpenApiAuthType.ANONYMOUS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'anonymous'. Required.""" - - @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, type=OpenApiAuthType.ANONYMOUS, **kwargs) - - -class OpenApiConnectionAuthDetails(OpenApiAuthDetails, discriminator="connection"): - """Security details for OpenApi connection authentication. - - :ivar type: The object type, which is always 'connection'. Required. - :vartype type: str or ~azure.ai.projects.models.CONNECTION - :ivar security_scheme: Connection auth security details. Required. - :vartype security_scheme: ~azure.ai.projects.models.OpenApiConnectionSecurityScheme - """ - - type: Literal[OpenApiAuthType.CONNECTION] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'connection'. Required.""" - security_scheme: "_models.OpenApiConnectionSecurityScheme" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Connection auth security details. Required.""" - - @overload - def __init__( - self, - *, - security_scheme: "_models.OpenApiConnectionSecurityScheme", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type=OpenApiAuthType.CONNECTION, **kwargs) - - -class OpenApiConnectionSecurityScheme(_model_base.Model): - """Security scheme for OpenApi managed_identity authentication. - - :ivar connection_id: Connection id for Connection auth type. Required. - :vartype connection_id: str - """ - - connection_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Connection id for Connection auth type. Required.""" - - @overload - def __init__( - self, - *, - connection_id: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class OpenApiFunctionDefinition(_model_base.Model): - """The input definition information for an openapi function. - - :ivar name: The name of the function to be called. Required. - :vartype name: str - :ivar description: A description of what the function does, used by the model to choose when - and how to call the function. - :vartype description: str - :ivar spec: The openapi function shape, described as a JSON Schema object. Required. - :vartype spec: 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] - """ - - 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: 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.""" - - @overload - def __init__( - self, - *, - name: str, - spec: Any, - auth: "_models.OpenApiAuthDetails", - description: Optional[str] = None, - default_params: Optional[List[str]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class OpenApiManagedAuthDetails(OpenApiAuthDetails, discriminator="managed_identity"): - """Security details for OpenApi managed_identity authentication. - - :ivar type: The object type, which is always 'managed_identity'. Required. - :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 - """ - - 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.""" - security_scheme: "_models.OpenApiManagedSecurityScheme" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Connection auth security details. Required.""" - - @overload - def __init__( - self, - *, - security_scheme: "_models.OpenApiManagedSecurityScheme", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type=OpenApiAuthType.MANAGED_IDENTITY, **kwargs) - - -class OpenApiManagedSecurityScheme(_model_base.Model): - """Security scheme for OpenApi managed_identity authentication. - - :ivar audience: Authentication scope for managed_identity auth type. Required. - :vartype audience: str - """ - - audience: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Authentication scope for managed_identity auth type. Required.""" - - @overload - def __init__( - self, - *, - audience: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class OpenApiToolDefinition(ToolDefinition, 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. Default value is "openapi". - :vartype type: str - :ivar openapi: The openapi function definition. Required. - :vartype openapi: ~azure.ai.projects.models.OpenApiFunctionDefinition - """ - - type: Literal["openapi"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'openapi'. Required. Default value is \"openapi\".""" - openapi: "_models.OpenApiFunctionDefinition" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The openapi function definition. Required.""" - - @overload - def __init__( - self, - *, - openapi: "_models.OpenApiFunctionDefinition", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="openapi", **kwargs) - - -class RecurrenceSchedule(_model_base.Model): - """RecurrenceSchedule Definition. - - :ivar hours: List of hours for the schedule. Required. - :vartype hours: list[int] - :ivar minutes: List of minutes for the schedule. Required. - :vartype minutes: list[int] - :ivar week_days: List of days for the schedule. - :vartype week_days: list[str or ~azure.ai.projects.models.WeekDays] - :ivar month_days: List of month days for the schedule. - :vartype month_days: list[int] - """ - - hours: List[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """List of hours for the schedule. Required.""" - minutes: List[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """List of minutes for the schedule. Required.""" - week_days: Optional[List[Union[str, "_models.WeekDays"]]] = rest_field( - name="weekDays", visibility=["read", "create", "update", "delete", "query"] - ) - """List of days for the schedule.""" - month_days: Optional[List[int]] = rest_field( - name="monthDays", visibility=["read", "create", "update", "delete", "query"] - ) - """List of month days for the schedule.""" - - @overload - def __init__( - self, - *, - hours: List[int], - minutes: List[int], - week_days: Optional[List[Union[str, "_models.WeekDays"]]] = None, - month_days: Optional[List[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 RecurrenceTrigger(Trigger, discriminator="Recurrence"): - """Recurrence Trigger Definition. - - :ivar type: Required. Default value is "Recurrence". - :vartype type: str - :ivar frequency: The frequency to trigger schedule. Required. Known values are: "Month", - "Week", "Day", "Hour", and "Minute". - :vartype frequency: str or ~azure.ai.projects.models.Frequency - :ivar interval: Specifies schedule interval in conjunction with frequency. Required. - :vartype interval: int - :ivar schedule: The recurrence schedule. - :vartype schedule: ~azure.ai.projects.models.RecurrenceSchedule - """ - - type: Literal["Recurrence"] = rest_discriminator(name="type", visibility=["read"]) # type: ignore - """Required. Default value is \"Recurrence\".""" - frequency: Union[str, "_models.Frequency"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The frequency to trigger schedule. Required. Known values are: \"Month\", \"Week\", \"Day\", - \"Hour\", and \"Minute\".""" - interval: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Specifies schedule interval in conjunction with frequency. Required.""" - schedule: Optional["_models.RecurrenceSchedule"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The recurrence schedule.""" - - @overload - def __init__( - self, - *, - frequency: Union[str, "_models.Frequency"], - interval: int, - schedule: Optional["_models.RecurrenceSchedule"] = 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, type="Recurrence", **kwargs) - - -class RequiredAction(_model_base.Model): - """An abstract representation of a required action for an agent thread run to continue. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - SubmitToolOutputsAction - - :ivar type: The object type. Required. Default value is None. - :vartype type: str - """ - - __mapping__: Dict[str, _model_base.Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The object type. Required. Default value is None.""" - - @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 RequiredToolCall(_model_base.Model): - """An abstract representation of a tool invocation needed by the model to continue a run. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - RequiredFunctionToolCall - - :ivar type: The object type for the required tool call. Required. Default value is None. - :vartype type: str - :ivar id: The ID of the tool call. This ID must be referenced when submitting tool outputs. - Required. - :vartype id: str - """ - - __mapping__: Dict[str, _model_base.Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The object type for the required tool call. Required. Default value is None.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the tool call. This ID must be referenced when submitting tool outputs. Required.""" - - @overload - def __init__( - self, - *, - type: str, - id: str, # pylint: disable=redefined-builtin - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class RequiredFunctionToolCall(RequiredToolCall, discriminator="function"): - """A representation of a requested call to a function tool, needed by the model to continue - evaluation of a run. - - :ivar id: The ID of the tool call. This ID must be referenced when submitting tool outputs. - Required. - :vartype id: str - :ivar type: The object type of the required tool call. Always 'function' for function tools. - Required. Default value is "function". - :vartype type: str - :ivar function: Detailed information about the function to be executed by the tool that - includes name and arguments. Required. - :vartype function: ~azure.ai.projects.models.RequiredFunctionToolCallDetails - """ - - type: Literal["function"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type of the required tool call. Always 'function' for function tools. Required. - Default value is \"function\".""" - function: "_models.RequiredFunctionToolCallDetails" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Detailed information about the function to be executed by the tool that includes name and - arguments. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - function: "_models.RequiredFunctionToolCallDetails", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="function", **kwargs) - - -class RequiredFunctionToolCallDetails(_model_base.Model): - """The detailed information for a function invocation, as provided by a required action invoking a - function tool, that includes the name of and arguments to the function. - - :ivar name: The name of the function. Required. - :vartype name: str - :ivar arguments: The arguments to use when invoking the named function, as provided by the - model. Arguments are presented as a JSON document that should be validated and parsed for - evaluation. Required. - :vartype arguments: str - """ - - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the function. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The arguments to use when invoking the named function, as provided by the model. Arguments are - presented as a JSON document that should be validated and parsed for evaluation. Required.""" - - @overload - def __init__( - self, - *, - name: str, - arguments: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ResponseFormatJsonSchema(_model_base.Model): - """A description of what the response format is for, used by the model to determine how to respond - in the format. - - :ivar description: A description of what the response format is for, used by the model to - determine how to respond in the format. - :vartype description: str - :ivar name: The name of a schema. Required. - :vartype name: str - :ivar schema: The JSON schema object, describing the response format. Required. - :vartype schema: any - """ - - description: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A description of what the response format is for, used by the model to determine how to respond - in the format.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of a schema. Required.""" - schema: Any = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The JSON schema object, describing the response format. Required.""" - - @overload - def __init__( - self, - *, - name: str, - schema: Any, - description: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ResponseFormatJsonSchemaType(_model_base.Model): - """The type of response format being defined: ``json_schema``. - - :ivar type: Type. Required. Default value is "json_schema". - :vartype type: str - :ivar json_schema: The JSON schema, describing response format. Required. - :vartype json_schema: ~azure.ai.projects.models.ResponseFormatJsonSchema - """ - - type: Literal["json_schema"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Type. Required. Default value is \"json_schema\".""" - json_schema: "_models.ResponseFormatJsonSchema" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The JSON schema, describing response format. Required.""" - - @overload - def __init__( - self, - *, - json_schema: "_models.ResponseFormatJsonSchema", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.type: Literal["json_schema"] = "json_schema" - - -class RunCompletionUsage(_model_base.Model): - """Usage statistics related to the run. This value will be ``null`` if the run is not in a - terminal state (i.e. ``in_progress``, ``queued``, etc.). - - :ivar completion_tokens: Number of completion tokens used over the course of the run. Required. - :vartype completion_tokens: int - :ivar prompt_tokens: Number of prompt tokens used over the course of the run. Required. - :vartype prompt_tokens: int - :ivar total_tokens: Total number of tokens used (prompt + completion). Required. - :vartype total_tokens: int - """ - - completion_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Number of completion tokens used over the course of the run. Required.""" - prompt_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Number of prompt tokens used over the course of the run. Required.""" - total_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Total number of tokens used (prompt + completion). Required.""" - - @overload - def __init__( - self, - *, - completion_tokens: int, - prompt_tokens: int, - 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 RunError(_model_base.Model): - """The details of an error as encountered by an agent thread run. - - :ivar code: The status for the error. Required. - :vartype code: str - :ivar message: The human-readable text associated with the error. Required. - :vartype message: str - """ - - code: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The status for the error. Required.""" - message: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The human-readable text associated with the error. Required.""" - - @overload - def __init__( - self, - *, - code: str, - message: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class RunStep(_model_base.Model): - """Detailed information about a single step of an agent thread run. - - :ivar id: The identifier, which can be referenced in API endpoints. Required. - :vartype id: str - :ivar object: The object type, which is always 'thread.run.step'. Required. Default value is - "thread.run.step". - :vartype object: str - :ivar type: The type of run step, which can be either message_creation or tool_calls. Required. - Known values are: "message_creation" and "tool_calls". - :vartype type: str or ~azure.ai.projects.models.RunStepType - :ivar agent_id: The ID of the agent associated with the run step. Required. - :vartype agent_id: str - :ivar thread_id: The ID of the thread that was run. Required. - :vartype thread_id: str - :ivar run_id: The ID of the run that this run step is a part of. Required. - :vartype run_id: str - :ivar status: The status of this run step. Required. Known values are: "in_progress", - "cancelled", "failed", "completed", and "expired". - :vartype status: str or ~azure.ai.projects.models.RunStepStatus - :ivar step_details: The details for this run step. Required. - :vartype step_details: ~azure.ai.projects.models.RunStepDetails - :ivar last_error: If applicable, information about the last error encountered by this run step. - Required. - :vartype last_error: ~azure.ai.projects.models.RunStepError - :ivar created_at: The Unix timestamp, in seconds, representing when this object was created. - Required. - :vartype created_at: ~datetime.datetime - :ivar expired_at: The Unix timestamp, in seconds, representing when this item expired. - Required. - :vartype expired_at: ~datetime.datetime - :ivar completed_at: The Unix timestamp, in seconds, representing when this completed. Required. - :vartype completed_at: ~datetime.datetime - :ivar cancelled_at: The Unix timestamp, in seconds, representing when this was cancelled. - Required. - :vartype cancelled_at: ~datetime.datetime - :ivar failed_at: The Unix timestamp, in seconds, representing when this failed. Required. - :vartype failed_at: ~datetime.datetime - :ivar usage: Usage statistics related to the run step. This value will be ``null`` while the - run step's status is ``in_progress``. - :vartype usage: ~azure.ai.projects.models.RunStepCompletionUsage - :ivar metadata: A set of up to 16 key/value pairs that can be attached to an object, used for - storing additional information about that object in a structured format. Keys may be up to 64 - characters in length and values may be up to 512 characters in length. Required. - :vartype metadata: dict[str, str] - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The identifier, which can be referenced in API endpoints. Required.""" - object: Literal["thread.run.step"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always 'thread.run.step'. Required. Default value is - \"thread.run.step\".""" - type: Union[str, "_models.RunStepType"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The type of run step, which can be either message_creation or tool_calls. Required. Known - values are: \"message_creation\" and \"tool_calls\".""" - agent_id: str = rest_field(name="assistant_id", visibility=["read", "create", "update", "delete", "query"]) - """The ID of the agent associated with the run step. Required.""" - thread_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the thread that was run. Required.""" - run_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the run that this run step is a part of. Required.""" - status: Union[str, "_models.RunStepStatus"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The status of this run step. Required. Known values are: \"in_progress\", \"cancelled\", - \"failed\", \"completed\", and \"expired\".""" - step_details: "_models.RunStepDetails" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The details for this run step. Required.""" - last_error: "_models.RunStepError" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """If applicable, information about the last error encountered by this run step. Required.""" - created_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp, in seconds, representing when this object was created. Required.""" - expired_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp, in seconds, representing when this item expired. Required.""" - completed_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp, in seconds, representing when this completed. Required.""" - cancelled_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp, in seconds, representing when this was cancelled. Required.""" - failed_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp, in seconds, representing when this failed. Required.""" - usage: Optional["_models.RunStepCompletionUsage"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Usage statistics related to the run step. This value will be ``null`` while the run step's - status is ``in_progress``.""" - metadata: Dict[str, str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A set of up to 16 key/value pairs that can be attached to an object, used for storing - additional information about that object in a structured format. Keys may be up to 64 - characters in length and values may be up to 512 characters in length. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - type: Union[str, "_models.RunStepType"], - agent_id: str, - thread_id: str, - run_id: str, - status: Union[str, "_models.RunStepStatus"], - step_details: "_models.RunStepDetails", - last_error: "_models.RunStepError", - created_at: datetime.datetime, - expired_at: datetime.datetime, - completed_at: datetime.datetime, - cancelled_at: datetime.datetime, - failed_at: datetime.datetime, - metadata: Dict[str, str], - usage: Optional["_models.RunStepCompletionUsage"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.object: Literal["thread.run.step"] = "thread.run.step" - - -class RunStepToolCall(_model_base.Model): - """An abstract representation of a detailed tool call as recorded within a run step for an - existing run. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - RunStepAzureAISearchToolCall, RunStepCustomSearchToolCall, RunStepBingGroundingToolCall, - RunStepCodeInterpreterToolCall, RunStepMicrosoftFabricToolCall, RunStepFileSearchToolCall, - RunStepFunctionToolCall, RunStepOpenAPIToolCall, RunStepSharepointToolCall - - :ivar type: The object type. Required. Default value is None. - :vartype type: str - :ivar id: The ID of the tool call. This ID must be referenced when you submit tool outputs. - Required. - :vartype id: str - """ - - __mapping__: Dict[str, _model_base.Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The object type. Required. Default value is None.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the tool call. This ID must be referenced when you submit tool outputs. Required.""" - - @overload - def __init__( - self, - *, - type: str, - id: str, # pylint: disable=redefined-builtin - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class RunStepAzureAISearchToolCall(RunStepToolCall, discriminator="azure_ai_search"): - """A record of a call to an Azure AI Search tool, issued by the model in evaluation of a defined - tool, that represents - executed Azure AI search. - - :ivar id: The ID of the tool call. This ID must be referenced when you submit tool outputs. - Required. - :vartype id: str - :ivar type: The object type, which is always 'azure_ai_search'. Required. Default value is - "azure_ai_search". - :vartype type: str - :ivar azure_ai_search: Reserved for future use. Required. - :vartype azure_ai_search: dict[str, str] - """ - - type: Literal["azure_ai_search"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'azure_ai_search'. Required. Default value is - \"azure_ai_search\".""" - azure_ai_search: Dict[str, str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Reserved for future use. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - azure_ai_search: Dict[str, 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, type="azure_ai_search", **kwargs) - - -class RunStepBingGroundingToolCall(RunStepToolCall, discriminator="bing_grounding"): - """A record of a call to a bing grounding tool, issued by the model in evaluation of a defined - tool, that represents - executed search with bing grounding. - - :ivar id: The ID of the tool call. This ID must be referenced when you submit tool outputs. - Required. - :vartype id: str - :ivar type: The object type, which is always 'bing_grounding'. Required. Default value is - "bing_grounding". - :vartype type: str - :ivar bing_grounding: Reserved for future use. Required. - :vartype bing_grounding: dict[str, str] - """ - - type: Literal["bing_grounding"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'bing_grounding'. Required. Default value is - \"bing_grounding\".""" - bing_grounding: Dict[str, str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Reserved for future use. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - bing_grounding: Dict[str, 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, type="bing_grounding", **kwargs) - - -class RunStepCodeInterpreterToolCallOutput(_model_base.Model): - """An abstract representation of an emitted output from a code interpreter tool. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - RunStepCodeInterpreterImageOutput, RunStepCodeInterpreterLogOutput - - :ivar type: The object type. Required. Default value is None. - :vartype type: str - """ - - __mapping__: Dict[str, _model_base.Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The object type. Required. Default value is None.""" - - @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 RunStepCodeInterpreterImageOutput(RunStepCodeInterpreterToolCallOutput, discriminator="image"): - """A representation of an image output emitted by a code interpreter tool in response to a tool - call by the model. - - :ivar type: The object type, which is always 'image'. Required. Default value is "image". - :vartype type: str - :ivar image: Referential information for the image associated with this output. Required. - :vartype image: ~azure.ai.projects.models.RunStepCodeInterpreterImageReference - """ - - type: Literal["image"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'image'. Required. Default value is \"image\".""" - image: "_models.RunStepCodeInterpreterImageReference" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Referential information for the image associated with this output. Required.""" - - @overload - def __init__( - self, - *, - image: "_models.RunStepCodeInterpreterImageReference", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="image", **kwargs) - - -class RunStepCodeInterpreterImageReference(_model_base.Model): - """An image reference emitted by a code interpreter tool in response to a tool call by the model. - - :ivar file_id: The ID of the file associated with this image. Required. - :vartype file_id: str - """ - - file_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the file associated with this image. Required.""" - - @overload - def __init__( - self, - *, - file_id: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class RunStepCodeInterpreterLogOutput(RunStepCodeInterpreterToolCallOutput, discriminator="logs"): - """A representation of a log output emitted by a code interpreter tool in response to a tool call - by the model. - - :ivar type: The object type, which is always 'logs'. Required. Default value is "logs". - :vartype type: str - :ivar logs: The serialized log output emitted by the code interpreter. Required. - :vartype logs: str - """ - - type: Literal["logs"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'logs'. Required. Default value is \"logs\".""" - logs: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The serialized log output emitted by the code interpreter. Required.""" - - @overload - def __init__( - self, - *, - logs: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="logs", **kwargs) - - -class RunStepCodeInterpreterToolCall(RunStepToolCall, discriminator="code_interpreter"): - """A record of a call to a code interpreter tool, issued by the model in evaluation of a defined - tool, that - represents inputs and outputs consumed and emitted by the code interpreter. - - :ivar id: The ID of the tool call. This ID must be referenced when you submit tool outputs. - Required. - :vartype id: str - :ivar type: The object type, which is always 'code_interpreter'. Required. Default value is - "code_interpreter". - :vartype type: str - :ivar code_interpreter: The details of the tool call to the code interpreter tool. Required. - :vartype code_interpreter: ~azure.ai.projects.models.RunStepCodeInterpreterToolCallDetails - """ - - type: Literal["code_interpreter"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'code_interpreter'. Required. Default value is - \"code_interpreter\".""" - code_interpreter: "_models.RunStepCodeInterpreterToolCallDetails" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The details of the tool call to the code interpreter tool. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - code_interpreter: "_models.RunStepCodeInterpreterToolCallDetails", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="code_interpreter", **kwargs) - - -class RunStepCodeInterpreterToolCallDetails(_model_base.Model): - """The detailed information about a code interpreter invocation by the model. - - :ivar input: The input provided by the model to the code interpreter tool. Required. - :vartype input: str - :ivar outputs: The outputs produced by the code interpreter tool back to the model in response - to the tool call. Required. - :vartype outputs: list[~azure.ai.projects.models.RunStepCodeInterpreterToolCallOutput] - """ - - input: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The input provided by the model to the code interpreter tool. Required.""" - outputs: List["_models.RunStepCodeInterpreterToolCallOutput"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The outputs produced by the code interpreter tool back to the model in response to the tool - call. Required.""" - - @overload - def __init__( - self, - *, - input: str, - outputs: List["_models.RunStepCodeInterpreterToolCallOutput"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param 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 RunStepCompletionUsage(_model_base.Model): - """Usage statistics related to the run step. - - :ivar completion_tokens: Number of completion tokens used over the course of the run step. - Required. - :vartype completion_tokens: int - :ivar prompt_tokens: Number of prompt tokens used over the course of the run step. Required. - :vartype prompt_tokens: int - :ivar total_tokens: Total number of tokens used (prompt + completion). Required. - :vartype total_tokens: int - """ - - completion_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Number of completion tokens used over the course of the run step. Required.""" - prompt_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Number of prompt tokens used over the course of the run step. Required.""" - total_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Total number of tokens used (prompt + completion). Required.""" - - @overload - def __init__( - self, - *, - completion_tokens: int, - prompt_tokens: int, - 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 RunStepCustomSearchToolCall(RunStepToolCall, discriminator="bing_custom_search"): - """A record of a call to a bing custom search tool, issued by the model in evaluation of a defined - tool, that represents - executed search with bing custom search. - - :ivar id: The ID of the tool call. This ID must be referenced when you submit tool outputs. - Required. - :vartype id: str - :ivar type: The object type, which is always 'bing_custom_search'. Required. Default value is - "bing_custom_search". - :vartype type: str - :ivar bing_custom_search: Reserved for future use. Required. - :vartype bing_custom_search: dict[str, str] - """ - - type: Literal["bing_custom_search"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'bing_custom_search'. Required. Default value is - \"bing_custom_search\".""" - bing_custom_search: Dict[str, str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Reserved for future use. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - bing_custom_search: Dict[str, 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, type="bing_custom_search", **kwargs) - - -class RunStepDelta(_model_base.Model): - """Represents the delta payload in a streaming run step delta chunk. - - :ivar step_details: The details of the run step. - :vartype step_details: ~azure.ai.projects.models.RunStepDeltaDetail - """ - - step_details: Optional["_models.RunStepDeltaDetail"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The details of the run step.""" - - @overload - def __init__( - self, - *, - step_details: Optional["_models.RunStepDeltaDetail"] = 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 RunStepDeltaChunk(_model_base.Model): - """Represents a run step delta i.e. any changed fields on a run step during streaming. - - :ivar id: The identifier of the run step, which can be referenced in API endpoints. Required. - :vartype id: str - :ivar object: The object type, which is always ``thread.run.step.delta``. Required. Default - value is "thread.run.step.delta". - :vartype object: str - :ivar delta: The delta containing the fields that have changed on the run step. Required. - :vartype delta: ~azure.ai.projects.models.RunStepDelta - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The identifier of the run step, which can be referenced in API endpoints. Required.""" - object: Literal["thread.run.step.delta"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always ``thread.run.step.delta``. Required. Default value is - \"thread.run.step.delta\".""" - delta: "_models.RunStepDelta" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The delta containing the fields that have changed on the run step. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - delta: "_models.RunStepDelta", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.object: Literal["thread.run.step.delta"] = "thread.run.step.delta" - - -class RunStepDeltaCodeInterpreterDetailItemObject(_model_base.Model): # pylint: disable=name-too-long - """Represents the Code Interpreter tool call data in a streaming run step's tool calls. - - :ivar input: The input into the Code Interpreter tool call. - :vartype input: str - :ivar outputs: The outputs from the Code Interpreter tool call. Code Interpreter can output one - or more - items, including text (``logs``) or images (``image``). Each of these are represented by a - different object type. - :vartype outputs: list[~azure.ai.projects.models.RunStepDeltaCodeInterpreterOutput] - """ - - input: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The input into the Code Interpreter tool call.""" - outputs: Optional[List["_models.RunStepDeltaCodeInterpreterOutput"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The outputs from the Code Interpreter tool call. Code Interpreter can output one or more - items, including text (``logs``) or images (``image``). Each of these are represented by a - different object type.""" - - @overload - def __init__( - self, - *, - input: Optional[str] = None, - outputs: Optional[List["_models.RunStepDeltaCodeInterpreterOutput"]] = 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 RunStepDeltaCodeInterpreterOutput(_model_base.Model): - """The abstract base representation of a streaming run step tool call's Code Interpreter tool - output. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - RunStepDeltaCodeInterpreterImageOutput, RunStepDeltaCodeInterpreterLogOutput - - :ivar index: The index of the output in the streaming run step tool call's Code Interpreter - outputs array. Required. - :vartype index: int - :ivar type: The type of the streaming run step tool call's Code Interpreter output. Required. - Default value is None. - :vartype type: str - """ - - __mapping__: Dict[str, _model_base.Model] = {} - index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the output in the streaming run step tool call's Code Interpreter outputs array. - Required.""" - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The type of the streaming run step tool call's Code Interpreter output. Required. Default value - is None.""" - - @overload - def __init__( - self, - *, - index: int, - 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 RunStepDeltaCodeInterpreterImageOutput(RunStepDeltaCodeInterpreterOutput, discriminator="image"): - """Represents an image output as produced the Code interpreter tool and as represented in a - streaming run step's delta tool calls collection. - - :ivar index: The index of the output in the streaming run step tool call's Code Interpreter - outputs array. Required. - :vartype index: int - :ivar type: The object type, which is always "image.". Required. Default value is "image". - :vartype type: str - :ivar image: The image data for the Code Interpreter tool call output. - :vartype image: ~azure.ai.projects.models.RunStepDeltaCodeInterpreterImageOutputObject - """ - - type: Literal["image"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always \"image.\". Required. Default value is \"image\".""" - image: Optional["_models.RunStepDeltaCodeInterpreterImageOutputObject"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The image data for the Code Interpreter tool call output.""" - - @overload - def __init__( - self, - *, - index: int, - image: Optional["_models.RunStepDeltaCodeInterpreterImageOutputObject"] = 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, type="image", **kwargs) - - -class RunStepDeltaCodeInterpreterImageOutputObject(_model_base.Model): # pylint: disable=name-too-long - """Represents the data for a streaming run step's Code Interpreter tool call image output. - - :ivar file_id: The file ID for the image. - :vartype file_id: str - """ - - file_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The file ID for the image.""" - - @overload - def __init__( - self, - *, - file_id: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class RunStepDeltaCodeInterpreterLogOutput(RunStepDeltaCodeInterpreterOutput, discriminator="logs"): - """Represents a log output as produced by the Code Interpreter tool and as represented in a - streaming run step's delta tool calls collection. - - :ivar index: The index of the output in the streaming run step tool call's Code Interpreter - outputs array. Required. - :vartype index: int - :ivar type: The type of the object, which is always "logs.". Required. Default value is "logs". - :vartype type: str - :ivar logs: The text output from the Code Interpreter tool call. - :vartype logs: str - """ - - type: Literal["logs"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The type of the object, which is always \"logs.\". Required. Default value is \"logs\".""" - logs: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The text output from the Code Interpreter tool call.""" - - @overload - def __init__( - self, - *, - index: int, - logs: 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, type="logs", **kwargs) - - -class RunStepDeltaToolCall(_model_base.Model): - """The abstract base representation of a single tool call within a streaming run step's delta tool - call details. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - RunStepDeltaCodeInterpreterToolCall, RunStepDeltaFileSearchToolCall, - RunStepDeltaFunctionToolCall - - :ivar index: The index of the tool call detail in the run step's tool_calls array. Required. - :vartype index: int - :ivar id: The ID of the tool call, used when submitting outputs to the run. Required. - :vartype id: str - :ivar type: The type of the tool call detail item in a streaming run step's details. Required. - Default value is None. - :vartype type: str - """ - - __mapping__: Dict[str, _model_base.Model] = {} - index: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The index of the tool call detail in the run step's tool_calls array. Required.""" - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the tool call, used when submitting outputs to the run. Required.""" - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The type of the tool call detail item in a streaming run step's details. Required. Default - value is None.""" - - @overload - def __init__( - self, - *, - index: int, - id: str, # pylint: disable=redefined-builtin - 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 RunStepDeltaCodeInterpreterToolCall(RunStepDeltaToolCall, discriminator="code_interpreter"): - """Represents a Code Interpreter tool call within a streaming run step's tool call details. - - :ivar index: The index of the tool call detail in the run step's tool_calls array. Required. - :vartype index: int - :ivar id: The ID of the tool call, used when submitting outputs to the run. Required. - :vartype id: str - :ivar type: The object type, which is always "code_interpreter.". Required. Default value is - "code_interpreter". - :vartype type: str - :ivar code_interpreter: The Code Interpreter data for the tool call. - :vartype code_interpreter: - ~azure.ai.projects.models.RunStepDeltaCodeInterpreterDetailItemObject - """ - - type: Literal["code_interpreter"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always \"code_interpreter.\". Required. Default value is - \"code_interpreter\".""" - code_interpreter: Optional["_models.RunStepDeltaCodeInterpreterDetailItemObject"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The Code Interpreter data for the tool call.""" - - @overload - def __init__( - self, - *, - index: int, - id: str, # pylint: disable=redefined-builtin - code_interpreter: Optional["_models.RunStepDeltaCodeInterpreterDetailItemObject"] = 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, type="code_interpreter", **kwargs) - - -class RunStepDeltaDetail(_model_base.Model): - """Represents a single run step detail item in a streaming run step's delta payload. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - RunStepDeltaMessageCreation, RunStepDeltaToolCallObject - - :ivar type: The object type for the run step detail object. Required. Default value is None. - :vartype type: str - """ - - __mapping__: Dict[str, _model_base.Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The object type for the run step detail object. Required. Default value is None.""" - - @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 RunStepDeltaFileSearchToolCall(RunStepDeltaToolCall, discriminator="file_search"): - """Represents a file search tool call within a streaming run step's tool call details. - - :ivar index: The index of the tool call detail in the run step's tool_calls array. Required. - :vartype index: int - :ivar id: The ID of the tool call, used when submitting outputs to the run. Required. - :vartype id: str - :ivar type: The object type, which is always "file_search.". Required. Default value is - "file_search". - :vartype type: str - :ivar file_search: Reserved for future use. - :vartype file_search: ~azure.ai.projects.models.RunStepFileSearchToolCallResults - """ - - type: Literal["file_search"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always \"file_search.\". Required. Default value is \"file_search\".""" - file_search: Optional["_models.RunStepFileSearchToolCallResults"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Reserved for future use.""" - - @overload - def __init__( - self, - *, - index: int, - id: str, # pylint: disable=redefined-builtin - file_search: Optional["_models.RunStepFileSearchToolCallResults"] = 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, type="file_search", **kwargs) - - -class RunStepDeltaFunction(_model_base.Model): - """Represents the function data in a streaming run step delta's function tool call. - - :ivar name: The name of the function. - :vartype name: str - :ivar arguments: The arguments passed to the function as input. - :vartype arguments: str - :ivar output: The output of the function, null if outputs have not yet been submitted. - :vartype output: str - """ - - name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the function.""" - arguments: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The arguments passed to the function as input.""" - output: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The output of the function, null if outputs have not yet been submitted.""" - - @overload - def __init__( - self, - *, - name: Optional[str] = None, - arguments: Optional[str] = None, - output: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class RunStepDeltaFunctionToolCall(RunStepDeltaToolCall, discriminator="function"): - """Represents a function tool call within a streaming run step's tool call details. - - :ivar index: The index of the tool call detail in the run step's tool_calls array. Required. - :vartype index: int - :ivar id: The ID of the tool call, used when submitting outputs to the run. Required. - :vartype id: str - :ivar type: The object type, which is always "function.". Required. Default value is - "function". - :vartype type: str - :ivar function: The function data for the tool call. - :vartype function: ~azure.ai.projects.models.RunStepDeltaFunction - """ - - type: Literal["function"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always \"function.\". Required. Default value is \"function\".""" - function: Optional["_models.RunStepDeltaFunction"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The function data for the tool call.""" - - @overload - def __init__( - self, - *, - index: int, - id: str, # pylint: disable=redefined-builtin - function: Optional["_models.RunStepDeltaFunction"] = 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, type="function", **kwargs) - - -class RunStepDeltaMessageCreation(RunStepDeltaDetail, discriminator="message_creation"): - """Represents a message creation within a streaming run step delta. - - :ivar type: The object type, which is always "message_creation.". Required. Default value is - "message_creation". - :vartype type: str - :ivar message_creation: The message creation data. - :vartype message_creation: ~azure.ai.projects.models.RunStepDeltaMessageCreationObject - """ - - type: Literal["message_creation"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always \"message_creation.\". Required. Default value is - \"message_creation\".""" - message_creation: Optional["_models.RunStepDeltaMessageCreationObject"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The message creation data.""" - - @overload - def __init__( - self, - *, - message_creation: Optional["_models.RunStepDeltaMessageCreationObject"] = 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, type="message_creation", **kwargs) - - -class RunStepDeltaMessageCreationObject(_model_base.Model): - """Represents the data within a streaming run step message creation response object. - - :ivar message_id: The ID of the newly-created message. - :vartype message_id: str - """ - - message_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the newly-created message.""" - - @overload - def __init__( - self, - *, - message_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 RunStepDeltaToolCallObject(RunStepDeltaDetail, discriminator="tool_calls"): - """Represents an invocation of tool calls as part of a streaming run step. - - :ivar type: The object type, which is always "tool_calls.". Required. Default value is - "tool_calls". - :vartype type: str - :ivar tool_calls: The collection of tool calls for the tool call detail item. - :vartype tool_calls: list[~azure.ai.projects.models.RunStepDeltaToolCall] - """ - - type: Literal["tool_calls"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always \"tool_calls.\". Required. Default value is \"tool_calls\".""" - tool_calls: Optional[List["_models.RunStepDeltaToolCall"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The collection of tool calls for the tool call detail item.""" - - @overload - def __init__( - self, - *, - tool_calls: Optional[List["_models.RunStepDeltaToolCall"]] = 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, type="tool_calls", **kwargs) - - -class RunStepDetails(_model_base.Model): - """An abstract representation of the details for a run step. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - RunStepMessageCreationDetails, RunStepToolCallDetails - - :ivar type: The object type. Required. Known values are: "message_creation" and "tool_calls". - :vartype type: str or ~azure.ai.projects.models.RunStepType - """ - - __mapping__: Dict[str, _model_base.Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The object type. Required. Known values are: \"message_creation\" and \"tool_calls\".""" - - @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 RunStepError(_model_base.Model): - """The error information associated with a failed run step. - - :ivar code: The error code for this error. Required. Known values are: "server_error" and - "rate_limit_exceeded". - :vartype code: str or ~azure.ai.projects.models.RunStepErrorCode - :ivar message: The human-readable text associated with this error. Required. - :vartype message: str - """ - - code: Union[str, "_models.RunStepErrorCode"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The error code for this error. Required. Known values are: \"server_error\" and - \"rate_limit_exceeded\".""" - message: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The human-readable text associated with this error. Required.""" - - @overload - def __init__( - self, - *, - code: Union[str, "_models.RunStepErrorCode"], - message: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class RunStepFileSearchToolCall(RunStepToolCall, discriminator="file_search"): - """A record of a call to a file search tool, issued by the model in evaluation of a defined tool, - that represents - executed file search. - - :ivar type: The object type, which is always 'file_search'. Required. Default value is - "file_search". - :vartype type: str - :ivar id: The ID of the tool call. This ID must be referenced when you submit tool outputs. - Required. - :vartype id: str - :ivar file_search: For now, this is always going to be an empty object. Required. - :vartype file_search: ~azure.ai.projects.models.RunStepFileSearchToolCallResults - """ - - type: Literal["file_search"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'file_search'. Required. Default value is \"file_search\".""" - file_search: "_models.RunStepFileSearchToolCallResults" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """For now, this is always going to be an empty object. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - file_search: "_models.RunStepFileSearchToolCallResults", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="file_search", **kwargs) - - -class RunStepFileSearchToolCallResult(_model_base.Model): - """File search tool call result. - - :ivar file_id: The ID of the file that result was found in. Required. - :vartype file_id: str - :ivar file_name: The name of the file that result was found in. Required. - :vartype file_name: str - :ivar score: The score of the result. All values must be a floating point number between 0 and - 1. Required. - :vartype score: float - :ivar content: The content of the result that was found. The content is only included if - requested via the include query parameter. - :vartype content: list[~azure.ai.projects.models.FileSearchToolCallContent] - """ - - file_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the file that result was found in. Required.""" - file_name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the file that result was found in. Required.""" - score: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The score of the result. All values must be a floating point number between 0 and 1. Required.""" - content: Optional[List["_models.FileSearchToolCallContent"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The content of the result that was found. The content is only included if requested via the - include query parameter.""" - - @overload - def __init__( - self, - *, - file_id: str, - file_name: str, - score: float, - content: Optional[List["_models.FileSearchToolCallContent"]] = 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 RunStepFileSearchToolCallResults(_model_base.Model): - """The results of the file search. - - :ivar ranking_options: Ranking options for file search. - :vartype ranking_options: ~azure.ai.projects.models.FileSearchRankingOptions - :ivar results: The array of a file search results. Required. - :vartype results: list[~azure.ai.projects.models.RunStepFileSearchToolCallResult] - """ - - ranking_options: Optional["_models.FileSearchRankingOptions"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Ranking options for file search.""" - results: List["_models.RunStepFileSearchToolCallResult"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The array of a file search results. Required.""" - - @overload - def __init__( - self, - *, - results: List["_models.RunStepFileSearchToolCallResult"], - ranking_options: Optional["_models.FileSearchRankingOptions"] = 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 RunStepFunctionToolCall(RunStepToolCall, discriminator="function"): - """A record of a call to a function tool, issued by the model in evaluation of a defined tool, - that represents the inputs - and output consumed and emitted by the specified function. - - :ivar id: The ID of the tool call. This ID must be referenced when you submit tool outputs. - Required. - :vartype id: str - :ivar type: The object type, which is always 'function'. Required. Default value is "function". - :vartype type: str - :ivar function: The detailed information about the function called by the model. Required. - :vartype function: ~azure.ai.projects.models.RunStepFunctionToolCallDetails - """ - - type: Literal["function"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'function'. Required. Default value is \"function\".""" - function: "_models.RunStepFunctionToolCallDetails" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The detailed information about the function called by the model. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - function: "_models.RunStepFunctionToolCallDetails", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="function", **kwargs) - - -class RunStepFunctionToolCallDetails(_model_base.Model): - """The detailed information about the function called by the model. - - :ivar name: The name of the function. Required. - :vartype name: str - :ivar arguments: The arguments that the model requires are provided to the named function. - Required. - :vartype arguments: str - :ivar output: The output of the function, only populated for function calls that have already - have had their outputs submitted. Required. - :vartype output: str - """ - - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the function. Required.""" - arguments: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The arguments that the model requires are provided to the named function. Required.""" - output: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The output of the function, only populated for function calls that have already have had their - outputs submitted. Required.""" - - @overload - def __init__( - self, - *, - name: str, - arguments: str, - output: 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 RunStepMessageCreationDetails(RunStepDetails, discriminator="message_creation"): - """The detailed information associated with a message creation run step. - - :ivar type: The object type, which is always 'message_creation'. Required. Represents a run - step to create a message. - :vartype type: str or ~azure.ai.projects.models.MESSAGE_CREATION - :ivar message_creation: Information about the message creation associated with this run step. - Required. - :vartype message_creation: ~azure.ai.projects.models.RunStepMessageCreationReference - """ - - type: Literal[RunStepType.MESSAGE_CREATION] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'message_creation'. Required. Represents a run step to create - a message.""" - message_creation: "_models.RunStepMessageCreationReference" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Information about the message creation associated with this run step. Required.""" - - @overload - def __init__( - self, - *, - message_creation: "_models.RunStepMessageCreationReference", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type=RunStepType.MESSAGE_CREATION, **kwargs) - - -class RunStepMessageCreationReference(_model_base.Model): - """The details of a message created as a part of a run step. - - :ivar message_id: The ID of the message created by this run step. Required. - :vartype message_id: str - """ - - message_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the message created by this run step. Required.""" - - @overload - def __init__( - self, - *, - message_id: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class RunStepMicrosoftFabricToolCall(RunStepToolCall, discriminator="fabric_dataagent"): - """A record of a call to a Microsoft Fabric tool, issued by the model in evaluation of a defined - tool, that represents - executed Microsoft Fabric operations. - - :ivar id: The ID of the tool call. This ID must be referenced when you submit tool outputs. - Required. - :vartype id: str - :ivar type: The object type, which is always 'fabric_dataagent'. Required. Default value is - "fabric_dataagent". - :vartype type: str - :ivar microsoft_fabric: Reserved for future use. Required. - :vartype microsoft_fabric: dict[str, str] - """ - - type: Literal["fabric_dataagent"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'fabric_dataagent'. Required. Default value is - \"fabric_dataagent\".""" - microsoft_fabric: Dict[str, str] = rest_field( - name="fabric_dataagent", visibility=["read", "create", "update", "delete", "query"] - ) - """Reserved for future use. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - microsoft_fabric: Dict[str, 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, type="fabric_dataagent", **kwargs) - - -class RunStepOpenAPIToolCall(RunStepToolCall, discriminator="openapi"): - """A record of a call to an OpenAPI tool, issued by the model in evaluation of a defined tool, - that represents - executed OpenAPI operations. - - :ivar id: The ID of the tool call. This ID must be referenced when you submit tool outputs. - Required. - :vartype id: str - :ivar type: The object type, which is always 'openapi'. Required. Default value is "openapi". - :vartype type: str - :ivar open_api: Reserved for future use. Required. - :vartype open_api: dict[str, str] - """ - - type: Literal["openapi"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'openapi'. Required. Default value is \"openapi\".""" - open_api: Dict[str, str] = rest_field(name="openapi", visibility=["read", "create", "update", "delete", "query"]) - """Reserved for future use. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - open_api: Dict[str, 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, type="openapi", **kwargs) - - -class RunStepSharepointToolCall(RunStepToolCall, discriminator="sharepoint_grounding"): - """A record of a call to a SharePoint tool, issued by the model in evaluation of a defined tool, - that represents - executed SharePoint actions. - - :ivar id: The ID of the tool call. This ID must be referenced when you submit tool outputs. - Required. - :vartype id: str - :ivar type: The object type, which is always 'sharepoint_grounding'. Required. Default value is - "sharepoint_grounding". - :vartype type: str - :ivar share_point: Reserved for future use. Required. - :vartype share_point: dict[str, str] - """ - - type: Literal["sharepoint_grounding"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'sharepoint_grounding'. Required. Default value is - \"sharepoint_grounding\".""" - share_point: Dict[str, str] = rest_field( - name="sharepoint_grounding", visibility=["read", "create", "update", "delete", "query"] - ) - """Reserved for future use. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - share_point: Dict[str, 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, type="sharepoint_grounding", **kwargs) - - -class RunStepToolCallDetails(RunStepDetails, discriminator="tool_calls"): - """The detailed information associated with a run step calling tools. - - :ivar type: The object type, which is always 'tool_calls'. Required. Represents a run step that - calls tools. - :vartype type: str or ~azure.ai.projects.models.TOOL_CALLS - :ivar tool_calls: A list of tool call details for this run step. Required. - :vartype tool_calls: list[~azure.ai.projects.models.RunStepToolCall] - """ - - type: Literal[RunStepType.TOOL_CALLS] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'tool_calls'. Required. Represents a run step that calls - tools.""" - tool_calls: List["_models.RunStepToolCall"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A list of tool call details for this run step. Required.""" - - @overload - def __init__( - self, - *, - tool_calls: List["_models.RunStepToolCall"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type=RunStepType.TOOL_CALLS, **kwargs) - - -class SearchConfiguration(_model_base.Model): - """A custom search configuration. - - :ivar connection_id: A connection in a ToolConnectionList attached to this tool. Required. - :vartype connection_id: str - :ivar instance_name: Name of the custom configuration instance given to config. Required. - :vartype instance_name: str - """ - - connection_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A connection in a ToolConnectionList attached to this tool. Required.""" - instance_name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Name of the custom configuration instance given to config. Required.""" - - @overload - def __init__( - self, - *, - connection_id: str, - instance_name: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class SearchConfigurationList(_model_base.Model): - """A list of search configurations currently used by the ``bing_custom_search`` tool. - - :ivar search_configurations: The connections attached to this tool. There can be a maximum of 1 - connection - resource attached to the tool. Required. - :vartype search_configurations: list[~azure.ai.projects.models.SearchConfiguration] - """ - - search_configurations: List["_models.SearchConfiguration"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The connections attached to this tool. There can be a maximum of 1 connection - resource attached to the tool. Required.""" - - @overload - def __init__( - self, - *, - search_configurations: List["_models.SearchConfiguration"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param 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 SharepointToolDefinition(ToolDefinition, discriminator="sharepoint_grounding"): - """The input definition information for a sharepoint tool as used to configure an agent. - - :ivar type: The object type, which is always 'sharepoint_grounding'. Required. Default value is - "sharepoint_grounding". - :vartype type: str - :ivar sharepoint_grounding: The list of connections used by the SharePoint tool. Required. - :vartype sharepoint_grounding: ~azure.ai.projects.models.ToolConnectionList - """ - - type: Literal["sharepoint_grounding"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'sharepoint_grounding'. Required. Default value is - \"sharepoint_grounding\".""" - sharepoint_grounding: "_models.ToolConnectionList" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The list of connections used by the SharePoint tool. Required.""" - - @overload - def __init__( - self, - *, - sharepoint_grounding: "_models.ToolConnectionList", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="sharepoint_grounding", **kwargs) - - -class SubmitToolOutputsAction(RequiredAction, discriminator="submit_tool_outputs"): - """The details for required tool calls that must be submitted for an agent thread run to continue. - - :ivar type: The object type, which is always 'submit_tool_outputs'. Required. Default value is - "submit_tool_outputs". - :vartype type: str - :ivar submit_tool_outputs: The details describing tools that should be called to submit tool - outputs. Required. - :vartype submit_tool_outputs: ~azure.ai.projects.models.SubmitToolOutputsDetails - """ - - type: Literal["submit_tool_outputs"] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'submit_tool_outputs'. Required. Default value is - \"submit_tool_outputs\".""" - submit_tool_outputs: "_models.SubmitToolOutputsDetails" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The details describing tools that should be called to submit tool outputs. Required.""" - - @overload - def __init__( - self, - *, - submit_tool_outputs: "_models.SubmitToolOutputsDetails", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type="submit_tool_outputs", **kwargs) - - -class SubmitToolOutputsDetails(_model_base.Model): - """The details describing tools that should be called to submit tool outputs. - - :ivar tool_calls: The list of tool calls that must be resolved for the agent thread run to - continue. Required. - :vartype tool_calls: list[~azure.ai.projects.models.RequiredToolCall] - """ - - tool_calls: List["_models.RequiredToolCall"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The list of tool calls that must be resolved for the agent thread run to continue. Required.""" - - @overload - def __init__( - self, - *, - tool_calls: List["_models.RequiredToolCall"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param 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 SystemData(_model_base.Model): - """Metadata pertaining to creation and last modification of the resource. - - :ivar created_at: The timestamp the resource was created at. - :vartype created_at: ~datetime.datetime - :ivar created_by: The identity that created the resource. - :vartype created_by: str - :ivar created_by_type: The identity type that created the resource. - :vartype created_by_type: str - :ivar last_modified_at: The timestamp of resource last modification (UTC). - :vartype last_modified_at: ~datetime.datetime - """ - - created_at: Optional[datetime.datetime] = rest_field(name="createdAt", visibility=["read"], format="rfc3339") - """The timestamp the resource was created at.""" - created_by: Optional[str] = rest_field(name="createdBy", visibility=["read"]) - """The identity that created the resource.""" - created_by_type: Optional[str] = rest_field(name="createdByType", visibility=["read"]) - """The identity type that created the resource.""" - last_modified_at: Optional[datetime.datetime] = rest_field( - name="lastModifiedAt", visibility=["read"], format="rfc3339" - ) - """The timestamp of resource last modification (UTC).""" - - -class ThreadDeletionStatus(_model_base.Model): - """The status of a thread deletion operation. - - :ivar id: The ID of the resource specified for deletion. Required. - :vartype id: str - :ivar deleted: A value indicating whether deletion was successful. Required. - :vartype deleted: bool - :ivar object: The object type, which is always 'thread.deleted'. Required. Default value is - "thread.deleted". - :vartype object: str - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the resource specified for deletion. Required.""" - deleted: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A value indicating whether deletion was successful. Required.""" - object: Literal["thread.deleted"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always 'thread.deleted'. Required. Default value is - \"thread.deleted\".""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - 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) - self.object: Literal["thread.deleted"] = "thread.deleted" - - -class ThreadMessage(_model_base.Model): - """A single, existing message within an agent thread. - - :ivar id: The identifier, which can be referenced in API endpoints. Required. - :vartype id: str - :ivar object: The object type, which is always 'thread.message'. Required. Default value is - "thread.message". - :vartype object: str - :ivar created_at: The Unix timestamp, in seconds, representing when this object was created. - Required. - :vartype created_at: ~datetime.datetime - :ivar thread_id: The ID of the thread that this message belongs to. Required. - :vartype thread_id: str - :ivar status: The status of the message. Required. Known values are: "in_progress", - "incomplete", and "completed". - :vartype status: str or ~azure.ai.projects.models.MessageStatus - :ivar incomplete_details: On an incomplete message, details about why the message is - incomplete. Required. - :vartype incomplete_details: ~azure.ai.projects.models.MessageIncompleteDetails - :ivar completed_at: The Unix timestamp (in seconds) for when the message was completed. - Required. - :vartype completed_at: ~datetime.datetime - :ivar incomplete_at: The Unix timestamp (in seconds) for when the message was marked as - incomplete. Required. - :vartype incomplete_at: ~datetime.datetime - :ivar role: The role associated with the agent thread message. Required. Known values are: - "user" and "assistant". - :vartype role: str or ~azure.ai.projects.models.MessageRole - :ivar content: The list of content items associated with the agent thread message. Required. - :vartype content: list[~azure.ai.projects.models.MessageContent] - :ivar agent_id: If applicable, the ID of the agent that authored this message. Required. - :vartype agent_id: str - :ivar run_id: If applicable, the ID of the run associated with the authoring of this message. - Required. - :vartype run_id: str - :ivar attachments: A list of files attached to the message, and the tools they were added to. - Required. - :vartype attachments: list[~azure.ai.projects.models.MessageAttachment] - :ivar metadata: A set of up to 16 key/value pairs that can be attached to an object, used for - storing additional information about that object in a structured format. Keys may be up to 64 - characters in length and values may be up to 512 characters in length. Required. - :vartype metadata: dict[str, str] - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The identifier, which can be referenced in API endpoints. Required.""" - object: Literal["thread.message"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always 'thread.message'. Required. Default value is - \"thread.message\".""" - created_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp, in seconds, representing when this object was created. Required.""" - thread_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the thread that this message belongs to. Required.""" - status: Union[str, "_models.MessageStatus"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The status of the message. Required. Known values are: \"in_progress\", \"incomplete\", and - \"completed\".""" - incomplete_details: "_models.MessageIncompleteDetails" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """On an incomplete message, details about why the message is incomplete. Required.""" - completed_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp (in seconds) for when the message was completed. Required.""" - incomplete_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp (in seconds) for when the message was marked as incomplete. Required.""" - role: Union[str, "_models.MessageRole"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The role associated with the agent thread message. Required. Known values are: \"user\" and - \"assistant\".""" - content: List["_models.MessageContent"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The list of content items associated with the agent thread message. Required.""" - agent_id: str = rest_field(name="assistant_id", visibility=["read", "create", "update", "delete", "query"]) - """If applicable, the ID of the agent that authored this message. Required.""" - run_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """If applicable, the ID of the run associated with the authoring of this message. Required.""" - attachments: List["_models.MessageAttachment"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """A list of files attached to the message, and the tools they were added to. Required.""" - metadata: Dict[str, str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A set of up to 16 key/value pairs that can be attached to an object, used for storing - additional information about that object in a structured format. Keys may be up to 64 - characters in length and values may be up to 512 characters in length. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - created_at: datetime.datetime, - thread_id: str, - status: Union[str, "_models.MessageStatus"], - incomplete_details: "_models.MessageIncompleteDetails", - completed_at: datetime.datetime, - incomplete_at: datetime.datetime, - role: Union[str, "_models.MessageRole"], - content: List["_models.MessageContent"], - agent_id: str, - run_id: str, - attachments: List["_models.MessageAttachment"], - metadata: Dict[str, 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.object: Literal["thread.message"] = "thread.message" - - -class ThreadMessageOptions(_model_base.Model): - """A single message within an agent thread, - as provided during that thread's creation for its initial state. - - :ivar role: The role of the entity that is creating the message. Allowed values include: - ``user``, which indicates the message is sent by an actual user (and should be - used in most cases to represent user-generated messages), and ``assistant``, - which indicates the message is generated by the agent (use this value to insert - messages from the agent into the conversation). Required. Known values are: "user" and - "assistant". - :vartype role: str or ~azure.ai.projects.models.MessageRole - :ivar content: The content of the initial message. This may be a basic string (if you only - need text) or an array of typed content blocks (for example, text, image_file, - image_url, and so on). Required. Is either a str type or a [MessageInputContentBlock] type. - :vartype content: str or list[~azure.ai.projects.models.MessageInputContentBlock] - :ivar attachments: A list of files attached to the message, and the tools they should be added - to. - :vartype attachments: list[~azure.ai.projects.models.MessageAttachment] - :ivar metadata: A set of up to 16 key/value pairs that can be attached to an object, used for - storing additional information about that object in a structured format. Keys may be up to 64 - characters in length and values may be up to 512 characters in length. - :vartype metadata: dict[str, str] - """ - - role: Union[str, "_models.MessageRole"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The role of the entity that is creating the message. Allowed values include: - ``user``, which indicates the message is sent by an actual user (and should be - used in most cases to represent user-generated messages), and ``assistant``, - which indicates the message is generated by the agent (use this value to insert - messages from the agent into the conversation). Required. Known values are: \"user\" and - \"assistant\".""" - content: "_types.MessageInputContent" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The content of the initial message. This may be a basic string (if you only - need text) or an array of typed content blocks (for example, text, image_file, - image_url, and so on). Required. Is either a str type or a [MessageInputContentBlock] type.""" - attachments: Optional[List["_models.MessageAttachment"]] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """A list of files attached to the message, and the tools they should be added to.""" - metadata: Optional[Dict[str, str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A set of up to 16 key/value pairs that can be attached to an object, used for storing - additional information about that object in a structured format. Keys may be up to 64 - characters in length and values may be up to 512 characters in length.""" - - @overload - def __init__( - self, - *, - role: Union[str, "_models.MessageRole"], - content: "_types.MessageInputContent", - attachments: Optional[List["_models.MessageAttachment"]] = 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 ThreadRun(_model_base.Model): - """Data representing a single evaluation run of an agent thread. - - :ivar id: The identifier, which can be referenced in API endpoints. Required. - :vartype id: str - :ivar object: The object type, which is always 'thread.run'. Required. Default value is - "thread.run". - :vartype object: str - :ivar thread_id: The ID of the thread associated with this run. Required. - :vartype thread_id: str - :ivar agent_id: The ID of the agent associated with the thread this run was performed against. - Required. - :vartype agent_id: str - :ivar status: The status of the agent thread run. Required. Known values are: "queued", - "in_progress", "requires_action", "cancelling", "cancelled", "failed", "completed", and - "expired". - :vartype status: str or ~azure.ai.projects.models.RunStatus - :ivar required_action: The details of the action required for the agent thread run to continue. - :vartype required_action: ~azure.ai.projects.models.RequiredAction - :ivar last_error: The last error, if any, encountered by this agent thread run. Required. - :vartype last_error: ~azure.ai.projects.models.RunError - :ivar model: The ID of the model to use. Required. - :vartype model: str - :ivar instructions: The overridden system instructions used for this agent thread run. - Required. - :vartype instructions: str - :ivar tools: The overridden enabled tools used for this agent thread run. Required. - :vartype tools: list[~azure.ai.projects.models.ToolDefinition] - :ivar created_at: The Unix timestamp, in seconds, representing when this object was created. - Required. - :vartype created_at: ~datetime.datetime - :ivar expires_at: The Unix timestamp, in seconds, representing when this item expires. - Required. - :vartype expires_at: ~datetime.datetime - :ivar started_at: The Unix timestamp, in seconds, representing when this item was started. - Required. - :vartype started_at: ~datetime.datetime - :ivar completed_at: The Unix timestamp, in seconds, representing when this completed. Required. - :vartype completed_at: ~datetime.datetime - :ivar cancelled_at: The Unix timestamp, in seconds, representing when this was cancelled. - Required. - :vartype cancelled_at: ~datetime.datetime - :ivar failed_at: The Unix timestamp, in seconds, representing when this failed. Required. - :vartype failed_at: ~datetime.datetime - :ivar incomplete_details: Details on why the run is incomplete. Will be ``null`` if the run is - not incomplete. Required. - :vartype incomplete_details: ~azure.ai.projects.models.IncompleteRunDetails - :ivar usage: Usage statistics related to the run. This value will be ``null`` if the run is not - in a terminal state (i.e. ``in_progress``, ``queued``, etc.). Required. - :vartype usage: ~azure.ai.projects.models.RunCompletionUsage - :ivar temperature: The sampling temperature used for this run. If not set, defaults to 1. - :vartype temperature: float - :ivar top_p: The nucleus sampling value used for this run. If not set, defaults to 1. - :vartype top_p: float - :ivar max_prompt_tokens: The maximum number of prompt tokens specified to have been used over - the course of the run. Required. - :vartype max_prompt_tokens: int - :ivar max_completion_tokens: The maximum number of completion tokens specified to have been - used over the course of the run. Required. - :vartype max_completion_tokens: int - :ivar truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Required. - :vartype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :ivar tool_choice: Controls whether or not and which tool is called by the model. Required. Is - one of the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice - :vartype tool_choice: str or str or ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode or - ~azure.ai.projects.models.AgentsNamedToolChoice - :ivar response_format: The response format of the tool calls used in this run. Required. Is one - of the following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat, ResponseFormatJsonSchemaType - :vartype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat or - ~azure.ai.projects.models.ResponseFormatJsonSchemaType - :ivar metadata: A set of up to 16 key/value pairs that can be attached to an object, used for - storing additional information about that object in a structured format. Keys may be up to 64 - characters in length and values may be up to 512 characters in length. Required. - :vartype metadata: dict[str, str] - :ivar tool_resources: Override the tools the agent can use for this run. This is useful for - modifying the behavior on a per-run basis. - :vartype tool_resources: ~azure.ai.projects.models.UpdateToolResourcesOptions - :ivar parallel_tool_calls: Determines if tools can be executed in parallel within the run. - Required. - :vartype parallel_tool_calls: bool - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The identifier, which can be referenced in API endpoints. Required.""" - object: Literal["thread.run"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always 'thread.run'. Required. Default value is \"thread.run\".""" - thread_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the thread associated with this run. Required.""" - agent_id: str = rest_field(name="assistant_id", visibility=["read", "create", "update", "delete", "query"]) - """The ID of the agent associated with the thread this run was performed against. Required.""" - status: Union[str, "_models.RunStatus"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The status of the agent thread run. Required. Known values are: \"queued\", \"in_progress\", - \"requires_action\", \"cancelling\", \"cancelled\", \"failed\", \"completed\", and \"expired\".""" - required_action: Optional["_models.RequiredAction"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The details of the action required for the agent thread run to continue.""" - last_error: "_models.RunError" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The last error, if any, encountered by this agent thread run. Required.""" - model: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the model to use. Required.""" - instructions: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The overridden system instructions used for this agent thread run. Required.""" - tools: List["_models.ToolDefinition"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The overridden enabled tools used for this agent thread run. Required.""" - created_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp, in seconds, representing when this object was created. Required.""" - expires_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp, in seconds, representing when this item expires. Required.""" - started_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp, in seconds, representing when this item was started. Required.""" - completed_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp, in seconds, representing when this completed. Required.""" - cancelled_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp, in seconds, representing when this was cancelled. Required.""" - failed_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp, in seconds, representing when this failed. Required.""" - incomplete_details: "_models.IncompleteRunDetails" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Details on why the run is incomplete. Will be ``null`` if the run is not incomplete. Required.""" - usage: "_models.RunCompletionUsage" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Usage statistics related to the run. This value will be ``null`` if the run is not in a - terminal state (i.e. ``in_progress``, ``queued``, etc.). Required.""" - temperature: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The sampling temperature used for this run. If not set, defaults to 1.""" - top_p: Optional[float] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The nucleus sampling value used for this run. If not set, defaults to 1.""" - max_prompt_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The maximum number of prompt tokens specified to have been used over the course of the run. - Required.""" - max_completion_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The maximum number of completion tokens specified to have been used over the course of the run. - Required.""" - truncation_strategy: "_models.TruncationObject" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The strategy to use for dropping messages as the context windows moves forward. Required.""" - tool_choice: "_types.AgentsApiToolChoiceOption" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Controls whether or not and which tool is called by the model. Required. Is one of the - following types: str, Union[str, \"_models.AgentsApiToolChoiceOptionMode\"], - AgentsNamedToolChoice""" - response_format: "_types.AgentsApiResponseFormatOption" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The response format of the tool calls used in this run. Required. Is one of the following - types: str, Union[str, \"_models.AgentsApiResponseFormatMode\"], AgentsApiResponseFormat, - ResponseFormatJsonSchemaType""" - metadata: Dict[str, str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A set of up to 16 key/value pairs that can be attached to an object, used for storing - additional information about that object in a structured format. Keys may be up to 64 - characters in length and values may be up to 512 characters in length. Required.""" - tool_resources: Optional["_models.UpdateToolResourcesOptions"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Override the tools the agent can use for this run. This is useful for modifying the behavior on - a per-run basis.""" - parallel_tool_calls: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Determines if tools can be executed in parallel within the run. Required.""" - - @overload - def __init__( # pylint: disable=too-many-locals - self, - *, - id: str, # pylint: disable=redefined-builtin - thread_id: str, - agent_id: str, - status: Union[str, "_models.RunStatus"], - last_error: "_models.RunError", - model: str, - instructions: str, - tools: List["_models.ToolDefinition"], - created_at: datetime.datetime, - expires_at: datetime.datetime, - started_at: datetime.datetime, - completed_at: datetime.datetime, - cancelled_at: datetime.datetime, - failed_at: datetime.datetime, - incomplete_details: "_models.IncompleteRunDetails", - usage: "_models.RunCompletionUsage", - max_prompt_tokens: int, - max_completion_tokens: int, - truncation_strategy: "_models.TruncationObject", - tool_choice: "_types.AgentsApiToolChoiceOption", - response_format: "_types.AgentsApiResponseFormatOption", - metadata: Dict[str, str], - parallel_tool_calls: bool, - required_action: Optional["_models.RequiredAction"] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - tool_resources: Optional["_models.UpdateToolResourcesOptions"] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.object: Literal["thread.run"] = "thread.run" - - -class ToolConnection(_model_base.Model): - """A connection resource. - - :ivar connection_id: A connection in a ToolConnectionList attached to this tool. Required. - :vartype connection_id: str - """ - - connection_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A connection in a ToolConnectionList attached to this tool. Required.""" - - @overload - def __init__( - self, - *, - connection_id: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ToolConnectionList(_model_base.Model): - """A set of connection resources currently used by either the ``bing_grounding``, - ``fabric_dataagent``, or ``sharepoint_grounding`` tools. - - :ivar connection_list: The connections attached to this tool. There can be a maximum of 1 - connection - resource attached to the tool. - :vartype connection_list: list[~azure.ai.projects.models.ToolConnection] - """ - - connection_list: Optional[List["_models.ToolConnection"]] = rest_field( - name="connections", visibility=["read", "create", "update", "delete", "query"] - ) - """The connections attached to this tool. There can be a maximum of 1 connection - resource attached to the tool.""" - - @overload - def __init__( - self, - *, - connection_list: Optional[List["_models.ToolConnection"]] = 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 ToolOutput(_model_base.Model): - """The data provided during a tool outputs submission to resolve pending tool calls and allow the - model to continue. - - :ivar tool_call_id: The ID of the tool call being resolved, as provided in the tool calls of a - required action from a run. - :vartype tool_call_id: str - :ivar output: The output from the tool to be submitted. - :vartype output: str - """ - - tool_call_id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the tool call being resolved, as provided in the tool calls of a required action from - a run.""" - output: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The output from the tool to be submitted.""" - - @overload - def __init__( - self, - *, - tool_call_id: Optional[str] = None, - output: Optional[str] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class ToolResources(_model_base.Model): - """A set of resources that are used by the agent's tools. The resources are specific to the type - of - tool. For example, the ``code_interpreter`` tool requires a list of file IDs, while the - ``file_search`` - tool requires a list of vector store IDs. - - :ivar code_interpreter: Resources to be used by the ``code_interpreter`` tool consisting of - file IDs. - :vartype code_interpreter: ~azure.ai.projects.models.CodeInterpreterToolResource - :ivar file_search: Resources to be used by the ``file_search`` tool consisting of vector store - IDs. - :vartype file_search: ~azure.ai.projects.models.FileSearchToolResource - :ivar azure_ai_search: Resources to be used by the ``azure_ai_search`` tool consisting of index - IDs and names. - :vartype azure_ai_search: ~azure.ai.projects.models.AzureAISearchResource - """ - - code_interpreter: Optional["_models.CodeInterpreterToolResource"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Resources to be used by the ``code_interpreter`` tool consisting of file IDs.""" - file_search: Optional["_models.FileSearchToolResource"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Resources to be used by the ``file_search`` tool consisting of vector store IDs.""" - azure_ai_search: Optional["_models.AzureAISearchResource"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Resources to be used by the ``azure_ai_search`` tool consisting of index IDs and names.""" - - @overload - def __init__( - self, - *, - code_interpreter: Optional["_models.CodeInterpreterToolResource"] = None, - file_search: Optional["_models.FileSearchToolResource"] = None, - azure_ai_search: Optional["_models.AzureAISearchResource"] = 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 TruncationObject(_model_base.Model): - """Controls for how a thread will be truncated prior to the run. Use this to control the initial - context window of the run. - - :ivar type: The truncation strategy to use for the thread. The default is ``auto``. If set to - ``last_messages``, the thread will - be truncated to the ``lastMessages`` count most recent messages in the thread. When set to - ``auto``, messages in the middle of the thread - will be dropped to fit the context length of the model, ``max_prompt_tokens``. Required. Known - values are: "auto" and "last_messages". - :vartype type: str or ~azure.ai.projects.models.TruncationStrategy - :ivar last_messages: The number of most recent messages from the thread when constructing the - context for the run. - :vartype last_messages: int - """ - - type: Union[str, "_models.TruncationStrategy"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The truncation strategy to use for the thread. The default is ``auto``. If set to - ``last_messages``, the thread will - be truncated to the ``lastMessages`` count most recent messages in the thread. When set to - ``auto``, messages in the middle of the thread - will be dropped to fit the context length of the model, ``max_prompt_tokens``. Required. Known - values are: \"auto\" and \"last_messages\".""" - last_messages: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The number of most recent messages from the thread when constructing the context for the run.""" - - @overload - def __init__( - self, - *, - type: Union[str, "_models.TruncationStrategy"], - last_messages: 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 UpdateCodeInterpreterToolResourceOptions(_model_base.Model): - """Request object to update ``code_interpreted`` tool resources. - - :ivar file_ids: A list of file IDs to override the current list of the agent. - :vartype file_ids: list[str] - """ - - file_ids: Optional[List[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A list of file IDs to override the current list of the agent.""" - - @overload - def __init__( - self, - *, - file_ids: Optional[List[str]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class UpdateFileSearchToolResourceOptions(_model_base.Model): - """Request object to update ``file_search`` tool resources. - - :ivar vector_store_ids: A list of vector store IDs to override the current list of the agent. - :vartype vector_store_ids: list[str] - """ - - vector_store_ids: Optional[List[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A list of vector store IDs to override the current list of the agent.""" - - @overload - def __init__( - self, - *, - vector_store_ids: Optional[List[str]] = None, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class UpdateToolResourcesOptions(_model_base.Model): - """Request object. A set of resources that are used by the agent's tools. The resources are - specific to the type of tool. - For example, the ``code_interpreter`` tool requires a list of file IDs, while the - ``file_search`` tool requires a list of - vector store IDs. - - :ivar code_interpreter: Overrides the list of file IDs made available to the - ``code_interpreter`` tool. There can be a maximum of 20 files - associated with the tool. - :vartype code_interpreter: ~azure.ai.projects.models.UpdateCodeInterpreterToolResourceOptions - :ivar file_search: Overrides the vector store attached to this agent. There can be a maximum of - 1 vector store attached to the agent. - :vartype file_search: ~azure.ai.projects.models.UpdateFileSearchToolResourceOptions - :ivar azure_ai_search: Overrides the resources to be used by the ``azure_ai_search`` tool - consisting of index IDs and names. - :vartype azure_ai_search: ~azure.ai.projects.models.AzureAISearchResource - """ - - code_interpreter: Optional["_models.UpdateCodeInterpreterToolResourceOptions"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Overrides the list of file IDs made available to the ``code_interpreter`` tool. There can be a - maximum of 20 files - associated with the tool.""" - file_search: Optional["_models.UpdateFileSearchToolResourceOptions"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Overrides the vector store attached to this agent. There can be a maximum of 1 vector store - attached to the agent.""" - azure_ai_search: Optional["_models.AzureAISearchResource"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Overrides the resources to be used by the ``azure_ai_search`` tool consisting of index IDs and - names.""" - - @overload - def __init__( - self, - *, - code_interpreter: Optional["_models.UpdateCodeInterpreterToolResourceOptions"] = None, - file_search: Optional["_models.UpdateFileSearchToolResourceOptions"] = None, - azure_ai_search: Optional["_models.AzureAISearchResource"] = 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 UploadFileRequest(_model_base.Model): - """UploadFileRequest. - - :ivar file: The file data, in bytes. Required. - :vartype file: ~azure.ai.projects._vendor.FileType - :ivar purpose: The intended purpose of the uploaded file. Use ``assistants`` for Agents and - Message files, ``vision`` for Agents image file inputs, ``batch`` for Batch API, and - ``fine-tune`` for Fine-tuning. Required. Known values are: "fine-tune", "fine-tune-results", - "assistants", "assistants_output", "batch", "batch_output", and "vision". - :vartype purpose: str or ~azure.ai.projects.models.FilePurpose - :ivar filename: The name of the file. - :vartype filename: str - """ - - file: FileType = rest_field( - visibility=["read", "create", "update", "delete", "query"], is_multipart_file_input=True - ) - """The file data, in bytes. Required.""" - purpose: Union[str, "_models.FilePurpose"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The intended purpose of the uploaded file. Use ``assistants`` for Agents and Message files, - ``vision`` for Agents image file inputs, ``batch`` for Batch API, and ``fine-tune`` for - Fine-tuning. Required. Known values are: \"fine-tune\", \"fine-tune-results\", \"assistants\", - \"assistants_output\", \"batch\", \"batch_output\", and \"vision\".""" - filename: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the file.""" - - @overload - def __init__( - self, - *, - file: FileType, - purpose: Union[str, "_models.FilePurpose"], - filename: 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 VectorStore(_model_base.Model): - """A vector store is a collection of processed files can be used by the ``file_search`` tool. - - :ivar id: The identifier, which can be referenced in API endpoints. Required. - :vartype id: str - :ivar object: The object type, which is always ``vector_store``. Required. Default value is - "vector_store". - :vartype object: str - :ivar created_at: The Unix timestamp (in seconds) for when the vector store was created. - Required. - :vartype created_at: ~datetime.datetime - :ivar name: The name of the vector store. Required. - :vartype name: str - :ivar usage_bytes: The total number of bytes used by the files in the vector store. Required. - :vartype usage_bytes: int - :ivar file_counts: Files count grouped by status processed or being processed by this vector - store. Required. - :vartype file_counts: ~azure.ai.projects.models.VectorStoreFileCount - :ivar status: The status of the vector store, which can be either ``expired``, ``in_progress``, - or ``completed``. A status of ``completed`` indicates that the vector store is ready for use. - Required. Known values are: "expired", "in_progress", and "completed". - :vartype status: str or ~azure.ai.projects.models.VectorStoreStatus - :ivar expires_after: Details on when this vector store expires. - :vartype expires_after: ~azure.ai.projects.models.VectorStoreExpirationPolicy - :ivar expires_at: The Unix timestamp (in seconds) for when the vector store will expire. - :vartype expires_at: ~datetime.datetime - :ivar last_active_at: The Unix timestamp (in seconds) for when the vector store was last - active. Required. - :vartype last_active_at: ~datetime.datetime - :ivar metadata: A set of up to 16 key/value pairs that can be attached to an object, used for - storing additional information about that object in a structured format. Keys may be up to 64 - characters in length and values may be up to 512 characters in length. Required. - :vartype metadata: dict[str, str] - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The identifier, which can be referenced in API endpoints. Required.""" - object: Literal["vector_store"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always ``vector_store``. Required. Default value is \"vector_store\".""" - created_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp (in seconds) for when the vector store was created. Required.""" - name: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The name of the vector store. Required.""" - usage_bytes: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The total number of bytes used by the files in the vector store. Required.""" - file_counts: "_models.VectorStoreFileCount" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Files count grouped by status processed or being processed by this vector store. Required.""" - status: Union[str, "_models.VectorStoreStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the vector store, which can be either ``expired``, ``in_progress``, or - ``completed``. A status of ``completed`` indicates that the vector store is ready for use. - Required. Known values are: \"expired\", \"in_progress\", and \"completed\".""" - expires_after: Optional["_models.VectorStoreExpirationPolicy"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Details on when this vector store expires.""" - expires_at: Optional[datetime.datetime] = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp (in seconds) for when the vector store will expire.""" - last_active_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp (in seconds) for when the vector store was last active. Required.""" - metadata: Dict[str, str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A set of up to 16 key/value pairs that can be attached to an object, used for storing - additional information about that object in a structured format. Keys may be up to 64 - characters in length and values may be up to 512 characters in length. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - created_at: datetime.datetime, - name: str, - usage_bytes: int, - file_counts: "_models.VectorStoreFileCount", - status: Union[str, "_models.VectorStoreStatus"], - last_active_at: datetime.datetime, - metadata: Dict[str, str], - expires_after: Optional["_models.VectorStoreExpirationPolicy"] = None, - expires_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) - self.object: Literal["vector_store"] = "vector_store" - - -class VectorStoreChunkingStrategyRequest(_model_base.Model): - """An abstract representation of a vector store chunking strategy configuration. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - VectorStoreAutoChunkingStrategyRequest, VectorStoreStaticChunkingStrategyRequest - - :ivar type: The object type. Required. Known values are: "auto" and "static". - :vartype type: str or ~azure.ai.projects.models.VectorStoreChunkingStrategyRequestType - """ - - __mapping__: Dict[str, _model_base.Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The object type. Required. Known values are: \"auto\" and \"static\".""" - - @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 VectorStoreAutoChunkingStrategyRequest(VectorStoreChunkingStrategyRequest, discriminator="auto"): - """The default strategy. This strategy currently uses a max_chunk_size_tokens of 800 and - chunk_overlap_tokens of 400. - - :ivar type: The object type, which is always 'auto'. Required. - :vartype type: str or ~azure.ai.projects.models.AUTO - """ - - type: Literal[VectorStoreChunkingStrategyRequestType.AUTO] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'auto'. Required.""" - - @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, type=VectorStoreChunkingStrategyRequestType.AUTO, **kwargs) - - -class VectorStoreChunkingStrategyResponse(_model_base.Model): - """An abstract representation of a vector store chunking strategy configuration. - - You probably want to use the sub-classes and not this class directly. Known sub-classes are: - VectorStoreAutoChunkingStrategyResponse, VectorStoreStaticChunkingStrategyResponse - - :ivar type: The object type. Required. Known values are: "other" and "static". - :vartype type: str or ~azure.ai.projects.models.VectorStoreChunkingStrategyResponseType - """ - - __mapping__: Dict[str, _model_base.Model] = {} - type: str = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) - """The object type. Required. Known values are: \"other\" and \"static\".""" - - @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 VectorStoreAutoChunkingStrategyResponse(VectorStoreChunkingStrategyResponse, discriminator="other"): - """This is returned when the chunking strategy is unknown. Typically, this is because the file was - indexed before the chunking_strategy concept was introduced in the API. - - :ivar type: The object type, which is always 'other'. Required. - :vartype type: str or ~azure.ai.projects.models.OTHER - """ - - type: Literal[VectorStoreChunkingStrategyResponseType.OTHER] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'other'. Required.""" - - @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, type=VectorStoreChunkingStrategyResponseType.OTHER, **kwargs) - - -class VectorStoreConfiguration(_model_base.Model): - """Vector storage configuration is the list of data sources, used when multiple - files can be used for the enterprise file search. - - :ivar data_sources: Data sources. Required. - :vartype data_sources: list[~azure.ai.projects.models.VectorStoreDataSource] - """ - - data_sources: List["_models.VectorStoreDataSource"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Data sources. Required.""" - - @overload - def __init__( - self, - *, - data_sources: List["_models.VectorStoreDataSource"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param 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 VectorStoreConfigurations(_model_base.Model): - """The structure, containing the list of vector storage configurations i.e. the list of azure - asset IDs. - - :ivar store_name: Name. Required. - :vartype store_name: str - :ivar store_configuration: Configurations. Required. - :vartype store_configuration: ~azure.ai.projects.models.VectorStoreConfiguration - """ - - store_name: str = rest_field(name="name", visibility=["read", "create", "update", "delete", "query"]) - """Name. Required.""" - store_configuration: "_models.VectorStoreConfiguration" = rest_field( - name="configuration", visibility=["read", "create", "update", "delete", "query"] - ) - """Configurations. Required.""" - - @overload - def __init__( - self, - *, - store_name: str, - store_configuration: "_models.VectorStoreConfiguration", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param 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 VectorStoreDataSource(_model_base.Model): - """The structure, containing Azure asset URI path and the asset type of the file used as a data - source - for the enterprise file search. - - :ivar asset_identifier: Asset URI. Required. - :vartype asset_identifier: str - :ivar asset_type: The asset type. Required. Known values are: "uri_asset" and "id_asset". - :vartype asset_type: str or ~azure.ai.projects.models.VectorStoreDataSourceAssetType - """ - - asset_identifier: str = rest_field(name="uri", visibility=["read", "create", "update", "delete", "query"]) - """Asset URI. Required.""" - asset_type: Union[str, "_models.VectorStoreDataSourceAssetType"] = rest_field( - name="type", visibility=["read", "create", "update", "delete", "query"] - ) - """The asset type. Required. Known values are: \"uri_asset\" and \"id_asset\".""" - - @overload - def __init__( - self, - *, - asset_identifier: str, - asset_type: Union[str, "_models.VectorStoreDataSourceAssetType"], - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param 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 VectorStoreDeletionStatus(_model_base.Model): - """Response object for deleting a vector store. - - :ivar id: The ID of the resource specified for deletion. Required. - :vartype id: str - :ivar deleted: A value indicating whether deletion was successful. Required. - :vartype deleted: bool - :ivar object: The object type, which is always 'vector_store.deleted'. Required. Default value - is "vector_store.deleted". - :vartype object: str - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the resource specified for deletion. Required.""" - deleted: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A value indicating whether deletion was successful. Required.""" - object: Literal["vector_store.deleted"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always 'vector_store.deleted'. Required. Default value is - \"vector_store.deleted\".""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - 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) - self.object: Literal["vector_store.deleted"] = "vector_store.deleted" - - -class VectorStoreExpirationPolicy(_model_base.Model): - """The expiration policy for a vector store. - - :ivar anchor: Anchor timestamp after which the expiration policy applies. Supported anchors: - ``last_active_at``. Required. "last_active_at" - :vartype anchor: str or ~azure.ai.projects.models.VectorStoreExpirationPolicyAnchor - :ivar days: The anchor timestamp after which the expiration policy applies. Required. - :vartype days: int - """ - - anchor: Union[str, "_models.VectorStoreExpirationPolicyAnchor"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """Anchor timestamp after which the expiration policy applies. Supported anchors: - ``last_active_at``. Required. \"last_active_at\"""" - days: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The anchor timestamp after which the expiration policy applies. Required.""" - - @overload - def __init__( - self, - *, - anchor: Union[str, "_models.VectorStoreExpirationPolicyAnchor"], - days: 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 VectorStoreFile(_model_base.Model): - """Description of a file attached to a vector store. - - :ivar id: The identifier, which can be referenced in API endpoints. Required. - :vartype id: str - :ivar object: The object type, which is always ``vector_store.file``. Required. Default value - is "vector_store.file". - :vartype object: str - :ivar usage_bytes: The total vector store usage in bytes. Note that this may be different from - the original file - size. Required. - :vartype usage_bytes: int - :ivar created_at: The Unix timestamp (in seconds) for when the vector store file was created. - Required. - :vartype created_at: ~datetime.datetime - :ivar vector_store_id: The ID of the vector store that the file is attached to. Required. - :vartype vector_store_id: str - :ivar status: The status of the vector store file, which can be either ``in_progress``, - ``completed``, ``cancelled``, or ``failed``. The status ``completed`` indicates that the vector - store file is ready for use. Required. Known values are: "in_progress", "completed", "failed", - and "cancelled". - :vartype status: str or ~azure.ai.projects.models.VectorStoreFileStatus - :ivar last_error: The last error associated with this vector store file. Will be ``null`` if - there are no errors. Required. - :vartype last_error: ~azure.ai.projects.models.VectorStoreFileError - :ivar chunking_strategy: The strategy used to chunk the file. Required. - :vartype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyResponse - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The identifier, which can be referenced in API endpoints. Required.""" - object: Literal["vector_store.file"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always ``vector_store.file``. Required. Default value is - \"vector_store.file\".""" - usage_bytes: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The total vector store usage in bytes. Note that this may be different from the original file - size. Required.""" - created_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp (in seconds) for when the vector store file was created. Required.""" - vector_store_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the vector store that the file is attached to. Required.""" - status: Union[str, "_models.VectorStoreFileStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the vector store file, which can be either ``in_progress``, ``completed``, - ``cancelled``, or ``failed``. The status ``completed`` indicates that the vector store file is - ready for use. Required. Known values are: \"in_progress\", \"completed\", \"failed\", and - \"cancelled\".""" - last_error: "_models.VectorStoreFileError" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The last error associated with this vector store file. Will be ``null`` if there are no errors. - Required.""" - chunking_strategy: "_models.VectorStoreChunkingStrategyResponse" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The strategy used to chunk the file. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - usage_bytes: int, - created_at: datetime.datetime, - vector_store_id: str, - status: Union[str, "_models.VectorStoreFileStatus"], - last_error: "_models.VectorStoreFileError", - chunking_strategy: "_models.VectorStoreChunkingStrategyResponse", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.object: Literal["vector_store.file"] = "vector_store.file" - - -class VectorStoreFileBatch(_model_base.Model): - """A batch of files attached to a vector store. - - :ivar id: The identifier, which can be referenced in API endpoints. Required. - :vartype id: str - :ivar object: The object type, which is always ``vector_store.file_batch``. Required. Default - value is "vector_store.files_batch". - :vartype object: str - :ivar created_at: The Unix timestamp (in seconds) for when the vector store files batch was - created. Required. - :vartype created_at: ~datetime.datetime - :ivar vector_store_id: The ID of the vector store that the file is attached to. Required. - :vartype vector_store_id: str - :ivar status: The status of the vector store files batch, which can be either ``in_progress``, - ``completed``, ``cancelled`` or ``failed``. Required. Known values are: "in_progress", - "completed", "cancelled", and "failed". - :vartype status: str or ~azure.ai.projects.models.VectorStoreFileBatchStatus - :ivar file_counts: Files count grouped by status processed or being processed by this vector - store. Required. - :vartype file_counts: ~azure.ai.projects.models.VectorStoreFileCount - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The identifier, which can be referenced in API endpoints. Required.""" - object: Literal["vector_store.files_batch"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The object type, which is always ``vector_store.file_batch``. Required. Default value is - \"vector_store.files_batch\".""" - created_at: datetime.datetime = rest_field( - visibility=["read", "create", "update", "delete", "query"], format="unix-timestamp" - ) - """The Unix timestamp (in seconds) for when the vector store files batch was created. Required.""" - vector_store_id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the vector store that the file is attached to. Required.""" - status: Union[str, "_models.VectorStoreFileBatchStatus"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The status of the vector store files batch, which can be either ``in_progress``, ``completed``, - ``cancelled`` or ``failed``. Required. Known values are: \"in_progress\", \"completed\", - \"cancelled\", and \"failed\".""" - file_counts: "_models.VectorStoreFileCount" = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """Files count grouped by status processed or being processed by this vector store. Required.""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - created_at: datetime.datetime, - vector_store_id: str, - status: Union[str, "_models.VectorStoreFileBatchStatus"], - file_counts: "_models.VectorStoreFileCount", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - self.object: Literal["vector_store.files_batch"] = "vector_store.files_batch" - - -class VectorStoreFileCount(_model_base.Model): - """Counts of files processed or being processed by this vector store grouped by status. - - :ivar in_progress: The number of files that are currently being processed. Required. - :vartype in_progress: int - :ivar completed: The number of files that have been successfully processed. Required. - :vartype completed: int - :ivar failed: The number of files that have failed to process. Required. - :vartype failed: int - :ivar cancelled: The number of files that were cancelled. Required. - :vartype cancelled: int - :ivar total: The total number of files. Required. - :vartype total: int - """ - - in_progress: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The number of files that are currently being processed. Required.""" - completed: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The number of files that have been successfully processed. Required.""" - failed: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The number of files that have failed to process. Required.""" - cancelled: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The number of files that were cancelled. Required.""" - total: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The total number of files. Required.""" - - @overload - def __init__( - self, - *, - in_progress: int, - completed: int, - failed: int, - cancelled: int, - total: 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 VectorStoreFileDeletionStatus(_model_base.Model): - """Response object for deleting a vector store file relationship. - - :ivar id: The ID of the resource specified for deletion. Required. - :vartype id: str - :ivar deleted: A value indicating whether deletion was successful. Required. - :vartype deleted: bool - :ivar object: The object type, which is always 'vector_store.deleted'. Required. Default value - is "vector_store.file.deleted". - :vartype object: str - """ - - id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The ID of the resource specified for deletion. Required.""" - deleted: bool = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A value indicating whether deletion was successful. Required.""" - object: Literal["vector_store.file.deleted"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The object type, which is always 'vector_store.deleted'. Required. Default value is - \"vector_store.file.deleted\".""" - - @overload - def __init__( - self, - *, - id: str, # pylint: disable=redefined-builtin - 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) - self.object: Literal["vector_store.file.deleted"] = "vector_store.file.deleted" - - -class VectorStoreFileError(_model_base.Model): - """Details on the error that may have occurred while processing a file for this vector store. - - :ivar code: One of ``server_error`` or ``rate_limit_exceeded``. Required. Known values are: - "server_error", "invalid_file", and "unsupported_file". - :vartype code: str or ~azure.ai.projects.models.VectorStoreFileErrorCode - :ivar message: A human-readable description of the error. Required. - :vartype message: str - """ - - code: Union[str, "_models.VectorStoreFileErrorCode"] = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """One of ``server_error`` or ``rate_limit_exceeded``. Required. Known values are: - \"server_error\", \"invalid_file\", and \"unsupported_file\".""" - message: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """A human-readable description of the error. Required.""" - - @overload - def __init__( - self, - *, - code: Union[str, "_models.VectorStoreFileErrorCode"], - message: str, - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, **kwargs) - - -class VectorStoreStaticChunkingStrategyOptions(_model_base.Model): - """Options to configure a vector store static chunking strategy. - - :ivar max_chunk_size_tokens: The maximum number of tokens in each chunk. The default value is - 800. The minimum value is 100 and the maximum value is 4096. Required. - :vartype max_chunk_size_tokens: int - :ivar chunk_overlap_tokens: The number of tokens that overlap between chunks. The default value - is 400. - Note that the overlap must not exceed half of max_chunk_size_tokens. Required. - :vartype chunk_overlap_tokens: int - """ - - max_chunk_size_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The maximum number of tokens in each chunk. The default value is 800. The minimum value is 100 - and the maximum value is 4096. Required.""" - chunk_overlap_tokens: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) - """The number of tokens that overlap between chunks. The default value is 400. - Note that the overlap must not exceed half of max_chunk_size_tokens. Required.""" - - @overload - def __init__( - self, - *, - max_chunk_size_tokens: int, - chunk_overlap_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 VectorStoreStaticChunkingStrategyRequest(VectorStoreChunkingStrategyRequest, discriminator="static"): - """A statically configured chunking strategy. - - :ivar type: The object type, which is always 'static'. Required. - :vartype type: str or ~azure.ai.projects.models.STATIC - :ivar static: The options for the static chunking strategy. Required. - :vartype static: ~azure.ai.projects.models.VectorStoreStaticChunkingStrategyOptions - """ - - type: Literal[VectorStoreChunkingStrategyRequestType.STATIC] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'static'. Required.""" - static: "_models.VectorStoreStaticChunkingStrategyOptions" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The options for the static chunking strategy. Required.""" - - @overload - def __init__( - self, - *, - static: "_models.VectorStoreStaticChunkingStrategyOptions", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type=VectorStoreChunkingStrategyRequestType.STATIC, **kwargs) - - -class VectorStoreStaticChunkingStrategyResponse( - VectorStoreChunkingStrategyResponse, discriminator="static" -): # pylint: disable=name-too-long - """A statically configured chunking strategy. - - :ivar type: The object type, which is always 'static'. Required. - :vartype type: str or ~azure.ai.projects.models.STATIC - :ivar static: The options for the static chunking strategy. Required. - :vartype static: ~azure.ai.projects.models.VectorStoreStaticChunkingStrategyOptions - """ - - type: Literal[VectorStoreChunkingStrategyResponseType.STATIC] = rest_discriminator(name="type", visibility=["read", "create", "update", "delete", "query"]) # type: ignore - """The object type, which is always 'static'. Required.""" - static: "_models.VectorStoreStaticChunkingStrategyOptions" = rest_field( - visibility=["read", "create", "update", "delete", "query"] - ) - """The options for the static chunking strategy. Required.""" - - @overload - def __init__( - self, - *, - static: "_models.VectorStoreStaticChunkingStrategyOptions", - ) -> None: ... - - @overload - def __init__(self, mapping: Mapping[str, Any]) -> None: - """ - :param mapping: raw JSON to initialize the model. - :type mapping: Mapping[str, Any] - """ - - def __init__(self, *args: Any, **kwargs: Any) -> None: - super().__init__(*args, type=VectorStoreChunkingStrategyResponseType.STATIC, **kwargs) - - -class WorkspaceProperties(_model_base.Model): - """workspace properties. - - :ivar application_insights: Authentication type of the connection target. Required. - :vartype application_insights: str - """ - - application_insights: str = rest_field( - name="applicationInsights", visibility=["read", "create", "update", "delete", "query"] - ) - """Authentication type of the connection target. Required.""" - - @overload - def __init__( - self, - *, - application_insights: str, + size: str, + tier: str, ) -> 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 0d6d44e9c93c..8bcb627aa475 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 @@ -1,2042 +1,15 @@ -# pylint: disable=too-many-lines -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -import asyncio # pylint: disable=do-not-import-asyncio -import base64 -import datetime -import inspect -import itertools -import json -import logging -import math -import re -from abc import ABC, abstractmethod -from typing import ( - Any, - AsyncIterator, - Awaitable, - Callable, - Dict, - Generic, - Iterator, - List, - Mapping, - Optional, - Set, - Tuple, - Type, - TypeVar, - Union, - cast, - get_args, - get_origin, - overload, -) +from typing import List -from azure.core.credentials import AccessToken, TokenCredential -from azure.core.credentials_async import AsyncTokenCredential - -from ._enums import AgentStreamEvent, ConnectionType, MessageRole, AzureAISearchQueryType -from ._models import ( - AISearchIndexResource, - AzureAISearchResource, - AzureAISearchToolDefinition, - AzureFunctionDefinition, - AzureFunctionStorageQueue, - AzureFunctionToolDefinition, - AzureFunctionBinding, - BingCustomSearchToolDefinition, - BingGroundingToolDefinition, - CodeInterpreterToolDefinition, - CodeInterpreterToolResource, - ConnectedAgentToolDefinition, - ConnectedAgentDetails, - FileSearchToolDefinition, - FileSearchToolResource, - FunctionDefinition, - FunctionToolDefinition, - GetConnectionResponse, - MessageImageFileContent, - MessageTextContent, - MessageTextFileCitationAnnotation, - MessageTextUrlCitationAnnotation, - MessageTextFilePathAnnotation, - MicrosoftFabricToolDefinition, - OpenApiAuthDetails, - OpenApiToolDefinition, - OpenApiFunctionDefinition, - RequiredFunctionToolCall, - RunStep, - RunStepDeltaChunk, - SearchConfiguration, - SearchConfigurationList, - SharepointToolDefinition, - SubmitToolOutputsAction, - ThreadRun, - ToolConnection, - ToolConnectionList, - ToolDefinition, - ToolResources, - MessageDeltaTextContent, - VectorStoreDataSource, -) - -from ._models import MessageDeltaChunk as MessageDeltaChunkGenerated -from ._models import ThreadMessage as ThreadMessageGenerated -from ._models import OpenAIPageableListOfThreadMessage as OpenAIPageableListOfThreadMessageGenerated -from ._models import MessageAttachment as MessageAttachmentGenerated - -from .. import _types - - -logger = logging.getLogger(__name__) - -StreamEventData = Union["MessageDeltaChunk", "ThreadMessage", ThreadRun, RunStep, str] - - -def _has_errors_in_toolcalls_output(tool_outputs: List[Dict]) -> bool: - """ - Check if any tool output contains an error. - - :param List[Dict] tool_outputs: A list of tool outputs to check. - :return: True if any output contains an error, False otherwise. - :rtype: bool - """ - for tool_output in tool_outputs: - output = tool_output.get("output") - if isinstance(output, str): - try: - output_json = json.loads(output) - if "error" in output_json: - return True - except json.JSONDecodeError: - continue - return False - - -def _filter_parameters(model_class: Type, parameters: Dict[str, Any]) -> Dict[str, Any]: - """ - Remove the parameters, non present in class public fields; return shallow copy of a dictionary. - - **Note:** Classes inherited from the model check that the parameters are present - in the list of attributes and if they are not, the error is being raised. This check may not - be relevant for classes, not inherited from azure.ai.projects._model_base.Model. - :param Type model_class: The class of model to be used. - :param parameters: The parsed dictionary with parameters. - :type parameters: Union[str, Dict[str, Any]] - :return: The dictionary with all invalid parameters removed. - :rtype: Dict[str, Any] - """ - new_params = {} - valid_parameters = set( - filter( - lambda x: not x.startswith("_") and hasattr(model_class.__dict__[x], "_type"), model_class.__dict__.keys() - ) - ) - for k in filter(lambda x: x in valid_parameters, parameters.keys()): - new_params[k] = parameters[k] - return new_params - - -def _safe_instantiate( - model_class: Type, parameters: Union[str, Dict[str, Any]], *, generated_class: Optional[Type] = None -) -> StreamEventData: - """ - Instantiate class with the set of parameters from the server. - - :param Type model_class: The class of model to be used. - :param parameters: The parsed dictionary with parameters. - :type parameters: Union[str, Dict[str, Any]] - :keyword Optional[Type] generated_class: The optional generated type. - :return: The class of model_class type if parameters is a dictionary, or the parameters themselves otherwise. - :rtype: Any - """ - if not generated_class: - generated_class = model_class - if not isinstance(parameters, dict): - return parameters - return cast(StreamEventData, model_class(**_filter_parameters(generated_class, parameters))) - - -def _parse_event(event_data_str: str) -> Tuple[str, StreamEventData]: - event_lines = event_data_str.strip().split("\n") - event_type: Optional[str] = None - event_data = "" - event_obj: StreamEventData - for line in event_lines: - if line.startswith("event:"): - event_type = line.split(":", 1)[1].strip() - elif line.startswith("data:"): - event_data = line.split(":", 1)[1].strip() - - if not event_type: - raise ValueError("Event type not specified in the event data.") - - try: - parsed_data: Union[str, Dict[str, StreamEventData]] = cast(Dict[str, StreamEventData], json.loads(event_data)) - except json.JSONDecodeError: - parsed_data = event_data - - # Workaround for service bug: Rename 'expires_at' to 'expired_at' - if event_type.startswith("thread.run.step") and isinstance(parsed_data, dict) and "expires_at" in parsed_data: - parsed_data["expired_at"] = parsed_data.pop("expires_at") - - if isinstance(parsed_data, dict) and "assistant_id" in parsed_data: - parsed_data["agent_id"] = parsed_data.pop("assistant_id") - - # Map to the appropriate class instance - if event_type in { - AgentStreamEvent.THREAD_RUN_CREATED.value, - AgentStreamEvent.THREAD_RUN_QUEUED.value, - AgentStreamEvent.THREAD_RUN_INCOMPLETE.value, - AgentStreamEvent.THREAD_RUN_IN_PROGRESS.value, - AgentStreamEvent.THREAD_RUN_REQUIRES_ACTION.value, - AgentStreamEvent.THREAD_RUN_COMPLETED.value, - AgentStreamEvent.THREAD_RUN_FAILED.value, - AgentStreamEvent.THREAD_RUN_CANCELLING.value, - AgentStreamEvent.THREAD_RUN_CANCELLED.value, - AgentStreamEvent.THREAD_RUN_EXPIRED.value, - }: - event_obj = _safe_instantiate(ThreadRun, parsed_data) - elif event_type in { - AgentStreamEvent.THREAD_RUN_STEP_CREATED.value, - AgentStreamEvent.THREAD_RUN_STEP_IN_PROGRESS.value, - AgentStreamEvent.THREAD_RUN_STEP_COMPLETED.value, - AgentStreamEvent.THREAD_RUN_STEP_FAILED.value, - AgentStreamEvent.THREAD_RUN_STEP_CANCELLED.value, - AgentStreamEvent.THREAD_RUN_STEP_EXPIRED.value, - }: - event_obj = _safe_instantiate(RunStep, parsed_data) - elif event_type in { - AgentStreamEvent.THREAD_MESSAGE_CREATED.value, - AgentStreamEvent.THREAD_MESSAGE_IN_PROGRESS.value, - AgentStreamEvent.THREAD_MESSAGE_COMPLETED.value, - AgentStreamEvent.THREAD_MESSAGE_INCOMPLETE.value, - }: - event_obj = _safe_instantiate(ThreadMessage, parsed_data, generated_class=ThreadMessageGenerated) - elif event_type == AgentStreamEvent.THREAD_MESSAGE_DELTA.value: - event_obj = _safe_instantiate(MessageDeltaChunk, parsed_data, generated_class=MessageDeltaChunkGenerated) - - elif event_type == AgentStreamEvent.THREAD_RUN_STEP_DELTA.value: - event_obj = _safe_instantiate(RunStepDeltaChunk, parsed_data) - else: - event_obj = str(parsed_data) - - return event_type, event_obj - - -class ConnectionProperties: - """The properties of a single connection. - - :ivar id: A unique identifier for the connection. - :vartype id: str - :ivar name: The friendly name of the connection. - :vartype name: str - :ivar authentication_type: The authentication type used by the connection. - :vartype authentication_type: ~azure.ai.projects.models._models.AuthenticationType - :ivar connection_type: The connection type . - :vartype connection_type: ~azure.ai.projects.models._models.ConnectionType - :ivar endpoint_url: The endpoint URL associated with this connection - :vartype endpoint_url: str - :ivar key: The api-key to be used when accessing the connection. - :vartype key: str - :ivar token_credential: The TokenCredential to be used when accessing the connection. - :vartype token_credential: ~azure.core.credentials.TokenCredential - """ - - def __init__( - self, - *, - connection: GetConnectionResponse, - token_credential: Union[TokenCredential, AsyncTokenCredential, None] = None, - ) -> None: - self.id = connection.id - self.name = connection.name - self.authentication_type = connection.properties.auth_type - self.connection_type = cast(ConnectionType, connection.properties.category) - self.endpoint_url = ( - connection.properties.target[:-1] - if connection.properties.target.endswith("/") - else connection.properties.target - ) - self.key: Optional[str] = None - if hasattr(connection.properties, "credentials"): - if hasattr(connection.properties.credentials, "key"): # type: ignore - self.key = connection.properties.credentials.key # type: ignore - self.token_credential = token_credential - - def to_evaluator_model_config( - self, deployment_name: str, api_version: str, *, include_credentials: bool = False - ) -> Dict[str, str]: - """Get model configuration to be used with evaluators, from connection. - - :param deployment_name: Deployment name to build model configuration. - :type deployment_name: str - :param api_version: API version used by model deployment. - :type api_version: str - :keyword include_credentials: Include credentials in the model configuration. If set to True, the model - configuration will have the key field set to the actual key value. - If set to False, the model configuration will have the key field set to the connection id. - To get the secret, connection.get method should be called with include_credentials set to True. - :paramtype include_credentials: bool - - :returns: Model configuration dictionary. - :rtype: Dict[str, str] - """ - connection_type = self.connection_type.value - if self.connection_type.value == ConnectionType.AZURE_OPEN_AI: - connection_type = "azure_openai" - - if self.authentication_type == "ApiKey": - model_config = { - "azure_deployment": deployment_name, - "azure_endpoint": self.endpoint_url, - "type": connection_type, - "api_version": api_version, - "api_key": self.key if include_credentials and self.key else f"{self.id}/credentials/key", - } - else: - model_config = { - "azure_deployment": deployment_name, - "azure_endpoint": self.endpoint_url, - "type": self.connection_type, - "api_version": api_version, - } - return model_config - - def __str__(self): - out = "{\n" - out += f' "name": "{self.name}",\n' - out += f' "id": "{self.id}",\n' - out += f' "authentication_type": "{self.authentication_type}",\n' - out += f' "connection_type": "{self.connection_type}",\n' - out += f' "endpoint_url": "{self.endpoint_url}",\n' - if self.key: - out += ' "key": "REDACTED"\n' - else: - out += ' "key": null\n' - if self.token_credential: - out += ' "token_credential": "REDACTED"\n' - else: - out += ' "token_credential": null\n' - out += "}\n" - return out - - -# TODO: Look into adding an async version of this class -class SASTokenCredential(TokenCredential): - def __init__( - self, - *, - sas_token: str, - credential: TokenCredential, - subscription_id: str, - resource_group_name: str, - project_name: str, - connection_name: str, - ): - self._sas_token = sas_token - self._credential = credential - self._subscription_id = subscription_id - self._resource_group_name = resource_group_name - self._project_name = project_name - self._connection_name = connection_name - self._expires_on = SASTokenCredential._get_expiration_date_from_token(self._sas_token) - logger.debug("[SASTokenCredential.__init__] Exit. Given token expires on %s.", self._expires_on) - - @classmethod - def _get_expiration_date_from_token(cls, jwt_token: str) -> datetime.datetime: - payload = jwt_token.split(".")[1] - padded_payload = payload + "=" * (4 - len(payload) % 4) # Add padding if necessary - decoded_bytes = base64.urlsafe_b64decode(padded_payload) - decoded_str = decoded_bytes.decode("utf-8") - decoded_payload = json.loads(decoded_str) - expiration_date = decoded_payload.get("exp") - return datetime.datetime.fromtimestamp(expiration_date, datetime.timezone.utc) - - def _refresh_token(self) -> None: - logger.debug("[SASTokenCredential._refresh_token] Enter") - from azure.ai.projects import AIProjectClient - - project_client = AIProjectClient( - credential=self._credential, - # Since we are only going to use the "connections" operations, we don't need to supply an endpoint. - # http://management.azure.com is hard coded in the SDK. - endpoint="not-needed", - subscription_id=self._subscription_id, - resource_group_name=self._resource_group_name, - project_name=self._project_name, - ) - - connection = project_client.connections.get(connection_name=self._connection_name, include_credentials=True) - - self._sas_token = "" - if connection is not None and connection.token_credential is not None: - sas_credential = cast(SASTokenCredential, connection.token_credential) - self._sas_token = sas_credential._sas_token # pylint: disable=protected-access - self._expires_on = SASTokenCredential._get_expiration_date_from_token(self._sas_token) - logger.debug("[SASTokenCredential._refresh_token] Exit. New token expires on %s.", self._expires_on) - - def get_token( - self, - *scopes: str, - claims: Optional[str] = None, - tenant_id: Optional[str] = None, - enable_cae: bool = False, - **kwargs: Any, - ) -> AccessToken: - """Request an access token for `scopes`. - - :param str scopes: The type of access needed. - - :keyword str claims: Additional claims required in the token, such as those returned in a resource - provider's claims challenge following an authorization failure. - :keyword str tenant_id: Optional tenant to include in the token request. - :keyword bool enable_cae: Indicates whether to enable Continuous Access Evaluation (CAE) for the requested - token. Defaults to False. - - :rtype: AccessToken - :return: An AccessToken instance containing the token string and its expiration time in Unix time. - """ - logger.debug("SASTokenCredential.get_token] Enter") - if self._expires_on < datetime.datetime.now(datetime.timezone.utc): - self._refresh_token() - return AccessToken(self._sas_token, math.floor(self._expires_on.timestamp())) - - -# Define type_map to translate Python type annotations to JSON Schema types -type_map = { - "str": "string", - "int": "integer", - "float": "number", - "bool": "boolean", - "NoneType": "null", - "list": "array", - "dict": "object", -} - - -def _map_type(annotation) -> Dict[str, Any]: # pylint: disable=too-many-return-statements - if annotation == inspect.Parameter.empty: - return {"type": "string"} # Default type if annotation is missing - - origin = get_origin(annotation) - - if origin in {list, List}: - args = get_args(annotation) - item_type = args[0] if args else str - return {"type": "array", "items": _map_type(item_type)} - if origin in {dict, Dict}: - return {"type": "object"} - if origin is Union: - args = get_args(annotation) - # If Union contains None, it is an optional parameter - if type(None) in args: - # If Union contains only one non-None type, it is a nullable parameter - non_none_args = [arg for arg in args if arg is not type(None)] - if len(non_none_args) == 1: - schema = _map_type(non_none_args[0]) - if "type" in schema: - if isinstance(schema["type"], str): - schema["type"] = [schema["type"], "null"] - elif "null" not in schema["type"]: - schema["type"].append("null") - else: - schema["type"] = ["null"] - return schema - # If Union contains multiple types, it is a oneOf parameter - return {"oneOf": [_map_type(arg) for arg in args]} - if isinstance(annotation, type): - schema_type = type_map.get(annotation.__name__, "string") - return {"type": schema_type} - - return {"type": "string"} # Fallback to "string" if type is unrecognized - - -def is_optional(annotation) -> bool: - origin = get_origin(annotation) - if origin is Union: - args = get_args(annotation) - return type(None) in args - return False - - -class MessageDeltaChunk(MessageDeltaChunkGenerated): - @property - def text(self) -> str: - """Get the text content of the delta chunk. - - :rtype: str - """ - if not self.delta or not self.delta.content: - return "" - return "".join( - content_part.text.value or "" - for content_part in self.delta.content - if isinstance(content_part, MessageDeltaTextContent) and content_part.text - ) - - -class ThreadMessage(ThreadMessageGenerated): - @property - def text_messages(self) -> List[MessageTextContent]: - """Returns all text message contents in the messages. - - :rtype: List[MessageTextContent] - """ - if not self.content: - return [] - return [content for content in self.content if isinstance(content, MessageTextContent)] - - @property - def image_contents(self) -> List[MessageImageFileContent]: - """Returns all image file contents from image message contents in the messages. - - :rtype: List[MessageImageFileContent] - """ - if not self.content: - return [] - return [content for content in self.content if isinstance(content, MessageImageFileContent)] - - @property - def file_citation_annotations(self) -> List[MessageTextFileCitationAnnotation]: - """Returns all file citation annotations from text message annotations in the messages. - - :rtype: List[MessageTextFileCitationAnnotation] - """ - if not self.content: - return [] - - return [ - annotation - for content in self.content - if isinstance(content, MessageTextContent) - for annotation in content.text.annotations - if isinstance(annotation, MessageTextFileCitationAnnotation) - ] - - @property - def file_path_annotations(self) -> List[MessageTextFilePathAnnotation]: - """Returns all file path annotations from text message annotations in the messages. - - :rtype: List[MessageTextFilePathAnnotation] - """ - if not self.content: - return [] - return [ - annotation - for content in self.content - if isinstance(content, MessageTextContent) - for annotation in content.text.annotations - if isinstance(annotation, MessageTextFilePathAnnotation) - ] - - @property - def url_citation_annotations(self) -> List[MessageTextUrlCitationAnnotation]: - """Returns all URL citation annotations from text message annotations in the messages. - - :rtype: List[MessageTextUrlCitationAnnotation] - """ - if not self.content: - return [] - return [ - annotation - for content in self.content - if isinstance(content, MessageTextContent) - for annotation in content.text.annotations - if isinstance(annotation, MessageTextUrlCitationAnnotation) - ] - - -class MessageAttachment(MessageAttachmentGenerated): - @overload - def __init__( - self, - *, - tools: List["FileSearchToolDefinition"], - file_id: Optional[str] = None, - data_source: Optional["VectorStoreDataSource"] = None, - ) -> None: ... - @overload - def __init__( - self, - *, - tools: List["CodeInterpreterToolDefinition"], - file_id: Optional[str] = None, - data_source: Optional["VectorStoreDataSource"] = None, - ) -> None: ... - @overload - def __init__( - self, - *, - tools: List["_types.MessageAttachmentToolDefinition"], - file_id: Optional[str] = None, - data_source: Optional["VectorStoreDataSource"] = 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) - - -ToolDefinitionT = TypeVar("ToolDefinitionT", bound=ToolDefinition) -ToolT = TypeVar("ToolT", bound="Tool") - - -class Tool(ABC, Generic[ToolDefinitionT]): - """ - An abstract class representing a tool that can be used by an agent. - """ - - @property - @abstractmethod - def definitions(self) -> List[ToolDefinitionT]: - """Get the tool definitions.""" - - @property - @abstractmethod - def resources(self) -> ToolResources: - """Get the tool resources.""" - - @abstractmethod - def execute(self, tool_call: Any) -> Any: - """ - Execute the tool with the provided tool call. - - :param Any tool_call: The tool call to execute. - :return: The output of the tool operations. - """ - - -class BaseFunctionTool(Tool[FunctionToolDefinition]): - """ - A tool that executes user-defined functions. - """ - - def __init__(self, functions: Set[Callable[..., Any]]): - """ - Initialize FunctionTool with a set of functions. - - :param functions: A set of function objects. - """ - self._functions = self._create_function_dict(functions) - self._definitions = self._build_function_definitions(self._functions) - - def add_functions(self, extra_functions: Set[Callable[..., Any]]) -> None: - """ - Add more functions into this FunctionTool’s existing function set. - If a function with the same name already exists, it is overwritten. - - :param extra_functions: A set of additional functions to be added to - the existing function set. Functions are defined as callables and - may have any number of arguments and return types. - :type extra_functions: Set[Callable[..., Any]] - """ - # Convert the existing dictionary of { name: function } back into a set - existing_functions = set(self._functions.values()) - # Merge old + new - combined = existing_functions.union(extra_functions) - # Rebuild state - self._functions = self._create_function_dict(combined) - self._definitions = self._build_function_definitions(self._functions) - - def _create_function_dict(self, functions: Set[Callable[..., Any]]) -> Dict[str, Callable[..., Any]]: - return {func.__name__: func for func in functions} - - def _build_function_definitions(self, functions: Dict[str, Any]) -> List[FunctionToolDefinition]: - specs: List[FunctionToolDefinition] = [] - # Flexible regex to capture ':param : ' - param_pattern = re.compile( - r""" - ^\s* # Optional leading whitespace - :param # Literal ':param' - \s+ # At least one whitespace character - (?P[^:\s\(\)]+) # Parameter name (no spaces, colons, or parentheses) - (?:\s*\(\s*(?P[^)]+?)\s*\))? # Optional type in parentheses, allowing internal spaces - \s*:\s* # Colon ':' surrounded by optional whitespace - (?P.+) # Description (rest of the line) - """, - re.VERBOSE, - ) - - for name, func in functions.items(): - sig = inspect.signature(func) - params = sig.parameters - docstring = inspect.getdoc(func) or "" - description = docstring.split("\n", maxsplit=1)[0] if docstring else "No description" - - param_descriptions = {} - for line in docstring.splitlines(): - line = line.strip() - match = param_pattern.match(line) - if match: - groups = match.groupdict() - param_name = groups.get("name") - param_desc = groups.get("description") - param_desc = param_desc.strip() if param_desc else "No description" - param_descriptions[param_name] = param_desc.strip() - - properties = {} - required = [] - for param_name, param in params.items(): - param_type_info = _map_type(param.annotation) - param_description = param_descriptions.get(param_name, "No description") - - properties[param_name] = {**param_type_info, "description": param_description} - - # If the parameter has no default value and is not optional, add it to the required list - if param.default is inspect.Parameter.empty and not is_optional(param.annotation): - required.append(param_name) - - function_def = FunctionDefinition( - name=name, - description=description, - parameters={"type": "object", "properties": properties, "required": required}, - ) - tool_def = FunctionToolDefinition(function=function_def) - specs.append(tool_def) - - return specs - - def _get_func_and_args(self, tool_call: RequiredFunctionToolCall) -> Tuple[Any, Dict[str, Any]]: - function_name = tool_call.function.name - arguments = tool_call.function.arguments - - if function_name not in self._functions: - raise ValueError(f"Function '{function_name}' not found.") - - function = self._functions[function_name] - - try: - parsed_arguments = json.loads(arguments) - except json.JSONDecodeError as e: - raise ValueError(f"Invalid JSON arguments: {e}") from e - - if not isinstance(parsed_arguments, dict): - raise TypeError("Arguments must be a JSON object.") - - return function, parsed_arguments - - @property - def definitions(self) -> List[FunctionToolDefinition]: - """ - Get the function definitions. - - :return: A list of function definitions. - :rtype: List[ToolDefinition] - """ - return self._definitions - - @property - def resources(self) -> ToolResources: - """ - Get the tool resources for the agent. - - :return: An empty ToolResources as FunctionTool doesn't have specific resources. - :rtype: ToolResources - """ - return ToolResources() - - -class FunctionTool(BaseFunctionTool): - - def execute(self, tool_call: RequiredFunctionToolCall) -> Any: - try: - function, parsed_arguments = self._get_func_and_args(tool_call) - return function(**parsed_arguments) if parsed_arguments else function() - except Exception as e: # pylint: disable=broad-exception-caught - error_message = f"Error executing function '{tool_call.function.name}': {e}" - logging.error(error_message) - # Return error message as JSON string back to agent in order to make possible self - # correction to the function call - return json.dumps({"error": error_message}) - - -class AsyncFunctionTool(BaseFunctionTool): - - async def execute(self, tool_call: RequiredFunctionToolCall) -> Any: # pylint: disable=invalid-overridden-method - try: - function, parsed_arguments = self._get_func_and_args(tool_call) - if inspect.iscoroutinefunction(function): - return await function(**parsed_arguments) if parsed_arguments else await function() - return function(**parsed_arguments) if parsed_arguments else function() - except Exception as e: # pylint: disable=broad-exception-caught - error_message = f"Error executing function '{tool_call.function.name}': {e}" - logging.error(error_message) - # Return error message as JSON string back to agent in order to make possible self correction - # to the function call - return json.dumps({"error": error_message}) - - -class AzureAISearchTool(Tool[AzureAISearchToolDefinition]): - """ - A tool that searches for information using Azure AI Search. - :param connection_id: Connection ID used by tool. All connection tools allow only one connection. - """ - - def __init__( - self, - index_connection_id: str, - index_name: str, - query_type: AzureAISearchQueryType = AzureAISearchQueryType.SIMPLE, - filter: str = "", - top_k: int = 5, - ): - """ - Initialize AzureAISearch with an index_connection_id and index_name, with optional params. - - :param index_connection_id: Index Connection ID used by tool. Allows only one connection. - :type index_connection_id: str - :param index_name: Name of Index in search resource to be used by tool. - :type index_name: str - :param query_type: Type of query in an AIIndexResource attached to this agent. - Default value is AzureAISearchQueryType.SIMPLE. - :type query_type: AzureAISearchQueryType - :param filter: Odata filter string for search resource. - :type filter: str - :param top_k: Number of documents to retrieve from search and present to the model. - :type top_k: int - """ - self.index_list = [ - AISearchIndexResource( - index_connection_id=index_connection_id, - index_name=index_name, - query_type=query_type, - filter=filter, - top_k=top_k, - ) - ] - - @property - def definitions(self) -> List[AzureAISearchToolDefinition]: - """ - Get the Azure AI search tool definitions. - - :return: A list of tool definitions. - :rtype: List[ToolDefinition] - """ - return [AzureAISearchToolDefinition()] - - @property - def resources(self) -> ToolResources: - """ - Get the Azure AI search resources. - - :return: ToolResources populated with azure_ai_search associated resources. - :rtype: ToolResources - """ - return ToolResources(azure_ai_search=AzureAISearchResource(index_list=self.index_list)) - - def execute(self, tool_call: Any): - """ - AI Search tool does not execute client-side. - - :param Any tool_call: The tool call to execute. - """ - - -class OpenApiTool(Tool[OpenApiToolDefinition]): - """ - A tool that retrieves information using OpenAPI specs. - Initialized with an initial API definition (name, description, spec, auth), - this class also supports adding and removing additional API definitions dynamically. - """ - - def __init__( - self, - name: str, - description: str, - spec: Any, - auth: OpenApiAuthDetails, - default_parameters: Optional[List[str]] = None, - ) -> None: - """ - Constructor initializes the tool with a primary API definition. - - :param name: The name of the API. - :type name: str - :param description: The API description. - :type description: str - :param spec: The API specification. - :type spec: Any - :param auth: Authentication details for the API. - :type auth: OpenApiAuthDetails - :param default_parameters: List of OpenAPI spec parameters that will use user-provided defaults. - :type default_parameters: Optional[List[str]] - """ - default_params: List[str] = [] if default_parameters is None else default_parameters - self._default_auth = auth - self._definitions: List[OpenApiToolDefinition] = [ - OpenApiToolDefinition( - openapi=OpenApiFunctionDefinition( - name=name, description=description, spec=spec, auth=auth, default_params=default_params - ) - ) - ] - - @property - def definitions(self) -> List[OpenApiToolDefinition]: - """ - Get the list of all API definitions for the tool. - - :return: A list of OpenAPI tool definitions. - :rtype: List[ToolDefinition] - """ - return self._definitions - - def add_definition( - self, - name: str, - description: str, - spec: Any, - auth: Optional[OpenApiAuthDetails] = None, - default_parameters: Optional[List[str]] = None, - ) -> None: - """ - Adds a new API definition dynamically. - Raises a ValueError if a definition with the same name already exists. - - :param name: The name of the API. - :type name: str - :param description: The description of the API. - :type description: str - :param spec: The API specification. - :type spec: Any - :param auth: Optional authentication details for this particular API definition. - If not provided, the tool's default authentication details will be used. - :type auth: Optional[OpenApiAuthDetails] - :param default_parameters: List of OpenAPI spec parameters that will use user-provided defaults. - :type default_parameters: List[str] - :raises ValueError: If a definition with the same name exists. - """ - default_params: List[str] = [] if default_parameters is None else default_parameters - - # Check if a definition with the same name exists. - if any(definition.openapi.name == name for definition in self._definitions): - raise ValueError(f"Definition '{name}' already exists and cannot be added again.") - - # Use provided auth if specified, otherwise use default - auth_to_use = auth if auth is not None else self._default_auth - - new_definition = OpenApiToolDefinition( - openapi=OpenApiFunctionDefinition( - name=name, description=description, spec=spec, auth=auth_to_use, default_params=default_params - ) - ) - self._definitions.append(new_definition) - - def remove_definition(self, name: str) -> None: - """ - Removes an API definition based on its name. - - :param name: The name of the API definition to remove. - :type name: str - :raises ValueError: If the definition with the specified name does not exist. - """ - for definition in self._definitions: - if definition.openapi.name == name: - self._definitions.remove(definition) - logging.info("Definition '%s' removed. Total definitions: %d.", name, len(self._definitions)) - return - raise ValueError(f"Definition with the name '{name}' does not exist.") - - @property - def resources(self) -> ToolResources: - """ - Get the tool resources for the agent. - - :return: An empty ToolResources as OpenApiTool doesn't have specific resources. - :rtype: ToolResources - """ - return ToolResources() - - def execute(self, tool_call: Any) -> None: - """ - OpenApiTool does not execute client-side. - - :param Any tool_call: The tool call to execute. - :type tool_call: Any - """ - - -class AzureFunctionTool(Tool[AzureFunctionToolDefinition]): - """ - A tool that is used to inform agent about available the Azure function. - - :param name: The azure function name. - :param description: The azure function description. - :param parameters: The description of function parameters. - :param input_queue: Input queue used, by azure function. - :param output_queue: Output queue used, by azure function. - """ - - def __init__( - self, - name: str, - description: str, - parameters: Dict[str, Any], - input_queue: AzureFunctionStorageQueue, - output_queue: AzureFunctionStorageQueue, - ) -> None: - self._definitions = [ - AzureFunctionToolDefinition( - azure_function=AzureFunctionDefinition( - function=FunctionDefinition( - name=name, - description=description, - parameters=parameters, - ), - input_binding=AzureFunctionBinding(storage_queue=input_queue), - output_binding=AzureFunctionBinding(storage_queue=output_queue), - ) - ) - ] - - @property - def definitions(self) -> List[AzureFunctionToolDefinition]: - """ - Get the Azure AI search tool definitions. - - :rtype: List[ToolDefinition] - """ - return self._definitions - - @property - def resources(self) -> ToolResources: - """ - Get the Azure AI search resources. - - :rtype: ToolResources - """ - return ToolResources() - - def execute(self, tool_call: Any) -> Any: - pass - - -class ConnectionTool(Tool[ToolDefinitionT]): - """ - A tool that requires connection ids. - Used as base class for Bing Grounding, Sharepoint, and Microsoft Fabric - """ - - def __init__(self, connection_id: str): - """ - Initialize ConnectionTool with a connection_id. - - :param connection_id: Connection ID used by tool. All connection tools allow only one connection. - """ - self.connection_ids = [ToolConnection(connection_id=connection_id)] - - @property - def resources(self) -> ToolResources: - """ - Get the connection tool resources. - - :rtype: ToolResources - """ - return ToolResources() - - def execute(self, tool_call: Any) -> Any: - pass - - -class BingGroundingTool(ConnectionTool[BingGroundingToolDefinition]): - """ - A tool that searches for information using Bing. - """ - - @property - def definitions(self) -> List[BingGroundingToolDefinition]: - """ - Get the Bing grounding tool definitions. - - :rtype: List[ToolDefinition] - """ - return [BingGroundingToolDefinition(bing_grounding=ToolConnectionList(connection_list=self.connection_ids))] - - -class BingCustomSearchTool(Tool[BingCustomSearchToolDefinition]): - """ - A tool that searches for information using Bing Custom Search. - """ - - def __init__(self, connection_id: str, instance_name: str): - """ - Initialize Bing Custom Search with a connection_id. - - :param connection_id: Connection ID used by tool. Bing Custom Search tools allow only one connection. - :param instance_name: Config instance name used by tool. - """ - self.connection_ids = [SearchConfiguration(connection_id=connection_id, instance_name=instance_name)] - - @property - def definitions(self) -> List[BingCustomSearchToolDefinition]: - """ - Get the Bing grounding tool definitions. - - :rtype: List[ToolDefinition] - """ - return [ - BingCustomSearchToolDefinition( - bing_custom_search=SearchConfigurationList(search_configurations=self.connection_ids) - ) - ] - - @property - def resources(self) -> ToolResources: - """ - Get the connection tool resources. - - :rtype: ToolResources - """ - return ToolResources() - - def execute(self, tool_call: Any) -> Any: - pass - - -class ConnectedAgentTool(Tool[ConnectedAgentToolDefinition]): - """ - A tool that connects to a sub-agent, with a description describing the conditions - or domain where the sub-agent would be called. - """ - - def __init__(self, id: str, name: str, description: str): - """ - Initialize ConnectedAgentTool with an id, name, and description. - - :param id: The ID of the connected agent. - :param name: The name of the connected agent. - :param description: The description of the connected agent, used by the calling agent - to determine when to call the connected agent. - """ - self.connected_agent = ConnectedAgentDetails(id=id, name=name, description=description) - - @property - def definitions(self) -> List[ConnectedAgentToolDefinition]: - """ - Get the connected agent tool definitions. - - :rtype: List[ToolDefinition] - """ - return [ConnectedAgentToolDefinition(connected_agent=self.connected_agent)] - - @property - def resources(self) -> ToolResources: - """ - Get the tool resources for the agent. - - :return: An empty ToolResources as ConnectedAgentTool doesn't have specific resources. - :rtype: ToolResources - """ - return ToolResources() - - def execute(self, tool_call: Any) -> None: - """ - ConnectedAgentTool does not execute client-side. - - :param Any tool_call: The tool call to execute. - :type tool_call: Any - """ - - -class FabricTool(ConnectionTool[MicrosoftFabricToolDefinition]): - """ - A tool that searches for information using Microsoft Fabric. - """ - - @property - def definitions(self) -> List[MicrosoftFabricToolDefinition]: - """ - Get the Microsoft Fabric tool definitions. - - :rtype: List[ToolDefinition] - """ - return [MicrosoftFabricToolDefinition(fabric_dataagent=ToolConnectionList(connection_list=self.connection_ids))] - - -class SharepointTool(ConnectionTool[SharepointToolDefinition]): - """ - A tool that searches for information using Sharepoint. - """ - - @property - def definitions(self) -> List[SharepointToolDefinition]: - """ - Get the Sharepoint tool definitions. - - :rtype: List[ToolDefinition] - """ - return [SharepointToolDefinition(sharepoint_grounding=ToolConnectionList(connection_list=self.connection_ids))] - - -class FileSearchTool(Tool[FileSearchToolDefinition]): - """ - A tool that searches for uploaded file information from the created vector stores. - - :param vector_store_ids: A list of vector store IDs to search for files. - :type vector_store_ids: list[str] - """ - - def __init__(self, vector_store_ids: Optional[List[str]] = None): - if vector_store_ids is None: - self.vector_store_ids = set() - else: - self.vector_store_ids = set(vector_store_ids) - - def add_vector_store(self, store_id: str) -> None: - """ - Add a vector store ID to the list of vector stores to search for files. - - :param store_id: The ID of the vector store to search for files. - :type store_id: str - - """ - self.vector_store_ids.add(store_id) - - def remove_vector_store(self, store_id: str) -> None: - """ - Remove a vector store ID from the list of vector stores to search for files. - - :param store_id: The ID of the vector store to remove. - :type store_id: str - - """ - self.vector_store_ids.remove(store_id) - - @property - def definitions(self) -> List[FileSearchToolDefinition]: - """ - Get the file search tool definitions. - - :rtype: List[ToolDefinition] - """ - return [FileSearchToolDefinition()] - - @property - def resources(self) -> ToolResources: - """ - Get the file search resources. - - :rtype: ToolResources - """ - return ToolResources(file_search=FileSearchToolResource(vector_store_ids=list(self.vector_store_ids))) - - def execute(self, tool_call: Any) -> Any: - pass - - -class CodeInterpreterTool(Tool[CodeInterpreterToolDefinition]): - """ - A tool that interprets code files uploaded to the agent. - - :param file_ids: A list of file IDs to interpret. - :type file_ids: list[str] - """ - - def __init__(self, file_ids: Optional[List[str]] = None): - if file_ids is None: - self.file_ids = set() - else: - self.file_ids = set(file_ids) - - def add_file(self, file_id: str) -> None: - """ - Add a file ID to the list of files to interpret. - - :param file_id: The ID of the file to interpret. - :type file_id: str - """ - self.file_ids.add(file_id) - - def remove_file(self, file_id: str) -> None: - """ - Remove a file ID from the list of files to interpret. - - :param file_id: The ID of the file to remove. - :type file_id: str - """ - self.file_ids.remove(file_id) - - @property - def definitions(self) -> List[CodeInterpreterToolDefinition]: - """ - Get the code interpreter tool definitions. - - :rtype: List[ToolDefinition] - """ - return [CodeInterpreterToolDefinition()] - - @property - def resources(self) -> ToolResources: - """ - Get the code interpreter resources. - - :rtype: ToolResources - """ - if not self.file_ids: - return ToolResources() - return ToolResources(code_interpreter=CodeInterpreterToolResource(file_ids=list(self.file_ids))) - - def execute(self, tool_call: Any) -> Any: - pass - - -class BaseToolSet: - """ - Abstract class for a collection of tools that can be used by an agent. - """ - - def __init__(self) -> None: - self._tools: List[Tool] = [] - - def validate_tool_type(self, tool: Tool) -> None: - pass - - def add(self, tool: Tool): - """ - Add a tool to the tool set. - - :param Tool tool: The tool to add. - :raises ValueError: If a tool of the same type already exists. - """ - self.validate_tool_type(tool) - - if any(isinstance(existing_tool, type(tool)) for existing_tool in self._tools): - raise ValueError("Tool of type {type(tool).__name__} already exists in the ToolSet.") - self._tools.append(tool) - - def remove(self, tool_type: Type[Tool]) -> None: - """ - Remove a tool of the specified type from the tool set. - - :param Type[Tool] tool_type: The type of tool to remove. - :raises ValueError: If a tool of the specified type is not found. - """ - for i, tool in enumerate(self._tools): - if isinstance(tool, tool_type): - del self._tools[i] - logging.info("Tool of type %s removed from the ToolSet.", tool_type.__name__) - return - raise ValueError(f"Tool of type {tool_type.__name__} not found in the ToolSet.") - - @property - def definitions(self) -> List[ToolDefinition]: - """ - Get the definitions for all tools in the tool set. - - :rtype: List[ToolDefinition] - """ - tools = [] - for tool in self._tools: - tools.extend(tool.definitions) - return tools - - @property - def resources(self) -> ToolResources: - """ - Get the resources for all tools in the tool set. - - :rtype: ToolResources - """ - tool_resources: Dict[str, Any] = {} - for tool in self._tools: - resources = tool.resources - for key, value in resources.items(): - if key in tool_resources: - if isinstance(tool_resources[key], dict) and isinstance(value, dict): - tool_resources[key].update(value) - else: - tool_resources[key] = value - return self._create_tool_resources_from_dict(tool_resources) - - def _create_tool_resources_from_dict(self, resources: Dict[str, Any]) -> ToolResources: - """ - Safely converts a dictionary into a ToolResources instance. - - :param resources: A dictionary of tool resources. Should be a mapping - accepted by ~azure.ai.projects.models.AzureAISearchResource - :type resources: Dict[str, Any] - :return: A ToolResources instance. - :rtype: ToolResources - """ - try: - return ToolResources(**resources) - except TypeError as e: - logging.error("Error creating ToolResources: %s", e) - raise ValueError("Invalid resources for ToolResources.") from e - - def get_definitions_and_resources(self) -> Dict[str, Any]: - """ - Get the definitions and resources for all tools in the tool set. - - :return: A dictionary containing the tool resources and definitions. - :rtype: Dict[str, Any] - """ - return { - "tool_resources": self.resources, - "tools": self.definitions, - } - - def get_tool(self, tool_type: Type[ToolT]) -> ToolT: - """ - Get a tool of the specified type from the tool set. - - :param Type[Tool] tool_type: The type of tool to get. - :return: The tool of the specified type. - :rtype: Tool - :raises ValueError: If a tool of the specified type is not found. - """ - for tool in self._tools: - if isinstance(tool, tool_type): - return cast(ToolT, tool) - raise ValueError(f"Tool of type {tool_type.__name__} not found in the ToolSet.") - - -class ToolSet(BaseToolSet): - """ - A collection of tools that can be used by an synchronize agent. - """ - - def validate_tool_type(self, tool: Tool) -> None: - """ - Validate the type of the tool. - - :param Tool tool: The type of the tool to validate. - :raises ValueError: If the tool type is not a subclass of Tool. - """ - if isinstance(tool, AsyncFunctionTool): - raise ValueError( - "AsyncFunctionTool is not supported in ToolSet. " - + "To use async functions, use AsyncToolSet and agents operations in azure.ai.projects.aio." - ) - - def execute_tool_calls(self, tool_calls: List[Any]) -> Any: - """ - Execute a tool of the specified type with the provided tool calls. - - :param List[Any] tool_calls: A list of tool calls to execute. - :return: The output of the tool operations. - :rtype: Any - """ - tool_outputs = [] - - for tool_call in tool_calls: - try: - if tool_call.type == "function": - tool = self.get_tool(FunctionTool) - output = tool.execute(tool_call) - tool_output = { - "tool_call_id": tool_call.id, - "output": output, - } - tool_outputs.append(tool_output) - except Exception as e: # pylint: disable=broad-exception-caught - tool_output = {"tool_call_id": tool_call.id, "output": str(e)} - tool_outputs.append(tool_output) - - return tool_outputs - - -class AsyncToolSet(BaseToolSet): - """ - A collection of tools that can be used by an asynchronous agent. - """ - - def validate_tool_type(self, tool: Tool) -> None: - """ - Validate the type of the tool. - - :param Tool tool: The type of the tool to validate. - :raises ValueError: If the tool type is not a subclass of Tool. - """ - if isinstance(tool, FunctionTool): - raise ValueError( - "FunctionTool is not supported in AsyncToolSet. " - + "Please use AsyncFunctionTool instead and provide sync and/or async function(s)." - ) - - async def execute_tool_calls(self, tool_calls: List[Any]) -> Any: - """ - Execute a tool of the specified type with the provided tool calls. - - :param List[Any] tool_calls: A list of tool calls to execute. - :return: The output of the tool operations. - :rtype: Any - """ - tool_outputs = [] - - for tool_call in tool_calls: - try: - if tool_call.type == "function": - tool = self.get_tool(AsyncFunctionTool) - output = await tool.execute(tool_call) - tool_output = { - "tool_call_id": tool_call.id, - "output": output, - } - tool_outputs.append(tool_output) - except Exception as e: # pylint: disable=broad-exception-caught - logging.error("Failed to execute tool call %s: %s", tool_call, e) - - return tool_outputs - - -EventFunctionReturnT = TypeVar("EventFunctionReturnT") -T = TypeVar("T") -BaseAsyncAgentEventHandlerT = TypeVar("BaseAsyncAgentEventHandlerT", bound="BaseAsyncAgentEventHandler") -BaseAgentEventHandlerT = TypeVar("BaseAgentEventHandlerT", bound="BaseAgentEventHandler") - - -async def async_chain(*iterators: AsyncIterator[T]) -> AsyncIterator[T]: - for iterator in iterators: - async for item in iterator: - yield item - - -class BaseAsyncAgentEventHandler(AsyncIterator[T]): - - def __init__(self) -> None: - self.response_iterator: Optional[AsyncIterator[bytes]] = None - self.submit_tool_outputs: Optional[ - Callable[[ThreadRun, "BaseAsyncAgentEventHandler[T]", bool], Awaitable[Any]] - ] = None - self.buffer: Optional[bytes] = None - - def initialize( - self, - response_iterator: AsyncIterator[bytes], - submit_tool_outputs: Callable[[ThreadRun, "BaseAsyncAgentEventHandler[T]", bool], Awaitable[Any]], - ): - self.response_iterator = ( - async_chain(self.response_iterator, response_iterator) if self.response_iterator else response_iterator - ) - self.submit_tool_outputs = submit_tool_outputs - - # cspell:disable-next-line - async def __anext__(self) -> T: - # cspell:disable-next-line - event_bytes = await self.__anext_impl__() - return await self._process_event(event_bytes.decode("utf-8")) - - # cspell:disable-next-line - async def __anext_impl__(self) -> bytes: - self.buffer = b"" if self.buffer is None else self.buffer - if self.response_iterator is None: - raise ValueError("The response handler was not initialized.") - - if not b"\n\n" in self.buffer: - async for chunk in self.response_iterator: - self.buffer += chunk - if b"\n\n" in self.buffer: - break - - if self.buffer == b"": - raise StopAsyncIteration() - - event_bytes = b"" - if b"\n\n" in self.buffer: - event_end_index = self.buffer.index(b"\n\n") - event_bytes = self.buffer[:event_end_index] - self.buffer = self.buffer[event_end_index:].lstrip() - else: - event_bytes = self.buffer - self.buffer = b"" - - return event_bytes - - async def _process_event(self, event_data_str: str) -> T: - raise NotImplementedError("This method needs to be implemented.") - - async def until_done(self) -> None: - """ - Iterates through all events until the stream is marked as done. - Calls the provided callback function with each event data. - """ - try: - async for _ in self: - pass - except StopAsyncIteration: - pass - - -class BaseAgentEventHandler(Iterator[T]): - - def __init__(self) -> None: - self.response_iterator: Optional[Iterator[bytes]] = None - self.submit_tool_outputs: Optional[Callable[[ThreadRun, "BaseAgentEventHandler[T]", bool], Any]] - self.buffer: Optional[bytes] = None - - def initialize( - self, - response_iterator: Iterator[bytes], - submit_tool_outputs: Callable[[ThreadRun, "BaseAgentEventHandler[T]", bool], Any], - ) -> None: - self.response_iterator = ( - itertools.chain(self.response_iterator, response_iterator) if self.response_iterator else response_iterator - ) - self.submit_tool_outputs = submit_tool_outputs - - def __next__(self) -> T: - event_bytes = self.__next_impl__() - return self._process_event(event_bytes.decode("utf-8")) - - def __next_impl__(self) -> bytes: - self.buffer = b"" if self.buffer is None else self.buffer - if self.response_iterator is None: - raise ValueError("The response handler was not initialized.") - - if not b"\n\n" in self.buffer: - for chunk in self.response_iterator: - self.buffer += chunk - if b"\n\n" in self.buffer: - break - - if self.buffer == b"": - raise StopIteration() - - event_bytes = b"" - if b"\n\n" in self.buffer: - event_end_index = self.buffer.index(b"\n\n") - event_bytes = self.buffer[:event_end_index] - self.buffer = self.buffer[event_end_index:].lstrip() - else: - event_bytes = self.buffer - self.buffer = b"" - - return event_bytes - - def _process_event(self, event_data_str: str) -> T: - raise NotImplementedError("This method needs to be implemented.") - - def until_done(self) -> None: - """ - Iterates through all events until the stream is marked as done. - Calls the provided callback function with each event data. - """ - try: - for _ in self: - pass - except StopIteration: - pass - - -class AsyncAgentEventHandler(BaseAsyncAgentEventHandler[Tuple[str, StreamEventData, Optional[EventFunctionReturnT]]]): - def __init__(self) -> None: - super().__init__() - self._max_retry = 10 - self.current_retry = 0 - - def set_max_retry(self, max_retry: int) -> None: - """ - Set the maximum number of retries for tool output submission. - - :param int max_retry: The maximum number of retries. - """ - self._max_retry = max_retry - - async def _process_event(self, event_data_str: str) -> Tuple[str, StreamEventData, Optional[EventFunctionReturnT]]: - - event_type, event_data_obj = _parse_event(event_data_str) - if ( - isinstance(event_data_obj, ThreadRun) - and event_data_obj.status == "requires_action" - and isinstance(event_data_obj.required_action, SubmitToolOutputsAction) - ): - tool_output = await cast( - Callable[[ThreadRun, "BaseAsyncAgentEventHandler", bool], Awaitable[Any]], self.submit_tool_outputs - )(event_data_obj, self, self.current_retry < self._max_retry) - - if _has_errors_in_toolcalls_output(tool_output): - self.current_retry += 1 - - func_rt: Optional[EventFunctionReturnT] = None - try: - if isinstance(event_data_obj, MessageDeltaChunk): - func_rt = await self.on_message_delta(event_data_obj) - elif isinstance(event_data_obj, ThreadMessage): - func_rt = await self.on_thread_message(event_data_obj) - elif isinstance(event_data_obj, ThreadRun): - func_rt = await self.on_thread_run(event_data_obj) - elif isinstance(event_data_obj, RunStep): - func_rt = await self.on_run_step(event_data_obj) - elif isinstance(event_data_obj, RunStepDeltaChunk): - func_rt = await self.on_run_step_delta(event_data_obj) - elif event_type == AgentStreamEvent.ERROR: - func_rt = await self.on_error(event_data_obj) - elif event_type == AgentStreamEvent.DONE: - func_rt = await self.on_done() - else: - func_rt = await self.on_unhandled_event( - event_type, event_data_obj - ) # pylint: disable=assignment-from-none - except Exception as e: # pylint: disable=broad-exception-caught - logging.error("Error in event handler for event '%s': %s", event_type, e) - return event_type, event_data_obj, func_rt - - async def on_message_delta( - self, delta: "MessageDeltaChunk" # pylint: disable=unused-argument - ) -> Optional[EventFunctionReturnT]: - """Handle message delta events. - - :param MessageDeltaChunk delta: The message delta. - :rtype: Optional[EventFunctionReturnT] - """ - return None - - async def on_thread_message( - self, message: "ThreadMessage" # pylint: disable=unused-argument - ) -> Optional[EventFunctionReturnT]: - """Handle thread message events. - - :param ThreadMessage message: The thread message. - :rtype: Optional[EventFunctionReturnT] - """ - return None - - async def on_thread_run( - self, run: "ThreadRun" # pylint: disable=unused-argument - ) -> Optional[EventFunctionReturnT]: - """Handle thread run events. - - :param ThreadRun run: The thread run. - :rtype: Optional[EventFunctionReturnT] - """ - return None - - async def on_run_step(self, step: "RunStep") -> Optional[EventFunctionReturnT]: # pylint: disable=unused-argument - """Handle run step events. - - :param RunStep step: The run step. - :rtype: Optional[EventFunctionReturnT] - """ - return None - - async def on_run_step_delta( - self, delta: "RunStepDeltaChunk" # pylint: disable=unused-argument - ) -> Optional[EventFunctionReturnT]: - """Handle run step delta events. - - :param RunStepDeltaChunk delta: The run step delta. - :rtype: Optional[EventFunctionReturnT] - """ - return None - - async def on_error(self, data: str) -> Optional[EventFunctionReturnT]: # pylint: disable=unused-argument - """Handle error events. - - :param str data: The error event's data. - :rtype: Optional[EventFunctionReturnT] - """ - return None - - async def on_done( - self, - ) -> Optional[EventFunctionReturnT]: - """Handle the completion of the stream. - :rtype: Optional[EventFunctionReturnT] - """ - return None - - async def on_unhandled_event( - self, event_type: str, event_data: str # pylint: disable=unused-argument - ) -> Optional[EventFunctionReturnT]: - """Handle any unhandled event types. - - :param str event_type: The event type. - :param Any event_data: The event's data. - :rtype: Optional[EventFunctionReturnT] - """ - return None - - -class AgentEventHandler(BaseAgentEventHandler[Tuple[str, StreamEventData, Optional[EventFunctionReturnT]]]): - def __init__(self) -> None: - super().__init__() - self._max_retry = 10 - self.current_retry = 0 - - def set_max_retry(self, max_retry: int) -> None: - """ - Set the maximum number of retries for tool output submission. - - :param int max_retry: The maximum number of retries. - """ - self._max_retry = max_retry - - def _process_event(self, event_data_str: str) -> Tuple[str, StreamEventData, Optional[EventFunctionReturnT]]: - - event_type, event_data_obj = _parse_event(event_data_str) - if ( - isinstance(event_data_obj, ThreadRun) - and event_data_obj.status == "requires_action" - and isinstance(event_data_obj.required_action, SubmitToolOutputsAction) - ): - tool_output = cast(Callable[[ThreadRun, "BaseAgentEventHandler", bool], Any], self.submit_tool_outputs)( - event_data_obj, self, self.current_retry < self._max_retry - ) - - if _has_errors_in_toolcalls_output(tool_output): - self.current_retry += 1 - - func_rt: Optional[EventFunctionReturnT] = None - try: - if isinstance(event_data_obj, MessageDeltaChunk): - func_rt = self.on_message_delta(event_data_obj) # pylint: disable=assignment-from-none - elif isinstance(event_data_obj, ThreadMessage): - func_rt = self.on_thread_message(event_data_obj) # pylint: disable=assignment-from-none - elif isinstance(event_data_obj, ThreadRun): - func_rt = self.on_thread_run(event_data_obj) # pylint: disable=assignment-from-none - elif isinstance(event_data_obj, RunStep): - func_rt = self.on_run_step(event_data_obj) # pylint: disable=assignment-from-none - elif isinstance(event_data_obj, RunStepDeltaChunk): - func_rt = self.on_run_step_delta(event_data_obj) # pylint: disable=assignment-from-none - elif event_type == AgentStreamEvent.ERROR: - func_rt = self.on_error(event_data_obj) # pylint: disable=assignment-from-none - elif event_type == AgentStreamEvent.DONE: - func_rt = self.on_done() # pylint: disable=assignment-from-none - else: - func_rt = self.on_unhandled_event(event_type, event_data_obj) # pylint: disable=assignment-from-none - except Exception as e: # pylint: disable=broad-exception-caught - logging.error("Error in event handler for event '%s': %s", event_type, e) - return event_type, event_data_obj, func_rt - - def on_message_delta( - self, delta: "MessageDeltaChunk" # pylint: disable=unused-argument - ) -> Optional[EventFunctionReturnT]: - """Handle message delta events. - - :param MessageDeltaChunk delta: The message delta. - :rtype: Optional[EventFunctionReturnT] - """ - return None - - def on_thread_message( - self, message: "ThreadMessage" # pylint: disable=unused-argument - ) -> Optional[EventFunctionReturnT]: - """Handle thread message events. - - :param ThreadMessage message: The thread message. - :rtype: Optional[EventFunctionReturnT] - """ - return None - - def on_thread_run(self, run: "ThreadRun") -> Optional[EventFunctionReturnT]: # pylint: disable=unused-argument - """Handle thread run events. - - :param ThreadRun run: The thread run. - :rtype: Optional[EventFunctionReturnT] - """ - return None - - def on_run_step(self, step: "RunStep") -> Optional[EventFunctionReturnT]: # pylint: disable=unused-argument - """Handle run step events. - - :param RunStep step: The run step. - :rtype: Optional[EventFunctionReturnT] - """ - return None - - def on_run_step_delta( - self, delta: "RunStepDeltaChunk" # pylint: disable=unused-argument - ) -> Optional[EventFunctionReturnT]: - """Handle run step delta events. - - :param RunStepDeltaChunk delta: The run step delta. - :rtype: Optional[EventFunctionReturnT] - """ - return None - - def on_error(self, data: str) -> Optional[EventFunctionReturnT]: # pylint: disable=unused-argument - """Handle error events. - - :param str data: The error event's data. - :rtype: Optional[EventFunctionReturnT] - """ - return None - - def on_done( - self, - ) -> Optional[EventFunctionReturnT]: - """Handle the completion of the stream.""" - return None - - def on_unhandled_event( - self, event_type: str, event_data: str # pylint: disable=unused-argument - ) -> Optional[EventFunctionReturnT]: - """Handle any unhandled event types. - - :param str event_type: The event type. - :param Any event_data: The event's data. - """ - return None - - -class AsyncAgentRunStream(Generic[BaseAsyncAgentEventHandlerT]): - def __init__( - self, - response_iterator: AsyncIterator[bytes], - submit_tool_outputs: Callable[[ThreadRun, BaseAsyncAgentEventHandlerT, bool], Awaitable[Any]], - event_handler: BaseAsyncAgentEventHandlerT, - ): - self.response_iterator = response_iterator - self.event_handler = event_handler - self.submit_tool_outputs = submit_tool_outputs - self.event_handler.initialize( - self.response_iterator, - cast(Callable[[ThreadRun, BaseAsyncAgentEventHandler, bool], Awaitable[Any]], submit_tool_outputs), - ) - - async def __aenter__(self): - return self.event_handler - - async def __aexit__(self, exc_type, exc_val, exc_tb): - close_method = getattr(self.response_iterator, "close", None) - if callable(close_method): - result = close_method() - if asyncio.iscoroutine(result): - await result - - -class AgentRunStream(Generic[BaseAgentEventHandlerT]): - def __init__( - self, - response_iterator: Iterator[bytes], - submit_tool_outputs: Callable[[ThreadRun, BaseAgentEventHandlerT, bool], Any], - event_handler: BaseAgentEventHandlerT, - ): - self.response_iterator = response_iterator - self.event_handler = event_handler - self.submit_tool_outputs = submit_tool_outputs - self.event_handler.initialize( - self.response_iterator, - cast(Callable[[ThreadRun, BaseAgentEventHandler, bool], Any], submit_tool_outputs), - ) - - def __enter__(self): - return self.event_handler - - def __exit__(self, exc_type, exc_val, exc_tb): - close_method = getattr(self.response_iterator, "close", None) - if callable(close_method): - close_method() - - -class OpenAIPageableListOfThreadMessage(OpenAIPageableListOfThreadMessageGenerated): - - @property - def text_messages(self) -> List[MessageTextContent]: - """Returns all text message contents in the messages. - - :rtype: List[MessageTextContent] - """ - texts = [content for msg in self.data for content in msg.text_messages] - return texts - - @property - def image_contents(self) -> List[MessageImageFileContent]: - """Returns all image file contents from image message contents in the messages. - - :rtype: List[MessageImageFileContent] - """ - return [content for msg in self.data for content in msg.image_contents] - - @property - def file_citation_annotations(self) -> List[MessageTextFileCitationAnnotation]: - """Returns all file citation annotations from text message annotations in the messages. - - :rtype: List[MessageTextFileCitationAnnotation] - """ - annotations = [annotation for msg in self.data for annotation in msg.file_citation_annotations] - return annotations - - @property - def file_path_annotations(self) -> List[MessageTextFilePathAnnotation]: - """Returns all file path annotations from text message annotations in the messages. - - :rtype: List[MessageTextFilePathAnnotation] - """ - annotations = [annotation for msg in self.data for annotation in msg.file_path_annotations] - return annotations - - def get_last_message_by_role(self, role: MessageRole) -> Optional[ThreadMessage]: - """Returns the last message from a sender in the specified role. - - :param role: The role of the sender. - :type role: MessageRole - - :return: The last message from a sender in the specified role. - :rtype: ~azure.ai.projects.models.ThreadMessage - """ - for msg in self.data: - if msg.role == role: - return msg - return None - - def get_last_text_message_by_role(self, role: MessageRole) -> Optional[MessageTextContent]: - """Returns the last text message from a sender in the specified role. - - :param role: The role of the sender. - :type role: MessageRole - - :return: The last text message from a sender in the specified role. - :rtype: ~azure.ai.projects.models.MessageTextContent - """ - for msg in self.data: - if msg.role == role: - for content in msg.content: - if isinstance(content, MessageTextContent): - return content - return None - - -__all__: List[str] = [ - "AgentEventHandler", - "AgentRunStream", - "AsyncAgentRunStream", - "AsyncFunctionTool", - "AsyncToolSet", - "AzureAISearchTool", - "AzureFunctionTool", - "BaseAsyncAgentEventHandler", - "BaseAgentEventHandler", - "CodeInterpreterTool", - "ConnectedAgentTool", - "ConnectionProperties", - "AsyncAgentEventHandler", - "OpenAIPageableListOfThreadMessage", - "FileSearchTool", - "FunctionTool", - "OpenApiTool", - "BingCustomSearchTool", - "BingGroundingTool", - "StreamEventData", - "SharepointTool", - "FabricTool", - "AzureAISearchTool", - "SASTokenCredential", - "Tool", - "ToolSet", - "BaseAsyncAgentEventHandlerT", - "BaseAgentEventHandlerT", - "ThreadMessage", - "MessageTextFileCitationAnnotation", - "MessageDeltaChunk", - "MessageAttachment", -] # Add all objects you want publicly available to users at this package level +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/__init__.py b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/__init__.py index 64c4031e2bb6..c8b497b4854b 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/operations/__init__.py +++ b/sdk/ai/azure-ai-projects/azure/ai/projects/operations/__init__.py @@ -12,20 +12,26 @@ if TYPE_CHECKING: from ._patch import * # pylint: disable=unused-wildcard-import -from ._operations import AgentsOperations # type: ignore +from ._operations import ServicePatternsOperations # type: ignore from ._operations import ConnectionsOperations # type: ignore -from ._operations import TelemetryOperations # type: ignore from ._operations import EvaluationsOperations # type: ignore +from ._operations import DatasetsOperations # type: ignore +from ._operations import IndexesOperations # type: ignore +from ._operations import DeploymentsOperations # type: ignore +from ._operations import RedTeamsOperations # type: ignore from ._patch import __all__ as _patch_all from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ - "AgentsOperations", + "ServicePatternsOperations", "ConnectionsOperations", - "TelemetryOperations", "EvaluationsOperations", + "DatasetsOperations", + "IndexesOperations", + "DeploymentsOperations", + "RedTeamsOperations", ] __all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() 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 ce28ebedca8b..5579193b90c4 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 @@ -1,4 +1,4 @@ -# pylint: disable=line-too-long,useless-suppression,too-many-lines +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -9,7 +9,7 @@ from collections.abc import MutableMapping from io import IOBase import json -from typing import Any, Callable, Dict, IO, Iterable, Iterator, List, Optional, TYPE_CHECKING, TypeVar, Union, overload +from typing import Any, Callable, Dict, IO, Iterable, List, Optional, TypeVar, Union, overload import urllib.parse from azure.core import PipelineClient @@ -29,72 +29,37 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .. import _model_base, models as _models +from .. import models as _models from .._configuration import AIProjectClientConfiguration -from .._model_base import SdkJSONEncoder, _deserialize -from .._serialization import Deserializer, Serializer -from .._vendor import prepare_multipart_form_data +from .._utils.model_base import SdkJSONEncoder, _deserialize +from .._utils.serialization import Deserializer, Serializer +from .._validation import api_version_validation -if TYPE_CHECKING: - from .. import _types -JSON = MutableMapping[str, Any] -_Unset: Any = object() T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] +JSON = MutableMapping[str, Any] _SERIALIZER = Serializer() _SERIALIZER.client_side_validation = False -def build_agents_create_agent_request(**kwargs: Any) -> HttpRequest: +def build_connections_get_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", "2024-07-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/assistants" - - # 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_agents_list_agents_request( - *, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = 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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") + _url = "/connections/{name}" + path_format_arguments = { + "name": _SERIALIZER.url("name", name, "str"), + } - # Construct URL - _url = "/assistants" + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "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") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -102,17 +67,19 @@ def build_agents_list_agents_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_get_agent_request(agent_id: str, **kwargs: Any) -> HttpRequest: +def build_connections_get_with_credentials_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 {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/assistants/{assistantId}" + _url = "/connections/{name}/getConnectionWithCredentials" path_format_arguments = { - "assistantId": _SERIALIZER.url("agent_id", agent_id, "str"), + "name": _SERIALIZER.url("name", name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -123,47 +90,57 @@ def build_agents_get_agent_request(agent_id: 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_agents_update_agent_request(agent_id: str, **kwargs: Any) -> HttpRequest: +def build_connections_list_request( + *, + connection_type: Optional[Union[str, _models.ConnectionType]] = None, + default_connection: Optional[bool] = None, + top: Optional[int] = None, + skip: Optional[int] = None, + maxpagesize: Optional[int] = None, + **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/assistants/{assistantId}" - path_format_arguments = { - "assistantId": _SERIALIZER.url("agent_id", agent_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore + _url = "/connections" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if connection_type is not None: + _params["connectionType"] = _SERIALIZER.query("connection_type", connection_type, "str") + if default_connection is not None: + _params["defaultConnection"] = _SERIALIZER.query("default_connection", default_connection, "bool") + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + if skip is not None: + _params["skip"] = _SERIALIZER.query("skip", skip, "int") + if maxpagesize is not None: + _params["maxpagesize"] = _SERIALIZER.query("maxpagesize", maxpagesize, "int") # Construct headers - 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_agents_delete_agent_request(agent_id: str, **kwargs: Any) -> HttpRequest: +def build_evaluations_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", "2024-07-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/assistants/{assistantId}" + _url = "/evaluations/runs/{name}" path_format_arguments = { - "assistantId": _SERIALIZER.url("agent_id", agent_id, "str"), + "name": _SERIALIZER.url("name", name, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -174,70 +151,68 @@ def build_agents_delete_agent_request(agent_id: str, **kwargs: Any) -> HttpReque # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_create_thread_request(**kwargs: Any) -> HttpRequest: +def build_evaluations_list_request( + *, top: Optional[int] = None, skip: Optional[int] = None, maxpagesize: Optional[int] = None, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/threads" + _url = "/evaluations/runs" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + if skip is not None: + _params["skip"] = _SERIALIZER.query("skip", skip, "int") + if maxpagesize is not None: + _params["maxpagesize"] = _SERIALIZER.query("maxpagesize", maxpagesize, "int") # Construct headers - 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_agents_get_thread_request(thread_id: str, **kwargs: Any) -> HttpRequest: +def build_evaluations_create_run_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/threads/{threadId}" - path_format_arguments = { - "threadId": _SERIALIZER.url("thread_id", thread_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore + _url = "/evaluations/runs:run" # 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_agents_update_thread_request(thread_id: str, **kwargs: Any) -> HttpRequest: +def build_evaluations_create_agent_evaluation_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: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/threads/{threadId}" - path_format_arguments = { - "threadId": _SERIALIZER.url("thread_id", thread_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore + _url = "/evaluations/runs:runAgent" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -250,57 +225,52 @@ def build_agents_update_thread_request(thread_id: str, **kwargs: Any) -> HttpReq return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_delete_thread_request(thread_id: str, **kwargs: Any) -> HttpRequest: +def build_datasets_list_versions_request( + name: str, *, continuation_token_parameter: 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", "2024-07-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/threads/{threadId}" + _url = "/datasets/{name}/versions" path_format_arguments = { - "threadId": _SERIALIZER.url("thread_id", thread_id, "str"), + "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 continuation_token_parameter is not None: + _params["continuationToken"] = _SERIALIZER.query( + "continuation_token_parameter", continuation_token_parameter, "str" + ) # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_list_threads_request( - *, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: +def build_datasets_list_request(*, continuation_token_parameter: 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", "2024-07-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/threads" + _url = "/datasets" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "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") + if continuation_token_parameter is not None: + _params["continuationToken"] = _SERIALIZER.query( + "continuation_token_parameter", continuation_token_parameter, "str" + ) # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -308,18 +278,18 @@ def build_agents_list_threads_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_create_message_request(thread_id: str, **kwargs: Any) -> HttpRequest: +def build_datasets_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 {}) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/threads/{threadId}/messages" + _url = "/datasets/{name}/versions/{version}" path_format_arguments = { - "threadId": _SERIALIZER.url("thread_id", thread_id, "str"), + "name": _SERIALIZER.url("name", name, "str"), + "version": _SERIALIZER.url("version", version, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -328,68 +298,49 @@ def build_agents_create_message_request(thread_id: str, **kwargs: Any) -> HttpRe _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_agents_list_messages_request( - thread_id: str, - *, - run_id: Optional[str] = None, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: +def build_datasets_delete_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", "2024-07-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/threads/{threadId}/messages" + _url = "/datasets/{name}/versions/{version}" path_format_arguments = { - "threadId": _SERIALIZER.url("thread_id", thread_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 run_id is not None: - _params["run_id"] = _SERIALIZER.query("run_id", run_id, "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") # 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_agents_get_message_request(thread_id: str, message_id: str, **kwargs: Any) -> HttpRequest: +def build_datasets_create_or_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 {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/threads/{threadId}/messages/{messageId}" + _url = "/datasets/{name}/versions/{version}" path_format_arguments = { - "threadId": _SERIALIZER.url("thread_id", thread_id, "str"), - "messageId": _SERIALIZER.url("message_id", message_id, "str"), + "name": _SERIALIZER.url("name", name, "str"), + "version": _SERIALIZER.url("version", version, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -398,24 +349,26 @@ def build_agents_get_message_request(thread_id: str, message_id: str, **kwargs: _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="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_update_message_request(thread_id: str, message_id: str, **kwargs: Any) -> HttpRequest: +def build_datasets_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", "2024-07-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/threads/{threadId}/messages/{messageId}" + _url = "/datasets/{name}/versions/{version}/startPendingUpload" path_format_arguments = { - "threadId": _SERIALIZER.url("thread_id", thread_id, "str"), - "messageId": _SERIALIZER.url("message_id", message_id, "str"), + "name": _SERIALIZER.url("name", name, "str"), + "version": _SERIALIZER.url("version", version, "str"), } _url: str = _url.format(**path_format_arguments) # type: ignore @@ -431,70 +384,56 @@ def build_agents_update_message_request(thread_id: str, message_id: str, **kwarg return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_create_run_request( - thread_id: str, *, include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, **kwargs: Any -) -> HttpRequest: +def build_datasets_get_credentials_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", "2024-07-01-preview")) + content_type: str = kwargs.pop("content_type") + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/threads/{threadId}/runs" + _url = "/datasets/{name}/versions/{version}/credentials" path_format_arguments = { - "threadId": _SERIALIZER.url("thread_id", thread_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 include is not None: - _params["include[]"] = _SERIALIZER.query("include", include, "[str]", div=",") # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _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_agents_list_runs_request( - thread_id: str, - *, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any +def build_indexes_list_versions_request( + name: str, *, continuation_token_parameter: 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", "2024-07-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/threads/{threadId}/runs" + _url = "/indexes/{name}/versions" path_format_arguments = { - "threadId": _SERIALIZER.url("thread_id", thread_id, "str"), + "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 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 continuation_token_parameter is not None: + _params["continuationToken"] = _SERIALIZER.query( + "continuation_token_parameter", continuation_token_parameter, "str" + ) # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -502,24 +441,22 @@ def build_agents_list_runs_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_get_run_request(thread_id: str, run_id: str, **kwargs: Any) -> HttpRequest: +def build_indexes_list_request(*, continuation_token_parameter: 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", "2024-07-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/threads/{threadId}/runs/{runId}" - path_format_arguments = { - "threadId": _SERIALIZER.url("thread_id", thread_id, "str"), - "runId": _SERIALIZER.url("run_id", run_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore + _url = "/indexes" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + if continuation_token_parameter is not None: + _params["continuationToken"] = _SERIALIZER.query( + "continuation_token_parameter", continuation_token_parameter, "str" + ) # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -527,19 +464,18 @@ def build_agents_get_run_request(thread_id: str, run_id: str, **kwargs: Any) -> return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_update_run_request(thread_id: str, run_id: str, **kwargs: Any) -> HttpRequest: +def build_indexes_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 {}) - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/threads/{threadId}/runs/{runId}" + _url = "/indexes/{name}/versions/{version}" path_format_arguments = { - "threadId": _SERIALIZER.url("thread_id", thread_id, "str"), - "runId": _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 @@ -548,28 +484,23 @@ def build_agents_update_run_request(thread_id: str, run_id: str, **kwargs: Any) _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_agents_submit_tool_outputs_to_run_request( # pylint: disable=name-too-long - thread_id: str, run_id: str, **kwargs: Any -) -> HttpRequest: +def build_indexes_delete_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", "2024-07-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/threads/{threadId}/runs/{runId}/submit_tool_outputs" + _url = "/indexes/{name}/versions/{version}" path_format_arguments = { - "threadId": _SERIALIZER.url("thread_id", thread_id, "str"), - "runId": _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 @@ -578,25 +509,24 @@ def build_agents_submit_tool_outputs_to_run_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="POST", url=_url, params=_params, headers=_headers, **kwargs) + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_cancel_run_request(thread_id: str, run_id: str, **kwargs: Any) -> HttpRequest: +def build_indexes_create_or_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 {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/threads/{threadId}/runs/{runId}/cancel" + _url = "/indexes/{name}/versions/{version}" path_format_arguments = { - "threadId": _SERIALIZER.url("thread_id", thread_id, "str"), - "runId": _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 @@ -605,61 +535,70 @@ def build_agents_cancel_run_request(thread_id: str, run_id: str, **kwargs: Any) _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="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_create_thread_and_run_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long +def build_deployments_get_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", "2024-07-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/threads/runs" + _url = "/deployments/{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) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_get_run_step_request( - thread_id: str, - run_id: str, - step_id: str, +def build_deployments_list_request( *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, + model_publisher: Optional[str] = None, + model_name: Optional[str] = None, + deployment_type: Optional[Union[str, _models.DeploymentType]] = None, + top: Optional[int] = None, + skip: Optional[int] = None, + maxpagesize: Optional[int] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/threads/{threadId}/runs/{runId}/steps/{stepId}" - path_format_arguments = { - "threadId": _SERIALIZER.url("thread_id", thread_id, "str"), - "runId": _SERIALIZER.url("run_id", run_id, "str"), - "stepId": _SERIALIZER.url("step_id", step_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore + _url = "/deployments" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if include is not None: - _params["include[]"] = _SERIALIZER.query("include", include, "[str]", div=",") + if model_publisher is not None: + _params["modelPublisher"] = _SERIALIZER.query("model_publisher", model_publisher, "str") + if model_name is not None: + _params["modelName"] = _SERIALIZER.query("model_name", model_name, "str") + if deployment_type is not None: + _params["deploymentType"] = _SERIALIZER.query("deployment_type", deployment_type, "str") + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + if skip is not None: + _params["skip"] = _SERIALIZER.query("skip", skip, "int") + if maxpagesize is not None: + _params["maxpagesize"] = _SERIALIZER.query("maxpagesize", maxpagesize, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -667,44 +606,23 @@ def build_agents_get_run_step_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_list_run_steps_request( - thread_id: str, - run_id: str, - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: +def build_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 {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/threads/{threadId}/runs/{runId}/steps" + _url = "/redTeams/runs/{name}" path_format_arguments = { - "threadId": _SERIALIZER.url("thread_id", thread_id, "str"), - "runId": _SERIALIZER.url("run_id", run_id, "str"), + "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 include is not None: - _params["include[]"] = _SERIALIZER.query("include", include, "[str]", div=",") - 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") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -712,22 +630,26 @@ def build_agents_list_run_steps_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_list_files_request( - *, purpose: Optional[Union[str, _models.FilePurpose]] = None, **kwargs: Any +def build_red_teams_list_request( + *, top: Optional[int] = None, skip: Optional[int] = None, maxpagesize: Optional[int] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01-preview")) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/files" + _url = "/redTeams/runs" # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if purpose is not None: - _params["purpose"] = _SERIALIZER.query("purpose", purpose, "str") + if top is not None: + _params["top"] = _SERIALIZER.query("top", top, "int") + if skip is not None: + _params["skip"] = _SERIALIZER.query("skip", skip, "int") + if maxpagesize is not None: + _params["maxpagesize"] = _SERIALIZER.query("maxpagesize", maxpagesize, "int") # Construct headers _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") @@ -735,4963 +657,103 @@ def build_agents_list_files_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_agents_upload_file_request(**kwargs: Any) -> HttpRequest: +def build_red_teams_create_run_request(**kwargs: Any) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01-preview")) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2025-05-15-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL - _url = "/files" + _url = "/redTeams/runs:run" # 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_agents_delete_file_request(file_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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/files/{fileId}" - path_format_arguments = { - "fileId": _SERIALIZER.url("file_id", file_id, "str"), - } +class ServicePatternsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. - _url: str = _url.format(**path_format_arguments) # type: ignore + Instead, you should access the following operations through + :class:`~azure.ai.projects.AIProjectClient`'s + :attr:`service_patterns` attribute. + """ - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + def __init__(self, *args, **kwargs): + 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") - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) +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 build_agents_get_file_request(file_id: 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): + 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") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") + @distributed_trace + def _get(self, name: str, **kwargs: Any) -> _models.Connection: + """Get a connection by name, without populating connection credentials. - # Construct URL - _url = "/files/{fileId}" - path_format_arguments = { - "fileId": _SERIALIZER.url("file_id", file_id, "str"), - } + :param name: The name of the resource. 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 {}) - _url: str = _url.format(**path_format_arguments) # type: ignore + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + cls: ClsType[_models.Connection] = kwargs.pop("cls", None) - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + _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) - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - -def build_agents_get_file_content_request(file_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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/octet-stream") - - # Construct URL - _url = "/files/{fileId}/content" - path_format_arguments = { - "fileId": _SERIALIZER.url("file_id", file_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_agents_list_vector_stores_request( - *, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = 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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/vector_stores" - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "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") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_agents_create_vector_store_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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/vector_stores" - - # 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_agents_get_vector_store_request(vector_store_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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/vector_stores/{vectorStoreId}" - path_format_arguments = { - "vectorStoreId": _SERIALIZER.url("vector_store_id", vector_store_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_agents_modify_vector_store_request(vector_store_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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/vector_stores/{vectorStoreId}" - path_format_arguments = { - "vectorStoreId": _SERIALIZER.url("vector_store_id", vector_store_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) - - -def build_agents_delete_vector_store_request(vector_store_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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/vector_stores/{vectorStoreId}" - path_format_arguments = { - "vectorStoreId": _SERIALIZER.url("vector_store_id", vector_store_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="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_agents_list_vector_store_files_request( # pylint: disable=name-too-long - vector_store_id: str, - *, - filter: Optional[Union[str, _models.VectorStoreFileStatusFilter]] = None, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = 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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/vector_stores/{vectorStoreId}/files" - path_format_arguments = { - "vectorStoreId": _SERIALIZER.url("vector_store_id", vector_store_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - 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") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_agents_create_vector_store_file_request( # pylint: disable=name-too-long - vector_store_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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/vector_stores/{vectorStoreId}/files" - path_format_arguments = { - "vectorStoreId": _SERIALIZER.url("vector_store_id", vector_store_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) - - -def build_agents_get_vector_store_file_request( # pylint: disable=name-too-long - vector_store_id: str, file_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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/vector_stores/{vectorStoreId}/files/{fileId}" - path_format_arguments = { - "vectorStoreId": _SERIALIZER.url("vector_store_id", vector_store_id, "str"), - "fileId": _SERIALIZER.url("file_id", file_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_agents_delete_vector_store_file_request( # pylint: disable=name-too-long - vector_store_id: str, file_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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/vector_stores/{vectorStoreId}/files/{fileId}" - path_format_arguments = { - "vectorStoreId": _SERIALIZER.url("vector_store_id", vector_store_id, "str"), - "fileId": _SERIALIZER.url("file_id", file_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="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_agents_create_vector_store_file_batch_request( # pylint: disable=name-too-long - vector_store_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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/vector_stores/{vectorStoreId}/file_batches" - path_format_arguments = { - "vectorStoreId": _SERIALIZER.url("vector_store_id", vector_store_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) - - -def build_agents_get_vector_store_file_batch_request( # pylint: disable=name-too-long - vector_store_id: str, batch_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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/vector_stores/{vectorStoreId}/file_batches/{batchId}" - path_format_arguments = { - "vectorStoreId": _SERIALIZER.url("vector_store_id", vector_store_id, "str"), - "batchId": _SERIALIZER.url("batch_id", batch_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_agents_cancel_vector_store_file_batch_request( # pylint: disable=name-too-long - vector_store_id: str, batch_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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/vector_stores/{vectorStoreId}/file_batches/{batchId}/cancel" - path_format_arguments = { - "vectorStoreId": _SERIALIZER.url("vector_store_id", vector_store_id, "str"), - "batchId": _SERIALIZER.url("batch_id", batch_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_agents_list_vector_store_file_batch_files_request( # pylint: disable=name-too-long - vector_store_id: str, - batch_id: str, - *, - filter: Optional[Union[str, _models.VectorStoreFileStatusFilter]] = None, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = 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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/vector_stores/{vectorStoreId}/file_batches/{batchId}/files" - path_format_arguments = { - "vectorStoreId": _SERIALIZER.url("vector_store_id", vector_store_id, "str"), - "batchId": _SERIALIZER.url("batch_id", batch_id, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - 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") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_connections_get_workspace_request(**kwargs: Any) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/" - - # 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_connections_list_connections_request( # pylint: disable=name-too-long - *, - category: Optional[Union[str, _models.ConnectionType]] = None, - include_all: Optional[bool] = None, - target: 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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/connections" - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if category is not None: - _params["category"] = _SERIALIZER.query("category", category, "str") - if include_all is not None: - _params["includeAll"] = _SERIALIZER.query("include_all", include_all, "bool") - if target is not None: - _params["target"] = _SERIALIZER.query("target", target, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_connections_get_connection_request(connection_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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/connections/{connectionName}" - path_format_arguments = { - "connectionName": _SERIALIZER.url("connection_name", connection_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_connections_get_connection_with_secrets_request( # pylint: disable=name-too-long - connection_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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/connections/{connectionName}/listsecrets" - path_format_arguments = { - "connectionName": _SERIALIZER.url("connection_name", connection_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_telemetry_get_app_insights_request(app_insights_resource_url: 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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/{appInsightsResourceUrl}" - path_format_arguments = { - "appInsightsResourceUrl": _SERIALIZER.url("app_insights_resource_url", app_insights_resource_url, "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_evaluations_get_request(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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/evaluations/runs/{id}" - path_format_arguments = { - "id": _SERIALIZER.url("id", 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_evaluations_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("apiVersion", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/evaluations/runs:run" - - # Construct parameters - _params["apiVersion"] = _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_evaluations_list_request( - *, top: Optional[int] = None, skip: Optional[int] = None, maxpagesize: Optional[int] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/evaluations/runs" - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if top is not None: - _params["top"] = _SERIALIZER.query("top", top, "int") - if skip is not None: - _params["skip"] = _SERIALIZER.query("skip", skip, "int") - if maxpagesize is not None: - _params["maxpagesize"] = _SERIALIZER.query("maxpagesize", maxpagesize, "int") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_evaluations_update_request(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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/evaluations/runs/{id}" - path_format_arguments = { - "id": _SERIALIZER.url("id", 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="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_evaluations_get_schedule_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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/evaluations/schedules/{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_evaluations_create_or_replace_schedule_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", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/evaluations/schedules/{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="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_evaluations_list_schedule_request( - *, top: Optional[int] = None, skip: Optional[int] = None, maxpagesize: Optional[int] = None, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/evaluations/schedules" - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if top is not None: - _params["top"] = _SERIALIZER.query("top", top, "int") - if skip is not None: - _params["skip"] = _SERIALIZER.query("skip", skip, "int") - if maxpagesize is not None: - _params["maxpagesize"] = _SERIALIZER.query("maxpagesize", maxpagesize, "int") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_evaluations_disable_schedule_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 {}) - - api_version: str = kwargs.pop("api_version", _params.pop("apiVersion", "2024-07-01-preview")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/evaluations/schedules/{name}/disable" - path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["apiVersion"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -class AgentsOperations: # 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): - 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_agent( - self, - *, - model: str, - content_type: str = "application/json", - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.ToolResources] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.Agent: - """Creates a new agent. - - :keyword model: The ID of the model to use. Required. - :paramtype model: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword name: The name of the new agent. Default value is None. - :paramtype name: str - :keyword description: The description of the new agent. Default value is None. - :paramtype description: str - :keyword instructions: The system instructions for the new agent to use. Default value is None. - :paramtype instructions: str - :keyword tools: The collection of tools to enable for the new agent. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword tool_resources: A set of resources that are used by the agent's tools. The resources - are specific to the type of tool. For example, the ``code_interpreter`` - tool requires a list of file IDs, while the ``file_search`` tool requires a list of vector - store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output more random, - while lower values like 0.2 will make it more focused and deterministic. Default value is - None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword response_format: The response format of the tool calls used by this agent. Is one of - the following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat, ResponseFormatJsonSchemaType Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat or - ~azure.ai.projects.models.ResponseFormatJsonSchemaType - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_agent(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Agent: - """Creates a new agent. - - :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: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_agent(self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> _models.Agent: - """Creates a new agent. - - :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: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_agent( - self, - body: Union[JSON, IO[bytes]] = _Unset, - *, - model: str = _Unset, - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.ToolResources] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.Agent: - """Creates a new agent. - - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword model: The ID of the model to use. Required. - :paramtype model: str - :keyword name: The name of the new agent. Default value is None. - :paramtype name: str - :keyword description: The description of the new agent. Default value is None. - :paramtype description: str - :keyword instructions: The system instructions for the new agent to use. Default value is None. - :paramtype instructions: str - :keyword tools: The collection of tools to enable for the new agent. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword tool_resources: A set of resources that are used by the agent's tools. The resources - are specific to the type of tool. For example, the ``code_interpreter`` - tool requires a list of file IDs, while the ``file_search`` tool requires a list of vector - store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output more random, - while lower values like 0.2 will make it more focused and deterministic. Default value is - None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword response_format: The response format of the tool calls used by this agent. Is one of - the following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat, ResponseFormatJsonSchemaType Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat or - ~azure.ai.projects.models.ResponseFormatJsonSchemaType - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :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.Agent] = kwargs.pop("cls", None) - - if body is _Unset: - if model is _Unset: - raise TypeError("missing required argument: model") - body = { - "description": description, - "instructions": instructions, - "metadata": metadata, - "model": model, - "name": name, - "response_format": response_format, - "temperature": temperature, - "tool_resources": tool_resources, - "tools": tools, - "top_p": top_p, - } - 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_agent_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.Agent, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_agents( - self, - *, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any - ) -> _models.OpenAIPageableListOfAgent: - """Gets a list of agents that were previously created. - - :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.ListSortOrder - :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: OpenAIPageableListOfAgent. The OpenAIPageableListOfAgent is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIPageableListOfAgent - :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.OpenAIPageableListOfAgent] = kwargs.pop("cls", None) - - _request = build_agents_list_agents_request( - 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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.OpenAIPageableListOfAgent, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_agent(self, agent_id: str, **kwargs: Any) -> _models.Agent: - """Retrieves an existing agent. - - :param agent_id: Identifier of the agent. Required. - :type agent_id: str - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :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.Agent] = kwargs.pop("cls", None) - - _request = build_agents_get_agent_request( - agent_id=agent_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.Agent, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def update_agent( - self, - agent_id: str, - *, - content_type: str = "application/json", - model: Optional[str] = None, - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.ToolResources] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.Agent: - """Modifies an existing agent. - - :param agent_id: The ID of the agent to modify. Required. - :type agent_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword model: The ID of the model to use. Default value is None. - :paramtype model: str - :keyword name: The modified name for the agent to use. Default value is None. - :paramtype name: str - :keyword description: The modified description for the agent to use. Default value is None. - :paramtype description: str - :keyword instructions: The modified system instructions for the new agent to use. Default value - is None. - :paramtype instructions: str - :keyword tools: The modified collection of tools to enable for the agent. Default value is - None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword tool_resources: A set of resources that are used by the agent's tools. The resources - are specific to the type of tool. For example, - the ``code_interpreter`` tool requires a list of file IDs, while the ``file_search`` tool - requires a list of vector store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output more random, - while lower values like 0.2 will make it more focused and deterministic. Default value is - None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword response_format: The response format of the tool calls used by this agent. Is one of - the following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat, ResponseFormatJsonSchemaType Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat or - ~azure.ai.projects.models.ResponseFormatJsonSchemaType - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update_agent( - self, agent_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Agent: - """Modifies an existing agent. - - :param agent_id: The ID of the agent to modify. Required. - :type agent_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: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update_agent( - self, agent_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Agent: - """Modifies an existing agent. - - :param agent_id: The ID of the agent to modify. Required. - :type agent_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: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def update_agent( - self, - agent_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - model: Optional[str] = None, - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.ToolResources] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.Agent: - """Modifies an existing agent. - - :param agent_id: The ID of the agent to modify. Required. - :type agent_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword model: The ID of the model to use. Default value is None. - :paramtype model: str - :keyword name: The modified name for the agent to use. Default value is None. - :paramtype name: str - :keyword description: The modified description for the agent to use. Default value is None. - :paramtype description: str - :keyword instructions: The modified system instructions for the new agent to use. Default value - is None. - :paramtype instructions: str - :keyword tools: The modified collection of tools to enable for the agent. Default value is - None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword tool_resources: A set of resources that are used by the agent's tools. The resources - are specific to the type of tool. For example, - the ``code_interpreter`` tool requires a list of file IDs, while the ``file_search`` tool - requires a list of vector store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output more random, - while lower values like 0.2 will make it more focused and deterministic. Default value is - None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword response_format: The response format of the tool calls used by this agent. Is one of - the following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat, ResponseFormatJsonSchemaType Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat or - ~azure.ai.projects.models.ResponseFormatJsonSchemaType - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :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.Agent] = kwargs.pop("cls", None) - - if body is _Unset: - body = { - "description": description, - "instructions": instructions, - "metadata": metadata, - "model": model, - "name": name, - "response_format": response_format, - "temperature": temperature, - "tool_resources": tool_resources, - "tools": tools, - "top_p": top_p, - } - 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_update_agent_request( - agent_id=agent_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.Agent, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete_agent(self, agent_id: str, **kwargs: Any) -> _models.AgentDeletionStatus: - """Deletes an agent. - - :param agent_id: Identifier of the agent. Required. - :type agent_id: str - :return: AgentDeletionStatus. The AgentDeletionStatus is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentDeletionStatus - :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.AgentDeletionStatus] = kwargs.pop("cls", None) - - _request = build_agents_delete_agent_request( - agent_id=agent_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.AgentDeletionStatus, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create_thread( - self, - *, - content_type: str = "application/json", - messages: Optional[List[_models.ThreadMessageOptions]] = None, - tool_resources: Optional[_models.ToolResources] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.AgentThread: - """Creates a new thread. Threads contain messages and can be run by agents. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword messages: The initial messages to associate with the new thread. Default value is - None. - :paramtype messages: list[~azure.ai.projects.models.ThreadMessageOptions] - :keyword tool_resources: A set of resources that are made available to the agent's tools in - this thread. The resources are specific to the - type of tool. For example, the ``code_interpreter`` tool requires a list of file IDs, while - the ``file_search`` tool requires - a list of vector store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: AgentThread. The AgentThread is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentThread - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_thread( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AgentThread: - """Creates a new thread. Threads contain messages and can be run by agents. - - :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: AgentThread. The AgentThread is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentThread - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_thread( - self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AgentThread: - """Creates a new thread. Threads contain messages and can be run by agents. - - :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: AgentThread. The AgentThread is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentThread - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_thread( - self, - body: Union[JSON, IO[bytes]] = _Unset, - *, - messages: Optional[List[_models.ThreadMessageOptions]] = None, - tool_resources: Optional[_models.ToolResources] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.AgentThread: - """Creates a new thread. Threads contain messages and can be run by agents. - - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword messages: The initial messages to associate with the new thread. Default value is - None. - :paramtype messages: list[~azure.ai.projects.models.ThreadMessageOptions] - :keyword tool_resources: A set of resources that are made available to the agent's tools in - this thread. The resources are specific to the - type of tool. For example, the ``code_interpreter`` tool requires a list of file IDs, while - the ``file_search`` tool requires - a list of vector store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: AgentThread. The AgentThread is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentThread - :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.AgentThread] = kwargs.pop("cls", None) - - if body is _Unset: - body = {"messages": messages, "metadata": metadata, "tool_resources": tool_resources} - 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_thread_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.AgentThread, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_thread(self, thread_id: str, **kwargs: Any) -> _models.AgentThread: - """Gets information about an existing thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :return: AgentThread. The AgentThread is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentThread - :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.AgentThread] = kwargs.pop("cls", None) - - _request = build_agents_get_thread_request( - thread_id=thread_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.AgentThread, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def update_thread( - self, - thread_id: str, - *, - content_type: str = "application/json", - tool_resources: Optional[_models.ToolResources] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.AgentThread: - """Modifies an existing thread. - - :param thread_id: The ID of the thread to modify. Required. - :type thread_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword tool_resources: A set of resources that are made available to the agent's tools in - this thread. The resources are specific to the - type of tool. For example, the ``code_interpreter`` tool requires a list of file IDs, while - the ``file_search`` tool requires - a list of vector store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: AgentThread. The AgentThread is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentThread - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update_thread( - self, thread_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AgentThread: - """Modifies an existing thread. - - :param thread_id: The ID of the thread to modify. Required. - :type thread_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: AgentThread. The AgentThread is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentThread - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update_thread( - self, thread_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.AgentThread: - """Modifies an existing thread. - - :param thread_id: The ID of the thread to modify. Required. - :type thread_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: AgentThread. The AgentThread is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentThread - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def update_thread( - self, - thread_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - tool_resources: Optional[_models.ToolResources] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.AgentThread: - """Modifies an existing thread. - - :param thread_id: The ID of the thread to modify. Required. - :type thread_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword tool_resources: A set of resources that are made available to the agent's tools in - this thread. The resources are specific to the - type of tool. For example, the ``code_interpreter`` tool requires a list of file IDs, while - the ``file_search`` tool requires - a list of vector store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: AgentThread. The AgentThread is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentThread - :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.AgentThread] = kwargs.pop("cls", None) - - if body is _Unset: - body = {"metadata": metadata, "tool_resources": tool_resources} - 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_update_thread_request( - thread_id=thread_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.AgentThread, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete_thread(self, thread_id: str, **kwargs: Any) -> _models.ThreadDeletionStatus: - """Deletes an existing thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :return: ThreadDeletionStatus. The ThreadDeletionStatus is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadDeletionStatus - :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.ThreadDeletionStatus] = kwargs.pop("cls", None) - - _request = build_agents_delete_thread_request( - thread_id=thread_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.ThreadDeletionStatus, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_threads( - self, - *, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any - ) -> _models.OpenAIPageableListOfAgentThread: - """Gets a list of threads that were previously created. - - :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.ListSortOrder - :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: OpenAIPageableListOfAgentThread. The OpenAIPageableListOfAgentThread is compatible - with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIPageableListOfAgentThread - :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.OpenAIPageableListOfAgentThread] = kwargs.pop("cls", None) - - _request = build_agents_list_threads_request( - 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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.OpenAIPageableListOfAgentThread, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create_message( - self, - thread_id: str, - *, - role: Union[str, _models.MessageRole], - content: "_types.MessageInputContent", - content_type: str = "application/json", - attachments: Optional[List[_models.MessageAttachment]] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.ThreadMessage: - """Creates a new message on a specified thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :keyword role: The role of the entity that is creating the message. Allowed values include: - ``user``, which indicates the message is sent by an actual user (and should be - used in most cases to represent user-generated messages), and ``assistant``, - which indicates the message is generated by the agent (use this value to insert - messages from the agent into the conversation). Known values are: "user" and "assistant". - Required. - :paramtype role: str or ~azure.ai.projects.models.MessageRole - :keyword content: The content of the initial message. This may be a basic string (if you only - need text) or an array of typed content blocks (for example, text, image_file, - image_url, and so on). Is either a str type or a [MessageInputContentBlock] type. Required. - :paramtype content: str or list[~azure.ai.projects.models.MessageInputContentBlock] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword attachments: A list of files attached to the message, and the tools they should be - added to. Default value is None. - :paramtype attachments: list[~azure.ai.projects.models.MessageAttachment] - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadMessage. The ThreadMessage is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadMessage - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_message( - self, thread_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadMessage: - """Creates a new message on a specified thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_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: ThreadMessage. The ThreadMessage is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadMessage - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_message( - self, thread_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadMessage: - """Creates a new message on a specified thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_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: ThreadMessage. The ThreadMessage is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadMessage - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_message( - self, - thread_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - role: Union[str, _models.MessageRole] = _Unset, - content: "_types.MessageInputContent" = _Unset, - attachments: Optional[List[_models.MessageAttachment]] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.ThreadMessage: - """Creates a new message on a specified thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword role: The role of the entity that is creating the message. Allowed values include: - ``user``, which indicates the message is sent by an actual user (and should be - used in most cases to represent user-generated messages), and ``assistant``, - which indicates the message is generated by the agent (use this value to insert - messages from the agent into the conversation). Known values are: "user" and "assistant". - Required. - :paramtype role: str or ~azure.ai.projects.models.MessageRole - :keyword content: The content of the initial message. This may be a basic string (if you only - need text) or an array of typed content blocks (for example, text, image_file, - image_url, and so on). Is either a str type or a [MessageInputContentBlock] type. Required. - :paramtype content: str or list[~azure.ai.projects.models.MessageInputContentBlock] - :keyword attachments: A list of files attached to the message, and the tools they should be - added to. Default value is None. - :paramtype attachments: list[~azure.ai.projects.models.MessageAttachment] - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadMessage. The ThreadMessage is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadMessage - :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.ThreadMessage] = kwargs.pop("cls", None) - - if body is _Unset: - if role is _Unset: - raise TypeError("missing required argument: role") - if content is _Unset: - raise TypeError("missing required argument: content") - body = {"attachments": attachments, "content": content, "metadata": metadata, "role": role} - 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_message_request( - thread_id=thread_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.ThreadMessage, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_messages( - self, - thread_id: str, - *, - run_id: Optional[str] = None, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any - ) -> _models.OpenAIPageableListOfThreadMessage: - """Gets a list of messages that exist on a thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :keyword run_id: Filter messages by the run ID that generated them. Default value is None. - :paramtype run_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.ListSortOrder - :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: OpenAIPageableListOfThreadMessage. The OpenAIPageableListOfThreadMessage is compatible - with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIPageableListOfThreadMessage - :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.OpenAIPageableListOfThreadMessage] = kwargs.pop("cls", None) - - _request = build_agents_list_messages_request( - thread_id=thread_id, - run_id=run_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.OpenAIPageableListOfThreadMessage, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_message(self, thread_id: str, message_id: str, **kwargs: Any) -> _models.ThreadMessage: - """Gets an existing message from an existing thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param message_id: Identifier of the message. Required. - :type message_id: str - :return: ThreadMessage. The ThreadMessage is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadMessage - :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.ThreadMessage] = kwargs.pop("cls", None) - - _request = build_agents_get_message_request( - thread_id=thread_id, - message_id=message_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.ThreadMessage, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def update_message( - self, - thread_id: str, - message_id: str, - *, - content_type: str = "application/json", - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.ThreadMessage: - """Modifies an existing message on an existing thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param message_id: Identifier of the message. Required. - :type message_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadMessage. The ThreadMessage is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadMessage - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update_message( - self, thread_id: str, message_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadMessage: - """Modifies an existing message on an existing thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param message_id: Identifier of the message. Required. - :type message_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: ThreadMessage. The ThreadMessage is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadMessage - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update_message( - self, thread_id: str, message_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadMessage: - """Modifies an existing message on an existing thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param message_id: Identifier of the message. Required. - :type message_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: ThreadMessage. The ThreadMessage is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadMessage - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def update_message( - self, - thread_id: str, - message_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.ThreadMessage: - """Modifies an existing message on an existing thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param message_id: Identifier of the message. Required. - :type message_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadMessage. The ThreadMessage is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadMessage - :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.ThreadMessage] = kwargs.pop("cls", None) - - if body is _Unset: - body = {"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_update_message_request( - thread_id=thread_id, - message_id=message_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.ThreadMessage, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create_run( - self, - thread_id: str, - *, - agent_id: str, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - content_type: str = "application/json", - model: Optional[str] = None, - instructions: Optional[str] = None, - additional_instructions: Optional[str] = None, - additional_messages: Optional[List[_models.ThreadMessageOptions]] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - stream_parameter: Optional[bool] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.ThreadRun: - """Creates a new run for an agent thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :keyword agent_id: The ID of the agent that should run the thread. Required. - :paramtype agent_id: str - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword model: The overridden model name that the agent should use to run the thread. Default - value is None. - :paramtype model: str - :keyword instructions: The overridden system instructions that the agent should use to run the - thread. Default value is None. - :paramtype instructions: str - :keyword additional_instructions: Additional instructions to append at the end of the - instructions for the run. This is useful for modifying the behavior - on a per-run basis without overriding other instructions. Default value is None. - :paramtype additional_instructions: str - :keyword additional_messages: Adds additional messages to the thread before creating the run. - Default value is None. - :paramtype additional_messages: list[~azure.ai.projects.models.ThreadMessageOptions] - :keyword tools: The overridden list of enabled tools that the agent should use to run the - thread. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword stream_parameter: If ``true``, returns a stream of events that happen during the Run - as server-sent events, - terminating when the Run enters a terminal state with a ``data: [DONE]`` message. Default - value is None. - :paramtype stream_parameter: bool - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort - to use only the number of completion tokens specified, across multiple turns of the run. If - the run exceeds the number of - completion tokens specified, the run will end with status ``incomplete``. See - ``incomplete_details`` for more info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode - or ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat, ResponseFormatJsonSchemaType Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat or - ~azure.ai.projects.models.ResponseFormatJsonSchemaType - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_run( - self, - thread_id: str, - body: JSON, - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ThreadRun: - """Creates a new run for an agent thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param body: Required. - :type body: JSON - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_run( - self, - thread_id: str, - body: IO[bytes], - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - content_type: str = "application/json", - **kwargs: Any - ) -> _models.ThreadRun: - """Creates a new run for an agent thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param body: Required. - :type body: IO[bytes] - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_run( - self, - thread_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - agent_id: str = _Unset, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - model: Optional[str] = None, - instructions: Optional[str] = None, - additional_instructions: Optional[str] = None, - additional_messages: Optional[List[_models.ThreadMessageOptions]] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - stream_parameter: Optional[bool] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.ThreadRun: - """Creates a new run for an agent thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword agent_id: The ID of the agent that should run the thread. Required. - :paramtype agent_id: str - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword model: The overridden model name that the agent should use to run the thread. Default - value is None. - :paramtype model: str - :keyword instructions: The overridden system instructions that the agent should use to run the - thread. Default value is None. - :paramtype instructions: str - :keyword additional_instructions: Additional instructions to append at the end of the - instructions for the run. This is useful for modifying the behavior - on a per-run basis without overriding other instructions. Default value is None. - :paramtype additional_instructions: str - :keyword additional_messages: Adds additional messages to the thread before creating the run. - Default value is None. - :paramtype additional_messages: list[~azure.ai.projects.models.ThreadMessageOptions] - :keyword tools: The overridden list of enabled tools that the agent should use to run the - thread. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword stream_parameter: If ``true``, returns a stream of events that happen during the Run - as server-sent events, - terminating when the Run enters a terminal state with a ``data: [DONE]`` message. Default - value is None. - :paramtype stream_parameter: bool - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort - to use only the number of completion tokens specified, across multiple turns of the run. If - the run exceeds the number of - completion tokens specified, the run will end with status ``incomplete``. See - ``incomplete_details`` for more info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode - or ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat, ResponseFormatJsonSchemaType Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat or - ~azure.ai.projects.models.ResponseFormatJsonSchemaType - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :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.ThreadRun] = kwargs.pop("cls", None) - - if body is _Unset: - if agent_id is _Unset: - raise TypeError("missing required argument: agent_id") - body = { - "additional_instructions": additional_instructions, - "additional_messages": additional_messages, - "assistant_id": agent_id, - "instructions": instructions, - "max_completion_tokens": max_completion_tokens, - "max_prompt_tokens": max_prompt_tokens, - "metadata": metadata, - "model": model, - "parallel_tool_calls": parallel_tool_calls, - "response_format": response_format, - "stream": stream_parameter, - "temperature": temperature, - "tool_choice": tool_choice, - "tools": tools, - "top_p": top_p, - "truncation_strategy": truncation_strategy, - } - 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_run_request( - thread_id=thread_id, - include=include, - 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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.ThreadRun, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_runs( - self, - thread_id: str, - *, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any - ) -> _models.OpenAIPageableListOfThreadRun: - """Gets a list of runs for a specified thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_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.ListSortOrder - :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: OpenAIPageableListOfThreadRun. The OpenAIPageableListOfThreadRun is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIPageableListOfThreadRun - :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.OpenAIPageableListOfThreadRun] = kwargs.pop("cls", None) - - _request = build_agents_list_runs_request( - thread_id=thread_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.OpenAIPageableListOfThreadRun, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_run(self, thread_id: str, run_id: str, **kwargs: Any) -> _models.ThreadRun: - """Gets an existing run from an existing thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_id: str - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :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.ThreadRun] = kwargs.pop("cls", None) - - _request = build_agents_get_run_request( - thread_id=thread_id, - run_id=run_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.ThreadRun, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def update_run( - self, - thread_id: str, - run_id: str, - *, - content_type: str = "application/json", - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.ThreadRun: - """Modifies an existing thread run. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update_run( - self, thread_id: str, run_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadRun: - """Modifies an existing thread run. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_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: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update_run( - self, thread_id: str, run_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadRun: - """Modifies an existing thread run. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_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: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def update_run( - self, - thread_id: str, - run_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.ThreadRun: - """Modifies an existing thread run. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :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.ThreadRun] = kwargs.pop("cls", None) - - if body is _Unset: - body = {"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_update_run_request( - thread_id=thread_id, - run_id=run_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.ThreadRun, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def submit_tool_outputs_to_run( - self, - thread_id: str, - run_id: str, - *, - tool_outputs: List[_models.ToolOutput], - content_type: str = "application/json", - stream_parameter: Optional[bool] = None, - **kwargs: Any - ) -> _models.ThreadRun: - """Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_id: str - :keyword tool_outputs: A list of tools for which the outputs are being submitted. Required. - :paramtype tool_outputs: list[~azure.ai.projects.models.ToolOutput] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword stream_parameter: If true, returns a stream of events that happen during the Run as - server-sent events, terminating when the run enters a terminal state. Default value is None. - :paramtype stream_parameter: bool - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def submit_tool_outputs_to_run( - self, thread_id: str, run_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadRun: - """Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_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: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def submit_tool_outputs_to_run( - self, thread_id: str, run_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadRun: - """Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_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: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def submit_tool_outputs_to_run( - self, - thread_id: str, - run_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - tool_outputs: List[_models.ToolOutput] = _Unset, - stream_parameter: Optional[bool] = None, - **kwargs: Any - ) -> _models.ThreadRun: - """Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword tool_outputs: A list of tools for which the outputs are being submitted. Required. - :paramtype tool_outputs: list[~azure.ai.projects.models.ToolOutput] - :keyword stream_parameter: If true, returns a stream of events that happen during the Run as - server-sent events, terminating when the run enters a terminal state. Default value is None. - :paramtype stream_parameter: bool - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :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.ThreadRun] = kwargs.pop("cls", None) - - if body is _Unset: - if tool_outputs is _Unset: - raise TypeError("missing required argument: tool_outputs") - body = {"stream": stream_parameter, "tool_outputs": tool_outputs} - 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_submit_tool_outputs_to_run_request( - thread_id=thread_id, - run_id=run_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.ThreadRun, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def cancel_run(self, thread_id: str, run_id: str, **kwargs: Any) -> _models.ThreadRun: - """Cancels a run of an in progress thread. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_id: str - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :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.ThreadRun] = kwargs.pop("cls", None) - - _request = build_agents_cancel_run_request( - thread_id=thread_id, - run_id=run_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.ThreadRun, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create_thread_and_run( - self, - *, - agent_id: str, - content_type: str = "application/json", - thread: Optional[_models.AgentThreadCreationOptions] = None, - model: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.UpdateToolResourcesOptions] = None, - stream_parameter: Optional[bool] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.ThreadRun: - """Creates a new agent thread and immediately starts a run using that new thread. - - :keyword agent_id: The ID of the agent for which the thread should be created. Required. - :paramtype agent_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword thread: The details used to create the new thread. If no thread is provided, an empty - one will be created. Default value is None. - :paramtype thread: ~azure.ai.projects.models.AgentThreadCreationOptions - :keyword model: The overridden model that the agent should use to run the thread. Default value - is None. - :paramtype model: str - :keyword instructions: The overridden system instructions the agent should use to run the - thread. Default value is None. - :paramtype instructions: str - :keyword tools: The overridden list of enabled tools the agent should use to run the thread. - Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword tool_resources: Override the tools the agent can use for this run. This is useful for - modifying the behavior on a per-run basis. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.UpdateToolResourcesOptions - :keyword stream_parameter: If ``true``, returns a stream of events that happen during the Run - as server-sent events, - terminating when the Run enters a terminal state with a ``data: [DONE]`` message. Default - value is None. - :paramtype stream_parameter: bool - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort to use only - the number of completion tokens specified, across multiple turns of the run. If the run - exceeds the number of completion tokens - specified, the run will end with status ``incomplete``. See ``incomplete_details`` for more - info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode - or ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat, ResponseFormatJsonSchemaType Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat or - ~azure.ai.projects.models.ResponseFormatJsonSchemaType - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_thread_and_run( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadRun: - """Creates a new agent thread and immediately starts a run using that new thread. - - :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: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_thread_and_run( - self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadRun: - """Creates a new agent thread and immediately starts a run using that new thread. - - :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: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_thread_and_run( - self, - body: Union[JSON, IO[bytes]] = _Unset, - *, - agent_id: str = _Unset, - thread: Optional[_models.AgentThreadCreationOptions] = None, - model: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.UpdateToolResourcesOptions] = None, - stream_parameter: Optional[bool] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.ThreadRun: - """Creates a new agent thread and immediately starts a run using that new thread. - - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword agent_id: The ID of the agent for which the thread should be created. Required. - :paramtype agent_id: str - :keyword thread: The details used to create the new thread. If no thread is provided, an empty - one will be created. Default value is None. - :paramtype thread: ~azure.ai.projects.models.AgentThreadCreationOptions - :keyword model: The overridden model that the agent should use to run the thread. Default value - is None. - :paramtype model: str - :keyword instructions: The overridden system instructions the agent should use to run the - thread. Default value is None. - :paramtype instructions: str - :keyword tools: The overridden list of enabled tools the agent should use to run the thread. - Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword tool_resources: Override the tools the agent can use for this run. This is useful for - modifying the behavior on a per-run basis. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.UpdateToolResourcesOptions - :keyword stream_parameter: If ``true``, returns a stream of events that happen during the Run - as server-sent events, - terminating when the Run enters a terminal state with a ``data: [DONE]`` message. Default - value is None. - :paramtype stream_parameter: bool - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort to use only - the number of completion tokens specified, across multiple turns of the run. If the run - exceeds the number of completion tokens - specified, the run will end with status ``incomplete``. See ``incomplete_details`` for more - info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode - or ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat, ResponseFormatJsonSchemaType Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat or - ~azure.ai.projects.models.ResponseFormatJsonSchemaType - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :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.ThreadRun] = kwargs.pop("cls", None) - - if body is _Unset: - if agent_id is _Unset: - raise TypeError("missing required argument: agent_id") - body = { - "assistant_id": agent_id, - "instructions": instructions, - "max_completion_tokens": max_completion_tokens, - "max_prompt_tokens": max_prompt_tokens, - "metadata": metadata, - "model": model, - "parallel_tool_calls": parallel_tool_calls, - "response_format": response_format, - "stream": stream_parameter, - "temperature": temperature, - "thread": thread, - "tool_choice": tool_choice, - "tool_resources": tool_resources, - "tools": tools, - "top_p": top_p, - "truncation_strategy": truncation_strategy, - } - 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_thread_and_run_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.ThreadRun, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_run_step( - self, - thread_id: str, - run_id: str, - step_id: str, - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - **kwargs: Any - ) -> _models.RunStep: - """Gets a single run step from a thread run. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_id: str - :param step_id: Identifier of the run step. Required. - :type step_id: str - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :return: RunStep. The RunStep is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.RunStep - :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.RunStep] = kwargs.pop("cls", None) - - _request = build_agents_get_run_step_request( - thread_id=thread_id, - run_id=run_id, - step_id=step_id, - include=include, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.RunStep, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_run_steps( - self, - thread_id: str, - run_id: str, - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any - ) -> _models.OpenAIPageableListOfRunStep: - """Gets a list of run steps from a thread run. - - :param thread_id: Identifier of the thread. Required. - :type thread_id: str - :param run_id: Identifier of the run. Required. - :type run_id: str - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :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.ListSortOrder - :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: OpenAIPageableListOfRunStep. The OpenAIPageableListOfRunStep is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIPageableListOfRunStep - :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.OpenAIPageableListOfRunStep] = kwargs.pop("cls", None) - - _request = build_agents_list_run_steps_request( - thread_id=thread_id, - run_id=run_id, - include=include, - 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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.OpenAIPageableListOfRunStep, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_files( - self, *, purpose: Optional[Union[str, _models.FilePurpose]] = None, **kwargs: Any - ) -> _models.FileListResponse: - """Gets a list of previously uploaded files. - - :keyword purpose: The purpose of the file. Known values are: "fine-tune", "fine-tune-results", - "assistants", "assistants_output", "batch", "batch_output", and "vision". Default value is - None. - :paramtype purpose: str or ~azure.ai.projects.models.FilePurpose - :return: FileListResponse. The FileListResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.FileListResponse - :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.FileListResponse] = kwargs.pop("cls", None) - - _request = build_agents_list_files_request( - purpose=purpose, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.FileListResponse, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def _upload_file(self, body: _models._models.UploadFileRequest, **kwargs: Any) -> _models.OpenAIFile: ... - @overload - def _upload_file(self, body: JSON, **kwargs: Any) -> _models.OpenAIFile: ... - - @distributed_trace - def _upload_file(self, body: Union[_models._models.UploadFileRequest, JSON], **kwargs: Any) -> _models.OpenAIFile: - """Uploads a file for use by other operations. - - :param body: Multipart body. Is either a UploadFileRequest type or a JSON type. Required. - :type body: ~azure.ai.projects.models._models.UploadFileRequest or JSON - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIFile - :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.OpenAIFile] = kwargs.pop("cls", None) - - _body = body.as_dict() if isinstance(body, _model_base.Model) else body - _file_fields: List[str] = ["file"] - _data_fields: List[str] = ["purpose", "filename"] - _files, _data = prepare_multipart_form_data(_body, _file_fields, _data_fields) - - _request = build_agents_upload_file_request( - api_version=self._config.api_version, - files=_files, - data=_data, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.OpenAIFile, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete_file(self, file_id: str, **kwargs: Any) -> _models.FileDeletionStatus: - """Delete a previously uploaded file. - - :param file_id: The ID of the file to delete. Required. - :type file_id: str - :return: FileDeletionStatus. The FileDeletionStatus is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.FileDeletionStatus - :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.FileDeletionStatus] = kwargs.pop("cls", None) - - _request = build_agents_delete_file_request( - file_id=file_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.FileDeletionStatus, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_file(self, file_id: str, **kwargs: Any) -> _models.OpenAIFile: - """Returns information about a specific file. Does not retrieve file content. - - :param file_id: The ID of the file to retrieve. Required. - :type file_id: str - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIFile - :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.OpenAIFile] = kwargs.pop("cls", None) - - _request = build_agents_get_file_request( - file_id=file_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.OpenAIFile, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def _get_file_content(self, file_id: str, **kwargs: Any) -> Iterator[bytes]: - """Retrieves the raw content of a specific file. - - :param file_id: The ID of the file to retrieve. Required. - :type file_id: 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 {}) - - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls: ClsType[Iterator[bytes]] = kwargs.pop("cls", None) - - _request = build_agents_get_file_content_request( - file_id=file_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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) - raise HttpResponseError(response=response) - - deserialized = response.iter_bytes() - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def list_vector_stores( - self, - *, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any - ) -> _models.OpenAIPageableListOfVectorStore: - """Returns a list of vector 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.ListSortOrder - :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: OpenAIPageableListOfVectorStore. The OpenAIPageableListOfVectorStore is compatible - with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIPageableListOfVectorStore - :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.OpenAIPageableListOfVectorStore] = kwargs.pop("cls", None) - - _request = build_agents_list_vector_stores_request( - 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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.OpenAIPageableListOfVectorStore, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def create_vector_store( - self, - *, - content_type: str = "application/json", - file_ids: Optional[List[str]] = None, - name: Optional[str] = None, - store_configuration: Optional[_models.VectorStoreConfiguration] = None, - expires_after: Optional[_models.VectorStoreExpirationPolicy] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.VectorStore: - """Creates a vector store. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword file_ids: A list of file IDs that the vector store should use. Useful for tools like - ``file_search`` that can access files. Default value is None. - :paramtype file_ids: list[str] - :keyword name: The name of the vector store. Default value is None. - :paramtype name: str - :keyword store_configuration: The vector store configuration, used when vector store is created - from Azure asset URIs. Default value is None. - :paramtype store_configuration: ~azure.ai.projects.models.VectorStoreConfiguration - :keyword expires_after: Details on when this vector store expires. Default value is None. - :paramtype expires_after: ~azure.ai.projects.models.VectorStoreExpirationPolicy - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Only applicable if file_ids is non-empty. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_vector_store( - self, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.VectorStore: - """Creates a vector 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: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_vector_store( - self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.VectorStore: - """Creates a vector 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: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_vector_store( - self, - body: Union[JSON, IO[bytes]] = _Unset, - *, - file_ids: Optional[List[str]] = None, - name: Optional[str] = None, - store_configuration: Optional[_models.VectorStoreConfiguration] = None, - expires_after: Optional[_models.VectorStoreExpirationPolicy] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.VectorStore: - """Creates a vector store. - - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword file_ids: A list of file IDs that the vector store should use. Useful for tools like - ``file_search`` that can access files. Default value is None. - :paramtype file_ids: list[str] - :keyword name: The name of the vector store. Default value is None. - :paramtype name: str - :keyword store_configuration: The vector store configuration, used when vector store is created - from Azure asset URIs. Default value is None. - :paramtype store_configuration: ~azure.ai.projects.models.VectorStoreConfiguration - :keyword expires_after: Details on when this vector store expires. Default value is None. - :paramtype expires_after: ~azure.ai.projects.models.VectorStoreExpirationPolicy - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Only applicable if file_ids is non-empty. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :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.VectorStore] = kwargs.pop("cls", None) - - if body is _Unset: - body = { - "chunking_strategy": chunking_strategy, - "configuration": store_configuration, - "expires_after": expires_after, - "file_ids": file_ids, - "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_agents_create_vector_store_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.VectorStore, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def get_vector_store(self, vector_store_id: str, **kwargs: Any) -> _models.VectorStore: - """Returns the vector store object matching the specified ID. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :return: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :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.VectorStore] = kwargs.pop("cls", None) - - _request = build_agents_get_vector_store_request( - vector_store_id=vector_store_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.VectorStore, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @overload - def modify_vector_store( - self, - vector_store_id: str, - *, - content_type: str = "application/json", - name: Optional[str] = None, - expires_after: Optional[_models.VectorStoreExpirationPolicy] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.VectorStore: - """The ID of the vector store to modify. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword name: The name of the vector store. Default value is None. - :paramtype name: str - :keyword expires_after: Details on when this vector store expires. Default value is None. - :paramtype expires_after: ~azure.ai.projects.models.VectorStoreExpirationPolicy - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def modify_vector_store( - self, vector_store_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.VectorStore: - """The ID of the vector store to modify. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_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: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def modify_vector_store( - self, vector_store_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.VectorStore: - """The ID of the vector store to modify. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_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: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def modify_vector_store( - self, - vector_store_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - name: Optional[str] = None, - expires_after: Optional[_models.VectorStoreExpirationPolicy] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any - ) -> _models.VectorStore: - """The ID of the vector store to modify. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :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 vector store. Default value is None. - :paramtype name: str - :keyword expires_after: Details on when this vector store expires. Default value is None. - :paramtype expires_after: ~azure.ai.projects.models.VectorStoreExpirationPolicy - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :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.VectorStore] = kwargs.pop("cls", None) - - if body is _Unset: - body = {"expires_after": expires_after, "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_agents_modify_vector_store_request( - vector_store_id=vector_store_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.VectorStore, response.json()) - - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore - - @distributed_trace - def delete_vector_store(self, vector_store_id: str, **kwargs: Any) -> _models.VectorStoreDeletionStatus: - """Deletes the vector store object matching the specified ID. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :return: VectorStoreDeletionStatus. The VectorStoreDeletionStatus is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreDeletionStatus - :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.VectorStoreDeletionStatus] = kwargs.pop("cls", None) - - _request = build_agents_delete_vector_store_request( - vector_store_id=vector_store_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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 + response = pipeline_response.http_response if response.status_code not in [200]: if _stream: @@ -5702,54 +764,29 @@ def delete_vector_store(self, vector_store_id: str, **kwargs: Any) -> _models.Ve 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() else: - deserialized = _deserialize(_models.VectorStoreDeletionStatus, response.json()) + deserialized = _deserialize(_models.Connection, 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_vector_store_files( - self, - vector_store_id: str, - *, - filter: Optional[Union[str, _models.VectorStoreFileStatusFilter]] = None, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any - ) -> _models.OpenAIPageableListOfVectorStoreFile: - """Returns a list of vector store files. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :keyword filter: Filter by file status. Known values are: "in_progress", "completed", "failed", - and "cancelled". Default value is None. - :paramtype filter: str or ~azure.ai.projects.models.VectorStoreFileStatusFilter - :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.ListSortOrder - :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: OpenAIPageableListOfVectorStoreFile. The OpenAIPageableListOfVectorStoreFile is - compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIPageableListOfVectorStoreFile + def _get_with_credentials(self, name: str, **kwargs: Any) -> _models.Connection: + """Get a connection by name, with its connection credentials. + + :param name: The name of the resource. 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 = { @@ -5763,26 +800,16 @@ def list_vector_store_files( _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.OpenAIPageableListOfVectorStoreFile] = kwargs.pop("cls", None) + cls: ClsType[_models.Connection] = kwargs.pop("cls", None) - _request = build_agents_list_vector_store_files_request( - vector_store_id=vector_store_id, - filter=filter, - limit=limit, - order=order, - after=after, - before=before, + _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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -5802,110 +829,54 @@ def list_vector_store_files( 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() else: - deserialized = _deserialize(_models.OpenAIPageableListOfVectorStoreFile, response.json()) + deserialized = _deserialize(_models.Connection, 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 create_vector_store_file( + @distributed_trace + def list( self, - vector_store_id: str, *, - content_type: str = "application/json", - file_id: Optional[str] = None, - data_source: Optional[_models.VectorStoreDataSource] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, + connection_type: Optional[Union[str, _models.ConnectionType]] = None, + default_connection: Optional[bool] = None, + top: Optional[int] = None, + skip: Optional[int] = None, **kwargs: Any - ) -> _models.VectorStoreFile: - """Create a vector store file by attaching a file to a vector store. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword file_id: Identifier of the file. Default value is None. - :paramtype file_id: str - :keyword data_source: Azure asset ID. Default value is None. - :paramtype data_source: ~azure.ai.projects.models.VectorStoreDataSource - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :return: VectorStoreFile. The VectorStoreFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_vector_store_file( - self, vector_store_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.VectorStoreFile: - """Create a vector store file by attaching a file to a vector store. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_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: VectorStoreFile. The VectorStoreFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFile + ) -> Iterable["_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", and "CustomKeys". 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 + :keyword top: The number of result items to return. Default value is None. + :paramtype top: int + :keyword skip: The number of result items to skip. Default value is None. + :paramtype skip: int + :return: 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 {} - @overload - def create_vector_store_file( - self, vector_store_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.VectorStoreFile: - """Create a vector store file by attaching a file to a vector store. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_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: VectorStoreFile. The VectorStoreFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFile - :raises ~azure.core.exceptions.HttpResponseError: - """ + maxpagesize = kwargs.pop("maxpagesize", None) + cls: ClsType[List[_models.Connection]] = kwargs.pop("cls", None) - @distributed_trace - def create_vector_store_file( - self, - vector_store_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - file_id: Optional[str] = None, - data_source: Optional[_models.VectorStoreDataSource] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - **kwargs: Any - ) -> _models.VectorStoreFile: - """Create a vector store file by attaching a file to a vector store. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword file_id: Identifier of the file. Default value is None. - :paramtype file_id: str - :keyword data_source: Azure asset ID. Default value is None. - :paramtype data_source: ~azure.ai.projects.models.VectorStoreDataSource - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :return: VectorStoreFile. The VectorStoreFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFile - :raises ~azure.core.exceptions.HttpResponseError: - """ error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -5914,76 +885,102 @@ def create_vector_store_file( } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = kwargs.pop("params", {}) or {} + def prepare_request(next_link=None): + if not next_link: - content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.VectorStoreFile] = kwargs.pop("cls", None) + _request = build_connections_list_request( + connection_type=connection_type, + default_connection=default_connection, + top=top, + skip=skip, + maxpagesize=maxpagesize, + 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 body is _Unset: - body = {"chunking_strategy": chunking_strategy, "data_source": data_source, "file_id": file_id} - body = {k: v for k, v in body.items() if v is not None} - content_type = content_type or "application/json" - _content = None - if isinstance(body, (IOBase, bytes)): - _content = body - else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + 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_agents_create_vector_store_file_request( - vector_store_id=vector_store_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) + return _request - _stream = kwargs.pop("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.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) - response = pipeline_response.http_response + def get_next(next_link=None): + _request = prepare_request(next_link) - 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) + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.VectorStoreFile, 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) + + +class EvaluationsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.ai.projects.AIProjectClient`'s + :attr:`evaluations` attribute. + """ + + def __init__(self, *args, **kwargs): + 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_vector_store_file(self, vector_store_id: str, file_id: str, **kwargs: Any) -> _models.VectorStoreFile: - """Retrieves a vector store file. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param file_id: Identifier of the file. Required. - :type file_id: str - :return: VectorStoreFile. The VectorStoreFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFile + @api_version_validation( + method_added_on="2025-05-15-preview", + params_added_on={"2025-05-15-preview": ["api_version", "name", "client_request_id", "accept"]}, + ) + def get(self, name: str, **kwargs: Any) -> _models.Evaluation: + """Get an evaluation run by name. + + :param name: Identifier of the evaluation. Required. + :type name: str + :return: Evaluation. The Evaluation is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Evaluation :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -5997,22 +994,16 @@ def get_vector_store_file(self, vector_store_id: str, file_id: str, **kwargs: An _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.VectorStoreFile] = kwargs.pop("cls", None) + cls: ClsType[_models.Evaluation] = kwargs.pop("cls", None) - _request = build_agents_get_vector_store_file_request( - vector_store_id=vector_store_id, - file_id=file_id, + _request = build_evaluations_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -6032,33 +1023,47 @@ def get_vector_store_file(self, vector_store_id: str, file_id: str, **kwargs: An 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() else: - deserialized = _deserialize(_models.VectorStoreFile, response.json()) + deserialized = _deserialize(_models.Evaluation, 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_vector_store_file( - self, vector_store_id: str, file_id: str, **kwargs: Any - ) -> _models.VectorStoreFileDeletionStatus: - """Delete a vector store file. This will remove the file from the vector store but the file itself - will not be deleted. - To delete the file, use the delete file endpoint. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param file_id: Identifier of the file. Required. - :type file_id: str - :return: VectorStoreFileDeletionStatus. The VectorStoreFileDeletionStatus is compatible with - MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileDeletionStatus + @api_version_validation( + method_added_on="2025-05-15-preview", + params_added_on={ + "2025-05-15-preview": ["api_version", "top", "skip", "maxpagesize", "client_request_id", "accept"] + }, + ) + def list( + self, *, top: Optional[int] = None, skip: Optional[int] = None, **kwargs: Any + ) -> Iterable["_models.Evaluation"]: + """List evaluation runs. + + :keyword top: The number of result items to return. Default value is None. + :paramtype top: int + :keyword skip: The number of result items to skip. Default value is None. + :paramtype skip: int + :return: An iterator like instance of Evaluation + :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.Evaluation] :raises ~azure.core.exceptions.HttpResponseError: """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + maxpagesize = kwargs.pop("maxpagesize", None) + cls: ClsType[List[_models.Evaluation]] = kwargs.pop("cls", None) + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, @@ -6067,146 +1072,131 @@ def delete_vector_store_file( } 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.VectorStoreFileDeletionStatus] = kwargs.pop("cls", None) + _request = build_evaluations_list_request( + top=top, + skip=skip, + maxpagesize=maxpagesize, + 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_agents_delete_vector_store_file_request( - vector_store_id=vector_store_id, - file_id=file_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _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) - _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.Evaluation], 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) - raise HttpResponseError(response=response) + def get_next(next_link=None): + _request = prepare_request(next_link) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.VectorStoreFileDeletionStatus, response.json()) + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + 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 deserialized # type: ignore + return pipeline_response + + return ItemPaged(get_next, extract_data) @overload - def create_vector_store_file_batch( - self, - vector_store_id: str, - *, - content_type: str = "application/json", - file_ids: Optional[List[str]] = None, - data_sources: Optional[List[_models.VectorStoreDataSource]] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - **kwargs: Any - ) -> _models.VectorStoreFileBatch: - """Create a vector store file batch. + def create_run( + self, evaluation: _models.Evaluation, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Evaluation: + """Creates an evaluation run. - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str + :param evaluation: Evaluation to be run. Required. + :type evaluation: ~azure.ai.projects.models.Evaluation :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :keyword file_ids: List of file identifiers. Default value is None. - :paramtype file_ids: list[str] - :keyword data_sources: List of Azure assets. Default value is None. - :paramtype data_sources: list[~azure.ai.projects.models.VectorStoreDataSource] - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :return: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch + :return: Evaluation. The Evaluation is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Evaluation :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_vector_store_file_batch( - self, vector_store_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.VectorStoreFileBatch: - """Create a vector store file batch. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param body: Required. - :type body: JSON + def create_run( + self, evaluation: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Evaluation: + """Creates an evaluation run. + + :param evaluation: Evaluation to be run. Required. + :type evaluation: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str - :return: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch + :return: Evaluation. The Evaluation is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Evaluation :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def create_vector_store_file_batch( - self, vector_store_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.VectorStoreFileBatch: - """Create a vector store file batch. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param body: Required. - :type body: IO[bytes] + def create_run( + self, evaluation: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.Evaluation: + """Creates an evaluation run. + + :param evaluation: Evaluation to be run. Required. + :type evaluation: 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: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch + :return: Evaluation. The Evaluation is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Evaluation :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def create_vector_store_file_batch( - self, - vector_store_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - file_ids: Optional[List[str]] = None, - data_sources: Optional[List[_models.VectorStoreDataSource]] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - **kwargs: Any - ) -> _models.VectorStoreFileBatch: - """Create a vector store file batch. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword file_ids: List of file identifiers. Default value is None. - :paramtype file_ids: list[str] - :keyword data_sources: List of Azure assets. Default value is None. - :paramtype data_sources: list[~azure.ai.projects.models.VectorStoreDataSource] - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :return: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch + @api_version_validation( + method_added_on="2025-05-15-preview", + params_added_on={"2025-05-15-preview": ["api_version", "content_type", "accept"]}, + ) + def create_run(self, evaluation: Union[_models.Evaluation, JSON, IO[bytes]], **kwargs: Any) -> _models.Evaluation: + """Creates an evaluation run. + + :param evaluation: Evaluation to be run. Is one of the following types: Evaluation, JSON, + IO[bytes] Required. + :type evaluation: ~azure.ai.projects.models.Evaluation or JSON or IO[bytes] + :return: Evaluation. The Evaluation is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Evaluation :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6221,20 +1211,16 @@ def create_vector_store_file_batch( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.VectorStoreFileBatch] = kwargs.pop("cls", None) + cls: ClsType[_models.Evaluation] = kwargs.pop("cls", None) - if body is _Unset: - body = {"chunking_strategy": chunking_strategy, "data_sources": data_sources, "file_ids": file_ids} - 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(evaluation, (IOBase, bytes)): + _content = evaluation else: - _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(evaluation, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_agents_create_vector_store_file_batch_request( - vector_store_id=vector_store_id, + _request = build_evaluations_create_run_request( content_type=content_type, api_version=self._config.api_version, content=_content, @@ -6242,12 +1228,7 @@ def create_vector_store_file_batch( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -6258,7 +1239,7 @@ def create_vector_store_file_batch( 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 @@ -6270,195 +1251,76 @@ def create_vector_store_file_batch( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.VectorStoreFileBatch, response.json()) + deserialized = _deserialize(_models.Evaluation, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @distributed_trace - def get_vector_store_file_batch( - self, vector_store_id: str, batch_id: str, **kwargs: Any - ) -> _models.VectorStoreFileBatch: - """Retrieve a vector store file batch. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param batch_id: Identifier of the file batch. Required. - :type batch_id: str - :return: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch + @overload + def create_agent_evaluation( + self, evaluation: _models.AgentEvaluationRequest, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AgentEvaluation: + """Creates an agent evaluation run. + + :param evaluation: Agent evaluation to be run. Required. + :type evaluation: ~azure.ai.projects.models.AgentEvaluationRequest + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: AgentEvaluation. The AgentEvaluation is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentEvaluation :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.VectorStoreFileBatch] = kwargs.pop("cls", None) - - _request = build_agents_get_vector_store_file_batch_request( - vector_store_id=vector_store_id, - batch_id=batch_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.VectorStoreFileBatch, response.json()) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore - - return deserialized # type: ignore + @overload + def create_agent_evaluation( + self, evaluation: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AgentEvaluation: + """Creates an agent evaluation run. - @distributed_trace - def cancel_vector_store_file_batch( - self, vector_store_id: str, batch_id: str, **kwargs: Any - ) -> _models.VectorStoreFileBatch: - """Cancel a vector store file batch. This attempts to cancel the processing of files in this batch - as soon as possible. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param batch_id: Identifier of the file batch. Required. - :type batch_id: str - :return: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch + :param evaluation: Agent evaluation to be run. Required. + :type evaluation: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: AgentEvaluation. The AgentEvaluation is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentEvaluation :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.VectorStoreFileBatch] = kwargs.pop("cls", None) - - _request = build_agents_cancel_vector_store_file_batch_request( - vector_store_id=vector_store_id, - batch_id=batch_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _request.url = self._client.format_url(_request.url, **path_format_arguments) - - _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() - else: - deserialized = _deserialize(_models.VectorStoreFileBatch, response.json()) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + @overload + def create_agent_evaluation( + self, evaluation: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.AgentEvaluation: + """Creates an agent evaluation run. - return deserialized # type: ignore + :param evaluation: Agent evaluation to be run. Required. + :type evaluation: 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: AgentEvaluation. The AgentEvaluation is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentEvaluation + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace - def list_vector_store_file_batch_files( - self, - vector_store_id: str, - batch_id: str, - *, - filter: Optional[Union[str, _models.VectorStoreFileStatusFilter]] = None, - limit: Optional[int] = None, - order: Optional[Union[str, _models.ListSortOrder]] = None, - after: Optional[str] = None, - before: Optional[str] = None, - **kwargs: Any - ) -> _models.OpenAIPageableListOfVectorStoreFile: - """Returns a list of vector store files in a batch. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param batch_id: Identifier of the file batch. Required. - :type batch_id: str - :keyword filter: Filter by file status. Known values are: "in_progress", "completed", "failed", - and "cancelled". Default value is None. - :paramtype filter: str or ~azure.ai.projects.models.VectorStoreFileStatusFilter - :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.ListSortOrder - :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: OpenAIPageableListOfVectorStoreFile. The OpenAIPageableListOfVectorStoreFile is - compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIPageableListOfVectorStoreFile + @api_version_validation( + method_added_on="2025-05-15-preview", + params_added_on={"2025-05-15-preview": ["api_version", "content_type", "accept"]}, + ) + def create_agent_evaluation( + self, evaluation: Union[_models.AgentEvaluationRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.AgentEvaluation: + """Creates an agent evaluation run. + + :param evaluation: Agent evaluation to be run. Is one of the following types: + AgentEvaluationRequest, JSON, IO[bytes] Required. + :type evaluation: ~azure.ai.projects.models.AgentEvaluationRequest or JSON or IO[bytes] + :return: AgentEvaluation. The AgentEvaluation is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AgentEvaluation :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6469,30 +1331,28 @@ def list_vector_store_file_batch_files( } 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.OpenAIPageableListOfVectorStoreFile] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.AgentEvaluation] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _content = None + if isinstance(evaluation, (IOBase, bytes)): + _content = evaluation + else: + _content = json.dumps(evaluation, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_agents_list_vector_store_file_batch_files_request( - vector_store_id=vector_store_id, - batch_id=batch_id, - filter=filter, - limit=limit, - order=order, - after=after, - before=before, + _request = build_evaluations_create_agent_evaluation_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -6503,7 +1363,7 @@ def list_vector_store_file_batch_files( 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 @@ -6515,7 +1375,7 @@ def list_vector_store_file_batch_files( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.OpenAIPageableListOfVectorStoreFile, response.json()) + deserialized = _deserialize(_models.AgentEvaluation, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -6523,14 +1383,14 @@ def list_vector_store_file_batch_files( return deserialized # type: ignore -class ConnectionsOperations: +class DatasetsOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.ai.projects.AIProjectClient`'s - :attr:`connections` attribute. + :attr:`datasets` attribute. """ def __init__(self, *args, **kwargs): @@ -6541,13 +1401,25 @@ def __init__(self, *args, **kwargs): self._deserialize: Deserializer = input_args.pop(0) if input_args else kwargs.pop("deserializer") @distributed_trace - def _get_workspace(self, **kwargs: Any) -> _models._models.GetWorkspaceResponse: - """Gets the properties of the specified machine learning workspace. + def list_versions( + self, name: str, *, continuation_token_parameter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.DatasetVersion"]: + """List all versions of the given DatasetVersion. - :return: GetWorkspaceResponse. The GetWorkspaceResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.models._models.GetWorkspaceResponse + :param name: The name of the resource. Required. + :type name: str + :keyword continuation_token_parameter: Continuation token for pagination. Default value is + None. + :paramtype continuation_token_parameter: 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, @@ -6556,78 +1428,87 @@ def _get_workspace(self, **kwargs: Any) -> _models._models.GetWorkspaceResponse: } 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._models.GetWorkspaceResponse] = kwargs.pop("cls", None) + _request = build_datasets_list_versions_request( + name=name, + continuation_token_parameter=continuation_token_parameter, + 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_connections_get_workspace_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _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) - _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.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) - 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) + def get_next(next_link=None): + _request = prepare_request(next_link) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize( - _models._models.GetWorkspaceResponse, response.json() # pylint: disable=protected-access + _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, deserialized, {}) # type: ignore + return pipeline_response - return deserialized # type: ignore + return ItemPaged(get_next, extract_data) @distributed_trace - def _list_connections( - self, - *, - category: Optional[Union[str, _models.ConnectionType]] = None, - include_all: Optional[bool] = None, - target: Optional[str] = None, - **kwargs: Any - ) -> _models._models.ListConnectionsResponse: - """List the details of all the connections (not including their credentials). - - :keyword category: Category of the workspace connection. Known values are: "AzureOpenAI", - "Serverless", "AzureBlob", "AIServices", "CognitiveSearch", "ApiKey", "CustomKeys", and - "CognitiveService". Default value is None. - :paramtype category: str or ~azure.ai.projects.models.ConnectionType - :keyword include_all: Indicates whether to list datastores. Service default: do not list - datastores. Default value is None. - :paramtype include_all: bool - :keyword target: Target of the workspace connection. Default value is None. - :paramtype target: str - :return: ListConnectionsResponse. The ListConnectionsResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.models._models.ListConnectionsResponse + def list( + self, *, continuation_token_parameter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.DatasetVersion"]: + """List the latest version of each DatasetVersion. + + :keyword continuation_token_parameter: Continuation token for pagination. Default value is + None. + :paramtype continuation_token_parameter: 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, @@ -6636,65 +1517,78 @@ def _list_connections( } 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._models.ListConnectionsResponse] = kwargs.pop("cls", None) + _request = build_datasets_list_request( + continuation_token_parameter=continuation_token_parameter, + 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_connections_list_connections_request( - category=category, - include_all=include_all, - target=target, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), - } - _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) - _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.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) - 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) + def get_next(next_link=None): + _request = prepare_request(next_link) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize( - _models._models.ListConnectionsResponse, response.json() # pylint: disable=protected-access + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) + response = pipeline_response.http_response - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + 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 deserialized # type: ignore + return pipeline_response + + return ItemPaged(get_next, extract_data) @distributed_trace - def _get_connection(self, connection_name: str, **kwargs: Any) -> _models._models.GetConnectionResponse: - """Get the details of a single connection, without credentials. + def get(self, name: str, version: str, **kwargs: Any) -> _models.DatasetVersion: + """Get the specific version of the DatasetVersion. - :param connection_name: Connection Name. Required. - :type connection_name: str - :return: GetConnectionResponse. The GetConnectionResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.models._models.GetConnectionResponse + :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 = { @@ -6708,21 +1602,17 @@ def _get_connection(self, connection_name: str, **kwargs: Any) -> _models._model _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models._models.GetConnectionResponse] = kwargs.pop("cls", None) + cls: ClsType[_models.DatasetVersion] = kwargs.pop("cls", None) - _request = build_connections_get_connection_request( - connection_name=connection_name, + _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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -6745,42 +1635,23 @@ def _get_connection(self, connection_name: str, **kwargs: Any) -> _models._model if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models._models.GetConnectionResponse, response.json() # pylint: disable=protected-access - ) + deserialized = _deserialize(_models.DatasetVersion, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - @overload - def _get_connection_with_secrets( - self, connection_name: str, *, ignored: str, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.GetConnectionResponse: ... - @overload - def _get_connection_with_secrets( - self, connection_name: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.GetConnectionResponse: ... - @overload - def _get_connection_with_secrets( - self, connection_name: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.GetConnectionResponse: ... - @distributed_trace - def _get_connection_with_secrets( - self, connection_name: str, body: Union[JSON, IO[bytes]] = _Unset, *, ignored: str = _Unset, **kwargs: Any - ) -> _models._models.GetConnectionResponse: - """Get the details of a single connection, including credentials (if available). - - :param connection_name: Connection Name. Required. - :type connection_name: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword ignored: The body is ignored. TODO: Can we remove this?. Required. - :paramtype ignored: str - :return: GetConnectionResponse. The GetConnectionResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.models._models.GetConnectionResponse + def delete(self, name: str, version: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Delete the specific version of the DatasetVersion. + + :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 = { @@ -6791,101 +1662,124 @@ def _get_connection_with_secrets( } 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._models.GetConnectionResponse] = kwargs.pop("cls", None) - - if body is _Unset: - if ignored is _Unset: - raise TypeError("missing required argument: ignored") - body = {"ignored": ignored} - 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[None] = kwargs.pop("cls", None) - _request = build_connections_get_connection_with_secrets_request( - connection_name=connection_name, - content_type=content_type, + _request = build_datasets_delete_request( + name=name, + version=version, 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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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 = 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() - else: - deserialized = _deserialize( - _models._models.GetConnectionResponse, response.json() # pylint: disable=protected-access - ) - if cls: - return cls(pipeline_response, deserialized, {}) # type: ignore + return cls(pipeline_response, None, {}) # type: ignore - return deserialized # type: ignore + @overload + def create_or_update( + self, + name: str, + version: str, + dataset_version: _models.DatasetVersion, + *, + content_type: str = "application/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 replace. Required. + :type version: str + :param dataset_version: The definition of 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/json". + :paramtype content_type: str + :return: DatasetVersion. The DatasetVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ -class TelemetryOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. + @overload + def create_or_update( + self, name: str, version: str, dataset_version: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.DatasetVersion: + """Create a new or update an existing DatasetVersion with the given version id. - Instead, you should access the following operations through - :class:`~azure.ai.projects.AIProjectClient`'s - :attr:`telemetry` attribute. - """ + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the DatasetVersion to create or replace. Required. + :type version: str + :param dataset_version: The definition of 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/json". + :paramtype content_type: str + :return: DatasetVersion. The DatasetVersion is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.DatasetVersion + :raises ~azure.core.exceptions.HttpResponseError: + """ - def __init__(self, *args, **kwargs): - 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_or_update( + self, + name: str, + version: str, + dataset_version: IO[bytes], + *, + content_type: str = "application/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 replace. Required. + :type version: str + :param dataset_version: The definition of 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/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 _get_app_insights( - self, app_insights_resource_url: str, **kwargs: Any - ) -> _models._models.GetAppInsightsResponse: - """Gets the properties of the specified Application Insights resource. - - :param app_insights_resource_url: The AppInsights Azure resource Url. It should have the - format: - '/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}/providers/microsoft.insights/components/{resourcename}'. - Required. - :type app_insights_resource_url: str - :return: GetAppInsightsResponse. The GetAppInsightsResponse is compatible with MutableMapping - :rtype: ~azure.ai.projects.models._models.GetAppInsightsResponse + 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 replace. Required. + :type version: str + :param dataset_version: The definition of 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 = { @@ -6896,24 +1790,30 @@ def _get_app_insights( } 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._models.GetAppInsightsResponse] = kwargs.pop("cls", None) + 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/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_telemetry_get_app_insights_request( - app_insights_resource_url=app_insights_resource_url, + _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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -6924,7 +1824,7 @@ def _get_app_insights( 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 @@ -6936,41 +1836,94 @@ def _get_app_insights( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models._models.GetAppInsightsResponse, response.json() # pylint: disable=protected-access - ) + 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, + body: _models.PendingUploadRequest, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.PendingUploadResponse: + """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 body: Parameters for the action. Required. + :type body: ~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: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ -class EvaluationsOperations: - """ - .. warning:: - **DO NOT** instantiate this class directly. + @overload + def pending_upload( + self, name: str, version: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PendingUploadResponse: + """Start a new or get an existing pending upload of a dataset for a specific version. - Instead, you should access the following operations through - :class:`~azure.ai.projects.AIProjectClient`'s - :attr:`evaluations` attribute. - """ + :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 body: Parameters for the action. 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: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ - def __init__(self, *args, **kwargs): - 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 pending_upload( + self, name: str, version: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.PendingUploadResponse: + """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 body: Parameters for the action. 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: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace - def get(self, id: str, **kwargs: Any) -> _models.Evaluation: - """Resource read operation template. + def pending_upload( + self, name: str, version: str, body: Union[_models.PendingUploadRequest, JSON, IO[bytes]], **kwargs: Any + ) -> _models.PendingUploadResponse: + """Start a new or get an existing pending upload of a dataset for a specific version. - :param id: Identifier of the evaluation. Required. - :type id: str - :return: Evaluation. The Evaluation is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Evaluation + :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 body: Parameters for the action. Is one of the following types: PendingUploadRequest, + JSON, IO[bytes] Required. + :type body: ~azure.ai.projects.models.PendingUploadRequest or JSON or IO[bytes] + :return: PendingUploadResponse. The PendingUploadResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.PendingUploadResponse :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -6981,24 +1934,30 @@ def get(self, id: str, **kwargs: Any) -> _models.Evaluation: } 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.Evaluation] = kwargs.pop("cls", None) + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.PendingUploadResponse] = kwargs.pop("cls", None) - _request = build_evaluations_get_request( - id=id, + 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_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -7018,76 +1977,28 @@ def get(self, id: str, **kwargs: Any) -> _models.Evaluation: 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() else: - deserialized = _deserialize(_models.Evaluation, response.json()) + deserialized = _deserialize(_models.PendingUploadResponse, 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( - self, evaluation: _models.Evaluation, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Evaluation: - """Run the evaluation. - - :param evaluation: Evaluation to run. Required. - :type evaluation: ~azure.ai.projects.models.Evaluation - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Evaluation. The Evaluation is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Evaluation - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create(self, evaluation: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Evaluation: - """Run the evaluation. - - :param evaluation: Evaluation to run. Required. - :type evaluation: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: Evaluation. The Evaluation is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Evaluation - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create( - self, evaluation: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Evaluation: - """Run the evaluation. - - :param evaluation: Evaluation to run. Required. - :type evaluation: 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: Evaluation. The Evaluation is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Evaluation - :raises ~azure.core.exceptions.HttpResponseError: - """ - @distributed_trace - def create(self, evaluation: Union[_models.Evaluation, JSON, IO[bytes]], **kwargs: Any) -> _models.Evaluation: - """Run the evaluation. + def get_credentials(self, name: str, version: str, body: Any, **kwargs: Any) -> _models.AssetCredentialResponse: + """Get the SAS credential to access the storage account associated with a Dataset version. - :param evaluation: Evaluation to run. Is one of the following types: Evaluation, JSON, - IO[bytes] Required. - :type evaluation: ~azure.ai.projects.models.Evaluation or JSON or IO[bytes] - :return: Evaluation. The Evaluation is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Evaluation + :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 body: Parameters for the action. Required. + :type body: any + :return: AssetCredentialResponse. The AssetCredentialResponse is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.AssetCredentialResponse :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -7101,17 +2012,14 @@ def create(self, evaluation: Union[_models.Evaluation, JSON, IO[bytes]], **kwarg _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.Evaluation] = kwargs.pop("cls", None) + content_type: str = kwargs.pop("content_type", _headers.pop("Content-Type", "application/json")) + cls: ClsType[_models.AssetCredentialResponse] = kwargs.pop("cls", None) - content_type = content_type or "application/json" - _content = None - if isinstance(evaluation, (IOBase, bytes)): - _content = evaluation - else: - _content = json.dumps(evaluation, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(body, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_evaluations_create_request( + _request = build_datasets_get_credentials_request( + name=name, + version=version, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -7119,12 +2027,7 @@ def create(self, evaluation: Union[_models.Evaluation, JSON, IO[bytes]], **kwarg params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -7135,7 +2038,7 @@ def create(self, evaluation: Union[_models.Evaluation, JSON, IO[bytes]], **kwarg 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 @@ -7147,32 +2050,50 @@ def create(self, evaluation: Union[_models.Evaluation, JSON, IO[bytes]], **kwarg if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.Evaluation, response.json()) + deserialized = _deserialize(_models.AssetCredentialResponse, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore + +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): + 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( - self, *, top: Optional[int] = None, skip: Optional[int] = None, **kwargs: Any - ) -> Iterable["_models.Evaluation"]: - """Resource list operation template. + def list_versions( + self, name: str, *, continuation_token_parameter: Optional[str] = None, **kwargs: Any + ) -> Iterable["_models.Index"]: + """List all versions of the given Index. - :keyword top: The number of result items to return. Default value is None. - :paramtype top: int - :keyword skip: The number of result items to skip. Default value is None. - :paramtype skip: int - :return: An iterator like instance of Evaluation - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.Evaluation] + :param name: The name of the resource. Required. + :type name: str + :keyword continuation_token_parameter: Continuation token for pagination. Default value is + None. + :paramtype continuation_token_parameter: 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 {} - maxpagesize = kwargs.pop("maxpagesize", None) - cls: ClsType[List[_models.Evaluation]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.Index]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -7185,23 +2106,17 @@ def list( def prepare_request(next_link=None): if not next_link: - _request = build_evaluations_list_request( - top=top, - skip=skip, - maxpagesize=maxpagesize, + _request = build_indexes_list_versions_request( + name=name, + continuation_token_parameter=continuation_token_parameter, api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url( - "self._config.subscription_id", self._config.subscription_id, "str" + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -7219,14 +2134,95 @@ def prepare_request(next_link=None): "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"), - "subscriptionId": self._serialize.url( - "self._config.subscription_id", self._config.subscription_id, "str" + "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, *, continuation_token_parameter: Optional[str] = None, **kwargs: Any) -> Iterable["_models.Index"]: + """List the latest version of each Index. + + :keyword continuation_token_parameter: Continuation token for pagination. Default value is + None. + :paramtype continuation_token_parameter: 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_request( + continuation_token_parameter=continuation_token_parameter, + 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 ), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" + } + _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 ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -7234,7 +2230,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.Evaluation], deserialized.get("value", [])) + 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) @@ -7248,86 +2244,221 @@ def get_next(next_link=None): ) 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 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. + + :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) + + _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() + 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. + + :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 - return pipeline_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) - return ItemPaged(get_next, extract_data) + if cls: + return cls(pipeline_response, None, {}) # type: ignore @overload - def update( + def create_or_update( self, - id: str, - resource: _models.Evaluation, + name: str, + version: str, + pending_upload_request: _models.Index, *, - content_type: str = "application/merge-patch+json", + content_type: str = "application/json", **kwargs: Any - ) -> _models.Evaluation: - """Resource update operation template. + ) -> _models.Index: + """Create a new or update an existing Index with the given version id. - :param id: Identifier of the evaluation. Required. - :type id: str - :param resource: The resource instance. Required. - :type resource: ~azure.ai.projects.models.Evaluation + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the Index to create or replace. Required. + :type version: str + :param pending_upload_request: The definition of the Index to create or update. Required. + :type pending_upload_request: ~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". + Default value is "application/json". :paramtype content_type: str - :return: Evaluation. The Evaluation is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Evaluation + :return: Index. The Index is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Index :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def update( - self, id: str, resource: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any - ) -> _models.Evaluation: - """Resource update operation template. + def create_or_update( + self, + name: str, + version: str, + pending_upload_request: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Index: + """Create a new or update an existing Index with the given version id. - :param id: Identifier of the evaluation. Required. - :type id: str - :param resource: The resource instance. Required. - :type resource: JSON + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the Index to create or replace. Required. + :type version: str + :param pending_upload_request: The definition of the Index to create or update. Required. + :type pending_upload_request: 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: Evaluation. The Evaluation is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Evaluation + :return: Index. The Index is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Index :raises ~azure.core.exceptions.HttpResponseError: """ @overload - def update( - self, id: str, resource: IO[bytes], *, content_type: str = "application/merge-patch+json", **kwargs: Any - ) -> _models.Evaluation: - """Resource update operation template. + def create_or_update( + self, + name: str, + version: str, + pending_upload_request: IO[bytes], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.Index: + """Create a new or update an existing Index with the given version id. - :param id: Identifier of the evaluation. Required. - :type id: str - :param resource: The resource instance. Required. - :type resource: IO[bytes] + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the Index to create or replace. Required. + :type version: str + :param pending_upload_request: The definition of the Index to create or update. Required. + :type pending_upload_request: 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: Evaluation. The Evaluation is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Evaluation + :return: Index. The Index is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Index :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace - def update( - self, id: str, resource: Union[_models.Evaluation, JSON, IO[bytes]], **kwargs: Any - ) -> _models.Evaluation: - """Resource update operation template. + def create_or_update( + self, name: str, version: str, pending_upload_request: Union[_models.Index, JSON, IO[bytes]], **kwargs: Any + ) -> _models.Index: + """Create a new or update an existing Index with the given version id. - :param id: Identifier of the evaluation. Required. - :type id: str - :param resource: The resource instance. Is one of the following types: Evaluation, JSON, - IO[bytes] Required. - :type resource: ~azure.ai.projects.models.Evaluation or JSON or IO[bytes] - :return: Evaluation. The Evaluation is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Evaluation + :param name: The name of the resource. Required. + :type name: str + :param version: The specific version id of the Index to create or replace. Required. + :type version: str + :param pending_upload_request: The definition of the Index to create or update. Is one of the + following types: Index, JSON, IO[bytes] Required. + :type pending_upload_request: ~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 = { @@ -7342,17 +2473,18 @@ def update( _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models.Evaluation] = kwargs.pop("cls", None) + cls: ClsType[_models.Index] = kwargs.pop("cls", None) - content_type = content_type or "application/merge-patch+json" + content_type = content_type or "application/json" _content = None - if isinstance(resource, (IOBase, bytes)): - _content = resource + if isinstance(pending_upload_request, (IOBase, bytes)): + _content = pending_upload_request else: - _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(pending_upload_request, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - _request = build_evaluations_update_request( - id=id, + _request = build_indexes_create_or_update_request( + name=name, + version=version, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -7360,12 +2492,7 @@ def update( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -7376,7 +2503,7 @@ def update( 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 @@ -7385,30 +2512,42 @@ def update( 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() else: - deserialized = _deserialize(_models.Evaluation, response.json()) + deserialized = _deserialize(_models.Index, response.json()) if cls: - return cls(pipeline_response, deserialized, response_headers) # type: ignore + 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): + 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_schedule(self, name: str, **kwargs: Any) -> _models.EvaluationSchedule: - """Resource read operation template. + def get(self, name: str, **kwargs: Any) -> _models.Deployment: + """Get a deployed model. - :param name: Name of the schedule, which also serves as the unique identifier for the - evaluation. Required. + :param name: Name of the deployment. Required. :type name: str - :return: EvaluationSchedule. The EvaluationSchedule is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationSchedule + :return: Deployment. The Deployment is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.Deployment :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -7422,21 +2561,16 @@ def get_schedule(self, name: str, **kwargs: Any) -> _models.EvaluationSchedule: _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls: ClsType[_models.EvaluationSchedule] = kwargs.pop("cls", None) + cls: ClsType[_models.Deployment] = kwargs.pop("cls", None) - _request = build_evaluations_get_schedule_request( + _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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -7464,84 +2598,153 @@ def get_schedule(self, name: str, **kwargs: Any) -> _models.EvaluationSchedule: if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.EvaluationSchedule, response.json()) + deserialized = _deserialize(_models.Deployment, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore return deserialized # type: ignore - @overload - def create_or_replace_schedule( - self, name: str, resource: _models.EvaluationSchedule, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationSchedule: - """Create or replace operation template. + @distributed_trace + def list( + self, + *, + model_publisher: Optional[str] = None, + model_name: Optional[str] = None, + deployment_type: Optional[Union[str, _models.DeploymentType]] = None, + top: Optional[int] = None, + skip: Optional[int] = None, + **kwargs: Any + ) -> Iterable["_models.Deployment"]: + """List all deployed models in the project. - :param name: Name of the schedule, which also serves as the unique identifier for the - evaluation. Required. - :type name: str - :param resource: The resource instance. Required. - :type resource: ~azure.ai.projects.models.EvaluationSchedule - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationSchedule. The EvaluationSchedule is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationSchedule + :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 + :keyword top: The number of result items to return. Default value is None. + :paramtype top: int + :keyword skip: The number of result items to skip. Default value is None. + :paramtype skip: int + :return: 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 {} - @overload - def create_or_replace_schedule( - self, name: str, resource: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationSchedule: - """Create or replace operation template. + maxpagesize = kwargs.pop("maxpagesize", None) + cls: ClsType[List[_models.Deployment]] = kwargs.pop("cls", None) - :param name: Name of the schedule, which also serves as the unique identifier for the - evaluation. Required. - :type name: str - :param resource: The resource instance. Required. - :type resource: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationSchedule. The EvaluationSchedule is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationSchedule - :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_replace_schedule( - self, name: str, resource: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.EvaluationSchedule: - """Create or replace operation template. + def prepare_request(next_link=None): + if not next_link: - :param name: Name of the schedule, which also serves as the unique identifier for the - evaluation. Required. - :type name: str - :param resource: The resource instance. Required. - :type resource: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: EvaluationSchedule. The EvaluationSchedule is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationSchedule - :raises ~azure.core.exceptions.HttpResponseError: - """ + _request = build_deployments_list_request( + model_publisher=model_publisher, + model_name=model_name, + deployment_type=deployment_type, + top=top, + skip=skip, + maxpagesize=maxpagesize, + 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) - @distributed_trace - def create_or_replace_schedule( - self, name: str, resource: Union[_models.EvaluationSchedule, JSON, IO[bytes]], **kwargs: Any - ) -> _models.EvaluationSchedule: - """Create or replace operation template. + 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 RedTeamsOperations: + """ + .. 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): + 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: Name of the schedule, which also serves as the unique identifier for the - evaluation. Required. + @distributed_trace + @api_version_validation( + method_added_on="2025-05-15-preview", + params_added_on={"2025-05-15-preview": ["api_version", "name", "client_request_id", "accept"]}, + ) + def get(self, name: str, **kwargs: Any) -> _models.RedTeam: + """Get a redteam by name. + + :param name: Identifier of the red team. Required. :type name: str - :param resource: The resource instance. Is one of the following types: EvaluationSchedule, - JSON, IO[bytes] Required. - :type resource: ~azure.ai.projects.models.EvaluationSchedule or JSON or IO[bytes] - :return: EvaluationSchedule. The EvaluationSchedule is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.EvaluationSchedule + :return: RedTeam. The RedTeam is compatible with MutableMapping + :rtype: ~azure.ai.projects.models.RedTeam :raises ~azure.core.exceptions.HttpResponseError: """ error_map: MutableMapping = { @@ -7552,34 +2755,19 @@ def create_or_replace_schedule( } 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.EvaluationSchedule] = kwargs.pop("cls", None) - - content_type = content_type or "application/json" - _content = None - if isinstance(resource, (IOBase, bytes)): - _content = resource - else: - _content = json.dumps(resource, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + cls: ClsType[_models.RedTeam] = kwargs.pop("cls", None) - _request = build_evaluations_create_or_replace_schedule_request( + _request = build_red_teams_get_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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) @@ -7590,7 +2778,7 @@ def create_or_replace_schedule( 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 @@ -7607,7 +2795,7 @@ def create_or_replace_schedule( if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize(_models.EvaluationSchedule, response.json()) + deserialized = _deserialize(_models.RedTeam, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -7615,24 +2803,30 @@ def create_or_replace_schedule( return deserialized # type: ignore @distributed_trace - def list_schedule( + @api_version_validation( + method_added_on="2025-05-15-preview", + params_added_on={ + "2025-05-15-preview": ["api_version", "top", "skip", "maxpagesize", "client_request_id", "accept"] + }, + ) + def list( self, *, top: Optional[int] = None, skip: Optional[int] = None, **kwargs: Any - ) -> Iterable["_models.EvaluationSchedule"]: - """Resource list operation template. + ) -> Iterable["_models.RedTeam"]: + """List a redteam by name. :keyword top: The number of result items to return. Default value is None. :paramtype top: int :keyword skip: The number of result items to skip. Default value is None. :paramtype skip: int - :return: An iterator like instance of EvaluationSchedule - :rtype: ~azure.core.paging.ItemPaged[~azure.ai.projects.models.EvaluationSchedule] + :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 {} maxpagesize = kwargs.pop("maxpagesize", None) - cls: ClsType[List[_models.EvaluationSchedule]] = kwargs.pop("cls", None) + cls: ClsType[List[_models.RedTeam]] = kwargs.pop("cls", None) error_map: MutableMapping = { 401: ClientAuthenticationError, @@ -7645,7 +2839,7 @@ def list_schedule( def prepare_request(next_link=None): if not next_link: - _request = build_evaluations_list_schedule_request( + _request = build_red_teams_list_request( top=top, skip=skip, maxpagesize=maxpagesize, @@ -7654,14 +2848,9 @@ def prepare_request(next_link=None): params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), - "subscriptionId": self._serialize.url( - "self._config.subscription_id", self._config.subscription_id, "str" - ), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -7679,14 +2868,9 @@ def prepare_request(next_link=None): "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"), - "subscriptionId": self._serialize.url( - "self._config.subscription_id", self._config.subscription_id, "str" + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -7694,7 +2878,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.EvaluationSchedule], deserialized.get("value", [])) + 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, iter(list_of_elem) @@ -7716,14 +2900,65 @@ def get_next(next_link=None): return ItemPaged(get_next, extract_data) - @distributed_trace - def disable_schedule(self, name: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """Disable the evaluation schedule. + @overload + def create_run( + self, red_team: _models.RedTeam, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.RedTeam: + """Creates a redteam run. - :param name: Name of the evaluation schedule. Required. - :type name: str - :return: None - :rtype: None + :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_run(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 + def create_run( + 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 + @api_version_validation( + method_added_on="2025-05-15-preview", + params_added_on={"2025-05-15-preview": ["api_version", "content_type", "accept"]}, + ) + def create_run(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. + :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 = { @@ -7734,37 +2969,53 @@ def disable_schedule(self, name: str, **kwargs: Any) -> None: # pylint: disable } 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.RedTeam] = kwargs.pop("cls", None) - _request = build_evaluations_disable_schedule_request( - name=name, + 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_red_teams_create_run_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"), - "subscriptionId": self._serialize.url("self._config.subscription_id", self._config.subscription_id, "str"), - "resourceGroupName": self._serialize.url( - "self._config.resource_group_name", self._config.resource_group_name, "str" - ), - "projectName": self._serialize.url("self._config.project_name", self._config.project_name, "str"), + "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 + _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) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.RedTeam, response.json()) + if cls: - return cls(pipeline_response, None, {}) # type: ignore + return cls(pipeline_response, deserialized, {}) # type: ignore + + return 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 c166be8df503..8bcb627aa475 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 @@ -1,3437 +1,15 @@ -# pylint: disable=too-many-lines,line-too-long,useless-suppression -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -import io -import logging -import os -import sys -import time -import json -from pathlib import Path -from typing import ( - IO, - TYPE_CHECKING, - Any, - Dict, - Iterator, - List, - Optional, - Sequence, - TextIO, - Union, - Callable, - Set, - cast, - overload, -) +from typing import List -from azure.core.exceptions import ResourceNotFoundError -from azure.core.tracing.decorator import distributed_trace - -from .. import models as _models -from .._vendor import FileType -from ..models._enums import AuthenticationType, ConnectionType, FilePurpose, RunStatus -from ..models._models import ( - GetAppInsightsResponse, - GetConnectionResponse, - GetWorkspaceResponse, - InternalConnectionPropertiesSASAuth, - ListConnectionsResponse, -) -from ..models._patch import ConnectionProperties -from ._operations import AgentsOperations as AgentsOperationsGenerated -from ._operations import ConnectionsOperations as ConnectionsOperationsGenerated -from ._operations import TelemetryOperations as TelemetryOperationsGenerated - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from openai import AzureOpenAI - - from azure.ai.inference import ChatCompletionsClient, EmbeddingsClient, ImageEmbeddingsClient - - from .. import _types - -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object -_Unset: Any = object() - -logger = logging.getLogger(__name__) - - -class InferenceOperations: - - def __init__(self, outer_instance): - - # All returned inference clients will have this application id set on their user-agent. - # For more info on user-agent HTTP header, see: - # https://azure.github.io/azure-sdk/general_azurecore.html#telemetry-policy - USER_AGENT_APP_ID = "AIProjectClient" - - if hasattr(outer_instance, "_user_agent") and outer_instance._user_agent: - # If the calling application has set "user_agent" when constructing the AIProjectClient, - # take that value and prepend it to USER_AGENT_APP_ID. - self._user_agent = f"{outer_instance._user_agent}-{USER_AGENT_APP_ID}" - else: - self._user_agent = USER_AGENT_APP_ID - - self._outer_instance = outer_instance - - @distributed_trace - def get_chat_completions_client( - self, *, connection_name: Optional[str] = None, **kwargs - ) -> "ChatCompletionsClient": - """Get an authenticated ChatCompletionsClient (from the package azure-ai-inference) for the default - Azure AI Services connected resource (if `connection_name` is not specificed), or from the Azure AI - Services resource given by its connection name. Keyword arguments are passed to the constructor of - ChatCompletionsClient. - - At least one AI model that supports chat completions must be deployed in this resource. - - .. note:: The package `azure-ai-inference` must be installed prior to calling this method. - - :keyword connection_name: The name of a connection to an Azure AI Services resource in your AI Foundry project. - resource. Optional. If not provided, the default Azure AI Services connection will be used. - :type connection_name: str - - :return: An authenticated chat completions client. - :rtype: ~azure.ai.inference.ChatCompletionsClient - - :raises ~azure.core.exceptions.ResourceNotFoundError: if an Azure AI Services connection - does not exist. - :raises ~azure.core.exceptions.ModuleNotFoundError: if the `azure-ai-inference` package - is not installed. - :raises ValueError: if the connection name is an empty string. - :raises ~azure.core.exceptions.HttpResponseError: - """ - kwargs.setdefault("merge_span", True) - - if connection_name is not None and not connection_name: - raise ValueError("Connection name cannot be empty") - - # Back-door way to access the old behavior where each AI model (non-OpenAI) was hosted on - # a separate "Serverless" connection. This is now deprecated. - use_serverless_connection: bool = os.getenv("USE_SERVERLESS_CONNECTION", None) == "true" - - if connection_name: - connection = self._outer_instance.connections.get(connection_name=connection_name, include_credentials=True) - else: - if use_serverless_connection: - connection = self._outer_instance.connections.get_default( - connection_type=ConnectionType.SERVERLESS, include_credentials=True - ) - else: - connection = self._outer_instance.connections.get_default( - connection_type=ConnectionType.AZURE_AI_SERVICES, include_credentials=True - ) - - logger.debug("[InferenceOperations.get_chat_completions_client] connection = %s", str(connection)) - - try: - from azure.ai.inference import ChatCompletionsClient - except ModuleNotFoundError as e: - raise ModuleNotFoundError( - "Azure AI Inference SDK is not installed. Please install it using 'pip install azure-ai-inference'" - ) from e - - if use_serverless_connection: - endpoint = connection.endpoint_url - credential_scopes = ["https://ml.azure.com/.default"] - else: - endpoint = f"{connection.endpoint_url}/models" - credential_scopes = ["https://cognitiveservices.azure.com/.default"] - - if connection.authentication_type == AuthenticationType.API_KEY: - logger.debug( - "[InferenceOperations.get_chat_completions_client] " - + "Creating ChatCompletionsClient using API key authentication" - ) - from azure.core.credentials import AzureKeyCredential - - client = ChatCompletionsClient( - endpoint=endpoint, - credential=AzureKeyCredential(connection.key), - user_agent=kwargs.pop("user_agent", self._user_agent), - **kwargs, - ) - elif connection.authentication_type == AuthenticationType.ENTRA_ID: - logger.debug( - "[InferenceOperations.get_chat_completions_client] " - + "Creating ChatCompletionsClient using Entra ID authentication" - ) - client = ChatCompletionsClient( - endpoint=endpoint, - credential=connection.token_credential, - credential_scopes=credential_scopes, - user_agent=kwargs.pop("user_agent", self._user_agent), - **kwargs, - ) - elif connection.authentication_type == AuthenticationType.SAS: - logger.debug( - "[InferenceOperations.get_chat_completions_client] " - + "Creating ChatCompletionsClient using SAS authentication" - ) - raise ValueError( - "Getting chat completions client from a connection with SAS authentication is not yet supported" - ) - else: - raise ValueError("Unknown authentication type") - - return client - - @distributed_trace - def get_embeddings_client(self, *, connection_name: Optional[str] = None, **kwargs) -> "EmbeddingsClient": - """Get an authenticated EmbeddingsClient (from the package azure-ai-inference) for the default - Azure AI Services connected resource (if `connection_name` is not specificed), or from the Azure AI - Services resource given by its connection name. Keyword arguments are passed to the constructor of - EmbeddingsClient. - - At least one AI model that supports text embeddings must be deployed in this resource. - - .. note:: The package `azure-ai-inference` must be installed prior to calling this method. - - :keyword connection_name: The name of a connection to an Azure AI Services resource in your AI Foundry project. - resource. Optional. If not provided, the default Azure AI Services connection will be used. - :type connection_name: str - - :return: An authenticated text embeddings client - :rtype: ~azure.ai.inference.EmbeddingsClient - - :raises ~azure.core.exceptions.ResourceNotFoundError: if an Azure AI Services connection - does not exist. - :raises ~azure.core.exceptions.ModuleNotFoundError: if the `azure-ai-inference` package - is not installed. - :raises ValueError: if the connection name is an empty string. - :raises ~azure.core.exceptions.HttpResponseError: - """ - kwargs.setdefault("merge_span", True) - - if connection_name is not None and not connection_name: - raise ValueError("Connection name cannot be empty") - - # Back-door way to access the old behavior where each AI model (non-OpenAI) was hosted on - # a separate "Serverless" connection. This is now deprecated. - use_serverless_connection: bool = os.getenv("USE_SERVERLESS_CONNECTION", None) == "true" - - if connection_name: - connection = self._outer_instance.connections.get(connection_name=connection_name, include_credentials=True) - else: - if use_serverless_connection: - connection = self._outer_instance.connections.get_default( - connection_type=ConnectionType.SERVERLESS, include_credentials=True - ) - else: - connection = self._outer_instance.connections.get_default( - connection_type=ConnectionType.AZURE_AI_SERVICES, include_credentials=True - ) - - logger.debug("[InferenceOperations.get_embeddings_client] connection = %s", str(connection)) - - try: - from azure.ai.inference import EmbeddingsClient - except ModuleNotFoundError as e: - raise ModuleNotFoundError( - "Azure AI Inference SDK is not installed. Please install it using 'pip install azure-ai-inference'" - ) from e - - if use_serverless_connection: - endpoint = connection.endpoint_url - credential_scopes = ["https://ml.azure.com/.default"] - else: - endpoint = f"{connection.endpoint_url}/models" - credential_scopes = ["https://cognitiveservices.azure.com/.default"] - - if connection.authentication_type == AuthenticationType.API_KEY: - logger.debug( - "[InferenceOperations.get_embeddings_client] Creating EmbeddingsClient using API key authentication" - ) - from azure.core.credentials import AzureKeyCredential - - client = EmbeddingsClient( - endpoint=endpoint, - credential=AzureKeyCredential(connection.key), - user_agent=kwargs.pop("user_agent", self._user_agent), - **kwargs, - ) - elif connection.authentication_type == AuthenticationType.ENTRA_ID: - logger.debug( - "[InferenceOperations.get_embeddings_client] Creating EmbeddingsClient using Entra ID authentication" - ) - client = EmbeddingsClient( - endpoint=endpoint, - credential=connection.token_credential, - credential_scopes=credential_scopes, - user_agent=kwargs.pop("user_agent", self._user_agent), - **kwargs, - ) - elif connection.authentication_type == AuthenticationType.SAS: - logger.debug( - "[InferenceOperations.get_embeddings_client] Creating EmbeddingsClient using SAS authentication" - ) - raise ValueError("Getting embeddings client from a connection with SAS authentication is not yet supported") - else: - raise ValueError("Unknown authentication type") - - return client - - @distributed_trace - def get_image_embeddings_client( - self, *, connection_name: Optional[str] = None, **kwargs - ) -> "ImageEmbeddingsClient": - """Get an authenticated ImageEmbeddingsClient (from the package azure-ai-inference) for the default - Azure AI Services connected resource (if `connection_name` is not specificed), or from the Azure AI - Services resource given by its connection name. Keyword arguments are passed to the constructor of - ImageEmbeddingsClient. - - At least one AI model that supports image embeddings must be deployed in this resource. - - .. note:: The package `azure-ai-inference` must be installed prior to calling this method. - - :keyword connection_name: The name of a connection to an Azure AI Services resource in your AI Foundry project. - resource. Optional. If not provided, the default Azure AI Services connection will be used. - :type connection_name: str - - :return: An authenticated image embeddings client - :rtype: ~azure.ai.inference.ImageEmbeddingsClient - - :raises ~azure.core.exceptions.ResourceNotFoundError: if an Azure AI Services connection - does not exist. - :raises ~azure.core.exceptions.ModuleNotFoundError: if the `azure-ai-inference` package - is not installed. - :raises ValueError: if the connection name is an empty string. - :raises ~azure.core.exceptions.HttpResponseError: - """ - kwargs.setdefault("merge_span", True) - - if connection_name is not None and not connection_name: - raise ValueError("Connection name cannot be empty") - - # Back-door way to access the old behavior where each AI model (non-OpenAI) was hosted on - # a separate "Serverless" connection. This is now deprecated. - use_serverless_connection: bool = os.getenv("USE_SERVERLESS_CONNECTION", None) == "true" - - if connection_name: - connection = self._outer_instance.connections.get(connection_name=connection_name, include_credentials=True) - else: - if use_serverless_connection: - connection = self._outer_instance.connections.get_default( - connection_type=ConnectionType.SERVERLESS, include_credentials=True - ) - else: - connection = self._outer_instance.connections.get_default( - connection_type=ConnectionType.AZURE_AI_SERVICES, include_credentials=True - ) - - logger.debug("[InferenceOperations.get_embeddings_client] connection = %s", str(connection)) - - try: - from azure.ai.inference import ImageEmbeddingsClient - except ModuleNotFoundError as e: - raise ModuleNotFoundError( - "Azure AI Inference SDK is not installed. Please install it using 'pip install azure-ai-inference'" - ) from e - - if use_serverless_connection: - endpoint = connection.endpoint_url - credential_scopes = ["https://ml.azure.com/.default"] - else: - endpoint = f"{connection.endpoint_url}/models" - credential_scopes = ["https://cognitiveservices.azure.com/.default"] - - if connection.authentication_type == AuthenticationType.API_KEY: - logger.debug( - "[InferenceOperations.get_image_embeddings_client] " - "Creating ImageEmbeddingsClient using API key authentication" - ) - from azure.core.credentials import AzureKeyCredential - - client = ImageEmbeddingsClient( - endpoint=endpoint, - credential=AzureKeyCredential(connection.key), - user_agent=kwargs.pop("user_agent", self._user_agent), - **kwargs, - ) - elif connection.authentication_type == AuthenticationType.ENTRA_ID: - logger.debug( - "[InferenceOperations.get_image_embeddings_client] " - "Creating ImageEmbeddingsClient using Entra ID authentication" - ) - client = ImageEmbeddingsClient( - endpoint=endpoint, - credential=connection.token_credential, - credential_scopes=credential_scopes, - user_agent=kwargs.pop("user_agent", self._user_agent), - **kwargs, - ) - elif connection.authentication_type == AuthenticationType.SAS: - logger.debug( - "[InferenceOperations.get_image_embeddings_client] " - "Creating ImageEmbeddingsClient using SAS authentication" - ) - raise ValueError( - "Getting image embeddings client from a connection with SAS authentication is not yet supported" - ) - else: - raise ValueError("Unknown authentication type") - - return client - - @distributed_trace - def get_azure_openai_client( - self, *, api_version: Optional[str] = None, connection_name: Optional[str] = None, **kwargs - ) -> "AzureOpenAI": - """Get an authenticated AzureOpenAI client (from the `openai` package) for the default - Azure OpenAI connection (if `connection_name` is not specificed), or from the Azure OpenAI - resource given by its connection name. - - .. note:: The package `openai` must be installed prior to calling this method. - - :keyword api_version: The Azure OpenAI api-version to use when creating the client. Optional. - See "Data plane - Inference" row in the table at - https://learn.microsoft.com/azure/ai-services/openai/reference#api-specs. If this keyword - is not specified, you must set the environment variable `OPENAI_API_VERSION` instead. - :paramtype api_version: str - :keyword connection_name: The name of a connection to an Azure OpenAI resource in your AI Foundry project. - resource. Optional. If not provided, the default Azure OpenAI connection will be used. - :type connection_name: str - - :return: An authenticated AzureOpenAI client - :rtype: ~openai.AzureOpenAI - - :raises ~azure.core.exceptions.ResourceNotFoundError: if an Azure OpenAI connection - does not exist. - :raises ~azure.core.exceptions.ModuleNotFoundError: if the `openai` package - is not installed. - :raises ValueError: if the connection name is an empty string. - :raises ~azure.core.exceptions.HttpResponseError: - """ - kwargs.setdefault("merge_span", True) - - if connection_name is not None and not connection_name: - raise ValueError("Connection name cannot be empty") - - if connection_name: - connection = self._outer_instance.connections.get( - connection_name=connection_name, include_credentials=True, **kwargs - ) - else: - connection = self._outer_instance.connections.get_default( - connection_type=ConnectionType.AZURE_OPEN_AI, include_credentials=True, **kwargs - ) - - logger.debug("[InferenceOperations.get_azure_openai_client] connection = %s", str(connection)) - - try: - from openai import AzureOpenAI - except ModuleNotFoundError as e: - raise ModuleNotFoundError( - "OpenAI SDK is not installed. Please install it using 'pip install openai'" - ) from e - - if connection.authentication_type == AuthenticationType.API_KEY: - logger.debug( - "[InferenceOperations.get_azure_openai_client] Creating AzureOpenAI using API key authentication" - ) - client = AzureOpenAI( - api_key=connection.key, azure_endpoint=connection.endpoint_url, api_version=api_version - ) - elif connection.authentication_type == AuthenticationType.ENTRA_ID: - logger.debug( - "[InferenceOperations.get_azure_openai_client] " + "Creating AzureOpenAI using Entra ID authentication" - ) - try: - from azure.identity import get_bearer_token_provider - except ModuleNotFoundError as e: - raise ModuleNotFoundError( - "azure.identity package not installed. Please install it using 'pip install azure.identity'" - ) from e - client = AzureOpenAI( - # See https://learn.microsoft.com/python/api/azure-identity/azure.identity?view=azure-python#azure-identity-get-bearer-token-provider # pylint: disable=line-too-long - azure_ad_token_provider=get_bearer_token_provider( - connection.token_credential, "https://cognitiveservices.azure.com/.default" - ), - azure_endpoint=connection.endpoint_url, - api_version=api_version, - ) - elif connection.authentication_type == AuthenticationType.SAS: - logger.debug( - "[InferenceOperations.get_azure_openai_client] " + "Creating AzureOpenAI using SAS authentication" - ) - raise ValueError( - "Getting an AzureOpenAI client from a connection with SAS authentication is not yet supported" - ) - else: - raise ValueError("Unknown authentication type") - - return client - - -class ConnectionsOperations(ConnectionsOperationsGenerated): - - @distributed_trace - def get_default( - self, *, connection_type: ConnectionType, include_credentials: bool = False, **kwargs: Any - ) -> ConnectionProperties: - """Get the properties of the default connection of a certain connection type, with or without - populating authentication credentials. Raises ~azure.core.exceptions.ResourceNotFoundError - exception if there are no connections of the given type. - - .. note:: - `get_default(connection_type=ConnectionType.AZURE_BLOB_STORAGE, include_credentials=True)` does not - currently work. It does work with `include_credentials=False`. - - :keyword connection_type: The connection type. Required. - :type connection_type: ~azure.ai.projects.models._models.ConnectionType - :keyword include_credentials: Whether to populate the connection properties with authentication credentials. - Optional. - :type include_credentials: bool - :return: The connection properties. - :rtype: ~azure.ai.projects.models.ConnectionProperties - :raises ~azure.core.exceptions.ResourceNotFoundError: - :raises ~azure.core.exceptions.HttpResponseError: - """ - kwargs.setdefault("merge_span", True) - if not connection_type: - raise ValueError("You must specify an connection type") - # Since there is no notion of default connection at the moment, list all connections in the category - # and return the first one (index 0), unless overridden by the environment variable DEFAULT_CONNECTION_INDEX. - connection_properties_list = self.list(connection_type=connection_type, **kwargs) - if len(connection_properties_list) > 0: - default_connection_index = int(os.getenv("DEFAULT_CONNECTION_INDEX", "0")) - if include_credentials: - return self.get( - connection_name=connection_properties_list[default_connection_index].name, - include_credentials=include_credentials, - **kwargs, - ) - return connection_properties_list[default_connection_index] - raise ResourceNotFoundError(f"No connection of type {connection_type} found") - - @distributed_trace - def get(self, *, connection_name: str, include_credentials: bool = False, **kwargs: Any) -> ConnectionProperties: - """Get the properties of a single connection, given its connection name, with or without - populating authentication credentials. Raises ~azure.core.exceptions.ResourceNotFoundError - exception if a connection with the given name was not found. - - .. note:: This method is not supported for Azure Blob Storage connections. - - :keyword connection_name: Connection Name. Required. - :type connection_name: str - :keyword include_credentials: Whether to populate the connection properties with authentication credentials. - Optional. - :type include_credentials: bool - :return: The connection properties, or `None` if a connection with this name does not exist. - :rtype: ~azure.ai.projects.models.ConnectionProperties - :raises ~azure.core.exceptions.ResourceNotFoundError: - :raises ~azure.core.exceptions.HttpResponseError: - """ - kwargs.setdefault("merge_span", True) - if not connection_name: - raise ValueError("Connection name cannot be empty") - if include_credentials: - connection: GetConnectionResponse = self._get_connection_with_secrets( - connection_name=connection_name, ignored="ignore", **kwargs - ) - if connection.properties.auth_type == AuthenticationType.ENTRA_ID: - return ConnectionProperties(connection=connection, token_credential=self._config.credential) - if connection.properties.auth_type == AuthenticationType.SAS: - from ..models._patch import SASTokenCredential - - cred_prop = cast(InternalConnectionPropertiesSASAuth, connection.properties) - - token_credential = SASTokenCredential( - sas_token=cred_prop.credentials.sas, - credential=self._config.credential, - subscription_id=self._config.subscription_id, - resource_group_name=self._config.resource_group_name, - project_name=self._config.project_name, - connection_name=connection_name, - ) - return ConnectionProperties(connection=connection, token_credential=token_credential) - - return ConnectionProperties(connection=connection) - connection = self._get_connection(connection_name=connection_name, **kwargs) - return ConnectionProperties(connection=connection) - - @distributed_trace - def list( - self, *, connection_type: Optional[ConnectionType] = None, **kwargs: Any - ) -> Sequence[ConnectionProperties]: - """List the properties of all connections, or all connections of a certain connection type. - - :keyword connection_type: The connection type. Optional. If provided, this method lists connections of this - type. If not provided, all connections are listed. - :type connection_type: ~azure.ai.projects.models._models.ConnectionType - :return: A list of connection properties - :rtype: Sequence[~azure.ai.projects.models._models.ConnectionProperties] - :raises ~azure.core.exceptions.HttpResponseError: - """ - kwargs.setdefault("merge_span", True) - connections_list: ListConnectionsResponse = self._list_connections( - include_all=True, category=connection_type, **kwargs - ) - - # Iterate to create the simplified result property - connection_properties_list: List[ConnectionProperties] = [] - for connection in connections_list.value: - connection_properties_list.append(ConnectionProperties(connection=connection)) - - return connection_properties_list - - -# Internal helper functions to enable OpenTelemetry, used by both sync and async clients -def _get_trace_exporter(destination: Union[TextIO, str, None]) -> Any: - if isinstance(destination, str): - # `destination` is the OTLP endpoint - # See: https://opentelemetry-python.readthedocs.io/en/latest/exporter/otlp/otlp.html#usage - try: - from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter # type: ignore - except ModuleNotFoundError as e: - raise ModuleNotFoundError( - "OpenTelemetry OTLP exporter is not installed. " - + "Please install it using 'pip install opentelemetry-exporter-otlp-proto-grpc'" - ) from e - return OTLPSpanExporter(endpoint=destination) - - if isinstance(destination, io.TextIOWrapper): - if destination is sys.stdout: - # See: https://opentelemetry-python.readthedocs.io/en/latest/sdk/trace.export.html#opentelemetry.sdk.trace.export.ConsoleSpanExporter # pylint: disable=line-too-long - try: - from opentelemetry.sdk.trace.export import ConsoleSpanExporter - except ModuleNotFoundError as e: - raise ModuleNotFoundError( - "OpenTelemetry SDK is not installed. Please install it using 'pip install opentelemetry-sdk'" - ) from e - - return ConsoleSpanExporter() - raise ValueError("Only `sys.stdout` is supported at the moment for type `TextIO`") - - return None - - -def _get_log_exporter(destination: Union[TextIO, str, None]) -> Any: - if isinstance(destination, str): - # `destination` is the OTLP endpoint - # See: https://opentelemetry-python.readthedocs.io/en/latest/exporter/otlp/otlp.html#usage - try: - # _logs are considered beta (not internal) in OpenTelemetry Python API/SDK. - # So it's ok to use it for local development, but we'll swallow - # any errors in case of any breaking changes on OTel side. - from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter # type: ignore # pylint: disable=import-error,no-name-in-module - except Exception as ex: # pylint: disable=broad-exception-caught - # since OTel logging is still in beta in Python, we're going to swallow any errors - # and just warn about them. - logger.warning("Failed to configure OpenTelemetry logging.", exc_info=ex) - return None - - return OTLPLogExporter(endpoint=destination) - - if isinstance(destination, io.TextIOWrapper): - if destination is sys.stdout: - # See: https://opentelemetry-python.readthedocs.io/en/latest/sdk/trace.export.html#opentelemetry.sdk.trace.export.ConsoleSpanExporter # pylint: disable=line-too-long - try: - from opentelemetry.sdk._logs.export import ConsoleLogExporter - - return ConsoleLogExporter() - except ModuleNotFoundError as ex: - # since OTel logging is still in beta in Python, we're going to swallow any errors - # and just warn about them. - logger.warning("Failed to configure OpenTelemetry logging.", exc_info=ex) - return None - raise ValueError("Only `sys.stdout` is supported at the moment for type `TextIO`") - - return None - - -def _configure_tracing(span_exporter: Any) -> None: - if span_exporter is None: - return - - try: - from opentelemetry import trace - from opentelemetry.sdk.trace import TracerProvider - from opentelemetry.sdk.trace.export import SimpleSpanProcessor - except ModuleNotFoundError as e: - raise ModuleNotFoundError( - "OpenTelemetry SDK is not installed. Please install it using 'pip install opentelemetry-sdk'" - ) from e - - # if tracing was not setup before, we need to create a new TracerProvider - if not isinstance(trace.get_tracer_provider(), TracerProvider): - # If the provider is NoOpTracerProvider, we need to create a new TracerProvider - provider = TracerProvider() - trace.set_tracer_provider(provider) - - # get_tracer_provider returns opentelemetry.trace.TracerProvider - # however, we have opentelemetry.sdk.trace.TracerProvider, which implements - # add_span_processor method, though we need to cast it to fix type checking. - provider = cast(TracerProvider, trace.get_tracer_provider()) - provider.add_span_processor(SimpleSpanProcessor(span_exporter)) - - -def _configure_logging(log_exporter: Any) -> None: - if log_exporter is None: - return - - try: - # _events and _logs are considered beta (not internal) in - # OpenTelemetry Python API/SDK. - # So it's ok to use them for local development, but we'll swallow - # any errors in case of any breaking changes on OTel side. - from opentelemetry import _logs, _events - from opentelemetry.sdk._logs import LoggerProvider # pylint: disable=import-error,no-name-in-module - from opentelemetry.sdk._events import EventLoggerProvider # pylint: disable=import-error,no-name-in-module - from opentelemetry.sdk._logs.export import ( - SimpleLogRecordProcessor, - ) # pylint: disable=import-error,no-name-in-module - - if not isinstance(_logs.get_logger_provider(), LoggerProvider): - logger_provider = LoggerProvider() - _logs.set_logger_provider(logger_provider) - - # get_logger_provider returns opentelemetry._logs.LoggerProvider - # however, we have opentelemetry.sdk._logs.LoggerProvider, which implements - # add_log_record_processor method, though we need to cast it to fix type checking. - logger_provider = cast(LoggerProvider, _logs.get_logger_provider()) - logger_provider.add_log_record_processor(SimpleLogRecordProcessor(log_exporter)) - _events.set_event_logger_provider(EventLoggerProvider(logger_provider)) - except Exception as ex: # pylint: disable=broad-exception-caught - # since OTel logging is still in beta in Python, we're going to swallow any errors - # and just warn about them. - logger.warning("Failed to configure OpenTelemetry logging.", exc_info=ex) - - -def _enable_telemetry(destination: Union[TextIO, str, None], **kwargs) -> None: # pylint: disable=unused-argument - """Enable tracing and logging to console (sys.stdout), or to an OpenTelemetry Protocol (OTLP) endpoint. - - :param destination: `sys.stdout` to print telemetry to console or a string holding the - OpenTelemetry protocol (OTLP) endpoint. - If not provided, this method enables instrumentation, but does not configure OpenTelemetry - SDK to export traces and logs. - :type destination: Union[TextIO, str, None] - """ - span_exporter = _get_trace_exporter(destination) - _configure_tracing(span_exporter) - - log_exporter = _get_log_exporter(destination) - _configure_logging(log_exporter) - - # Silently try to load a set of relevant Instrumentors - try: - from azure.core.settings import settings - - settings.tracing_implementation = "opentelemetry" - except ModuleNotFoundError: - logger.warning( - "Azure SDK tracing plugin is not installed. " - + "Please install it using 'pip install azure-core-tracing-opentelemetry'" - ) - - try: - from azure.ai.inference.tracing import AIInferenceInstrumentor # type: ignore - - inference_instrumentor = AIInferenceInstrumentor() - if not inference_instrumentor.is_instrumented(): - inference_instrumentor.instrument() - except ModuleNotFoundError: - logger.warning( - "Could not call `AIInferenceInstrumentor().instrument()` since `azure-ai-inference` is not installed" - ) - - try: - from azure.ai.projects.telemetry.agents import AIAgentsInstrumentor - - agents_instrumentor = AIAgentsInstrumentor() - if not agents_instrumentor.is_instrumented(): - agents_instrumentor.instrument() - except Exception as exc: # pylint: disable=broad-exception-caught - logger.warning("Could not call `AIAgentsInstrumentor().instrument()`", exc_info=exc) - - try: - from opentelemetry.instrumentation.openai_v2 import OpenAIInstrumentor # type: ignore - - OpenAIInstrumentor().instrument() - except ModuleNotFoundError: - logger.warning( - "Could not call `OpenAIInstrumentor().instrument()` since " - + "`opentelemetry-instrumentation-openai-v2` is not installed" - ) - - try: - from opentelemetry.instrumentation.langchain import LangchainInstrumentor # type: ignore - - LangchainInstrumentor().instrument() - except ModuleNotFoundError: - logger.warning( - "Could not call LangchainInstrumentor().instrument()` since " - + "`opentelemetry-instrumentation-langchain` is not installed" - ) - - -class TelemetryOperations(TelemetryOperationsGenerated): - - _connection_string: Optional[str] = None - - def __init__(self, *args, **kwargs): - self._outer_instance = kwargs.pop("outer_instance") - super().__init__(*args, **kwargs) - - def get_connection_string(self) -> str: - """Get the Application Insights connection string associated with the Project's Application Insights resource. - - :return: The Application Insights connection string if a the resource was enabled for the Project. - :rtype: str - :raises ~azure.core.exceptions.ResourceNotFoundError: An Application Insights resource was not - enabled for this project. - """ - if not self._connection_string: - # Get the AI Foundry project properties, including Application Insights resource URL if exists - get_workspace_response: GetWorkspaceResponse = ( - self._outer_instance.connections._get_workspace() # pylint: disable=protected-access - ) - - if not get_workspace_response.properties.application_insights: - raise ResourceNotFoundError("Application Insights resource was not enabled for this Project.") - - # Make a GET call to the Application Insights resource URL to get the connection string - app_insights_respose: GetAppInsightsResponse = self._get_app_insights( - app_insights_resource_url=get_workspace_response.properties.application_insights - ) - - self._connection_string = app_insights_respose.properties.connection_string - - return self._connection_string - - # TODO: what about `set AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED=true`? - # TODO: This could be a class method. But we don't have a class property AIProjectClient.telemetry - def enable(self, *, destination: Union[TextIO, str, None] = None, **kwargs) -> None: - """Enables telemetry collection with OpenTelemetry for Azure AI clients and popular GenAI libraries. - - Following instrumentations are enabled (when corresponding packages are installed): - - - Azure AI Inference (`azure-ai-inference`) - - Azure AI Projects (`azure-ai-projects`) - - OpenAI (`opentelemetry-instrumentation-openai-v2`) - - Langchain (`opentelemetry-instrumentation-langchain`) - - The recording of prompt and completion messages is disabled by default. To enable it, set the - `AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED` environment variable to `true`. - - When destination is provided, the method configures OpenTelemetry SDK to export traces to - stdout or OTLP (OpenTelemetry protocol) gRPC endpoint. It's recommended for local - development only. For production use, make sure to configure OpenTelemetry SDK directly. - - :keyword destination: Recommended for local testing only. Set it to `sys.stdout` for - tracing to console output, or a string holding the OpenTelemetry protocol (OTLP) - endpoint such as "http://localhost:4317. - If not provided, the method enables instrumentations, but does not configure OpenTelemetry - SDK to export traces. - :paramtype destination: Union[TextIO, str, None] - """ - _enable_telemetry(destination=destination, **kwargs) - - -class AgentsOperations(AgentsOperationsGenerated): - - def __init__(self, *args, **kwargs) -> None: - super().__init__(*args, **kwargs) - self._function_tool = _models.FunctionTool(set()) - self._function_tool_max_retry = 10 - - # pylint: disable=arguments-differ - @overload - def create_agent( # pylint: disable=arguments-differ - self, - *, - model: str, - content_type: str = "application/json", - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.ToolResources] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any, - ) -> _models.Agent: - """Creates a new agent. - - :keyword model: The ID of the model to use. Required. - :paramtype model: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword name: The name of the new agent. Default value is None. - :paramtype name: str - :keyword description: The description of the new agent. Default value is None. - :paramtype description: str - :keyword instructions: The system instructions for the new agent to use. Default value is None. - :paramtype instructions: str - :keyword tools: The collection of tools to enable for the new agent. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword tool_resources: A set of resources that are used by the agent's tools. The resources - are specific to the type of tool. For example, the ``code_interpreter`` - tool requires a list of file IDs, while the ``file_search`` tool requires a list of vector - store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output more random, - while lower values like 0.2 will make it more focused and deterministic. Default value is - None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword response_format: The response format of the tool calls used by this agent. Is one of - the following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - # pylint: disable=arguments-differ - @overload - def create_agent( # pylint: disable=arguments-differ - self, - *, - model: str, - content_type: str = "application/json", - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - toolset: Optional[_models.ToolSet] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any, - ) -> _models.Agent: - """Creates a new agent. - - :keyword model: The ID of the model to use. Required. - :paramtype model: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword name: The name of the new agent. Default value is None. - :paramtype name: str - :keyword description: The description of the new agent. Default value is None. - :paramtype description: str - :keyword instructions: The system instructions for the new agent to use. Default value is None. - :paramtype instructions: str - :keyword toolset: The Collection of tools and resources (alternative to `tools` and `tool_resources` - and adds automatic execution logic for functions). Default value is None. - :paramtype toolset: ~azure.ai.projects.models.ToolSet - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output more random, - while lower values like 0.2 will make it more focused and deterministic. Default value is - None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword response_format: The response format of the tool calls used by this agent. Is one of - the following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_agent(self, body: JSON, *, content_type: str = "application/json", **kwargs: Any) -> _models.Agent: - """Creates a new agent. - - :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: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_agent(self, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any) -> _models.Agent: - """Creates a new agent. - - :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: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_agent( - self, - body: Union[JSON, IO[bytes]] = _Unset, - *, - model: str = _Unset, - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.ToolResources] = None, - toolset: Optional[_models.ToolSet] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - metadata: Optional[Dict[str, str]] = None, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.Agent: - """ - Creates a new agent with various configurations, delegating to the generated operations. - - :param body: JSON or IO[bytes]. Required if `model` is not provided. - :type body: Union[JSON, IO[bytes]] - :keyword model: The ID of the model to use. Required if `body` is not provided. - :paramtype model: str - :keyword name: The name of the new agent. - :paramtype name: Optional[str] - :keyword description: A description for the new agent. - :paramtype description: Optional[str] - :keyword instructions: System instructions for the agent. - :paramtype instructions: Optional[str] - :keyword tools: List of tools definitions for the agent. - :paramtype tools: Optional[List[_models.ToolDefinition]] - :keyword tool_resources: Resources used by the agent's tools. - :paramtype tool_resources: Optional[_models.ToolResources] - :keyword toolset: Collection of tools and resources (alternative to `tools` and `tool_resources` - and adds automatic execution logic for functions). - :paramtype toolset: Optional[_models.ToolSet] - :keyword temperature: Sampling temperature for generating agent responses. - :paramtype temperature: Optional[float] - :keyword top_p: Nucleus sampling parameter. - :paramtype top_p: Optional[float] - :keyword response_format: Response format for tool calls. - :paramtype response_format: Optional["_types.AgentsApiResponseFormatOption"] - :keyword metadata: Key/value pairs for storing additional information. - :paramtype metadata: Optional[Dict[str, str]] - :keyword content_type: Content type of the body. - :paramtype content_type: str - :return: An Agent object. - :rtype: _models.Agent - :raises: HttpResponseError for HTTP errors. - """ - - self._validate_tools_and_tool_resources(tools, tool_resources) - - if body is not _Unset: - if isinstance(body, io.IOBase): - return super().create_agent(body=body, content_type=content_type, **kwargs) - return super().create_agent(body=body, **kwargs) - - if toolset is not None: - tools = toolset.definitions - tool_resources = toolset.resources - - new_agent = super().create_agent( - model=model, - name=name, - description=description, - instructions=instructions, - tools=tools, - tool_resources=tool_resources, - temperature=temperature, - top_p=top_p, - response_format=response_format, - metadata=metadata, - **kwargs, - ) - - return new_agent - - # pylint: disable=arguments-differ - @overload - def update_agent( # pylint: disable=arguments-differ - self, - agent_id: str, - *, - content_type: str = "application/json", - model: Optional[str] = None, - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.ToolResources] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any, - ) -> _models.Agent: - """Modifies an existing agent. - - :param agent_id: The ID of the agent to modify. Required. - :type agent_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword model: The ID of the model to use. Default value is None. - :paramtype model: str - :keyword name: The modified name for the agent to use. Default value is None. - :paramtype name: str - :keyword description: The modified description for the agent to use. Default value is None. - :paramtype description: str - :keyword instructions: The modified system instructions for the new agent to use. Default value - is None. - :paramtype instructions: str - :keyword tools: The modified collection of tools to enable for the agent. Default value is - None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword tool_resources: A set of resources that are used by the agent's tools. The resources - are specific to the type of tool. For example, - the ``code_interpreter`` tool requires a list of file IDs, while the ``file_search`` tool - requires a list of vector store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output more random, - while lower values like 0.2 will make it more focused and deterministic. Default value is - None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword response_format: The response format of the tool calls used by this agent. Is one of - the following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - # pylint: disable=arguments-differ - @overload - def update_agent( # pylint: disable=arguments-differ - self, - agent_id: str, - *, - content_type: str = "application/json", - model: Optional[str] = None, - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - toolset: Optional[_models.ToolSet] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any, - ) -> _models.Agent: - """Modifies an existing agent. - - :param agent_id: The ID of the agent to modify. Required. - :type agent_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword model: The ID of the model to use. Default value is None. - :paramtype model: str - :keyword name: The modified name for the agent to use. Default value is None. - :paramtype name: str - :keyword description: The modified description for the agent to use. Default value is None. - :paramtype description: str - :keyword instructions: The modified system instructions for the new agent to use. Default value - is None. - :paramtype instructions: str - :keyword toolset: The Collection of tools and resources (alternative to `tools` and `tool_resources` - and adds automatic execution logic for functions). Default value is None. - :paramtype toolset: ~azure.ai.projects.models.ToolSet - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output more random, - while lower values like 0.2 will make it more focused and deterministic. Default value is - None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword response_format: The response format of the tool calls used by this agent. Is one of - the following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update_agent( - self, agent_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Agent: - """Modifies an existing agent. - - :param agent_id: The ID of the agent to modify. Required. - :type agent_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: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def update_agent( - self, agent_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.Agent: - """Modifies an existing agent. - - :param agent_id: The ID of the agent to modify. Required. - :type agent_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: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def update_agent( - self, - agent_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - model: Optional[str] = None, - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - tool_resources: Optional[_models.ToolResources] = None, - toolset: Optional[_models.ToolSet] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - content_type: str = "application/json", - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any, - ) -> _models.Agent: - """Modifies an existing agent. - - :param agent_id: The ID of the agent to modify. Required. - :type agent_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword model: The ID of the model to use. Default value is None. - :paramtype model: str - :keyword name: The modified name for the agent to use. Default value is None. - :paramtype name: str - :keyword description: The modified description for the agent to use. Default value is None. - :paramtype description: str - :keyword instructions: The modified system instructions for the new agent to use. Default value - is None. - :paramtype instructions: str - :keyword tools: The modified collection of tools to enable for the agent. Default value is - None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword tool_resources: A set of resources that are used by the agent's tools. The resources - are specific to the type of tool. For example, - the ``code_interpreter`` tool requires a list of file IDs, while the ``file_search`` tool - requires a list of vector store IDs. Default value is None. - :paramtype tool_resources: ~azure.ai.projects.models.ToolResources - :keyword toolset: The Collection of tools and resources (alternative to `tools` and `tool_resources` - and adds automatic execution logic for functions). Default value is None. - :paramtype toolset: ~azure.ai.projects.models.ToolSet - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output more random, - while lower values like 0.2 will make it more focused and deterministic. Default value is - None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model considers the results of the tokens with top_p probability mass. - So 0.1 means only the tokens comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword response_format: The response format of the tool calls used by this agent. Is one of - the following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: Agent. The Agent is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.Agent - :raises ~azure.core.exceptions.HttpResponseError: - """ - self._validate_tools_and_tool_resources(tools, tool_resources) - - if body is not _Unset: - if isinstance(body, io.IOBase): - return super().update_agent(body=body, content_type=content_type, **kwargs) - return super().update_agent(body=body, **kwargs) - - if toolset is not None: - tools = toolset.definitions - tool_resources = toolset.resources - - return super().update_agent( - agent_id=agent_id, - model=model, - name=name, - description=description, - instructions=instructions, - tools=tools, - tool_resources=tool_resources, - temperature=temperature, - top_p=top_p, - response_format=response_format, - metadata=metadata, - **kwargs, - ) - - def _validate_tools_and_tool_resources( - self, tools: Optional[List[_models.ToolDefinition]], tool_resources: Optional[_models.ToolResources] - ): - if tool_resources is None: - return - if tools is None: - tools = [] - - if tool_resources.file_search is not None and not any( - isinstance(tool, _models.FileSearchToolDefinition) for tool in tools - ): - raise ValueError( - "Tools must contain a FileSearchToolDefinition when tool_resources.file_search is provided" - ) - if tool_resources.code_interpreter is not None and not any( - isinstance(tool, _models.CodeInterpreterToolDefinition) for tool in tools - ): - raise ValueError( - "Tools must contain a CodeInterpreterToolDefinition when tool_resources.code_interpreter is provided" - ) - - # pylint: disable=arguments-differ - @overload - def create_run( # pylint: disable=arguments-differ - self, - thread_id: str, - *, - agent_id: str, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - content_type: str = "application/json", - model: Optional[str] = None, - instructions: Optional[str] = None, - additional_instructions: Optional[str] = None, - additional_messages: Optional[List[_models.ThreadMessageOptions]] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any, - ) -> _models.ThreadRun: - """Creates a new run for an agent thread. - - :param thread_id: Required. - :type thread_id: str - :keyword agent_id: The ID of the agent that should run the thread. Required. - :paramtype agent_id: str - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword model: The overridden model name that the agent should use to run the thread. Default - value is None. - :paramtype model: str - :keyword instructions: The overridden system instructions that the agent should use to run the - thread. Default value is None. - :paramtype instructions: str - :keyword additional_instructions: Additional instructions to append at the end of the - instructions for the run. This is useful for modifying the behavior - on a per-run basis without overriding other instructions. Default value is None. - :paramtype additional_instructions: str - :keyword additional_messages: Adds additional messages to the thread before creating the run. - Default value is None. - :paramtype additional_messages: list[~azure.ai.projects.models.ThreadMessageOptions] - :keyword tools: The overridden list of enabled tools that the agent should use to run the - thread. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort - to use only the number of completion tokens specified, across multiple turns of the run. If - the run exceeds the number of - completion tokens specified, the run will end with status ``incomplete``. See - ``incomplete_details`` for more info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode or - ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_run( - self, - thread_id: str, - body: JSON, - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.ThreadRun: - """Creates a new run for an agent thread. - - :param thread_id: Required. - :type thread_id: str - :param body: Required. - :type body: JSON - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_run( - self, - thread_id: str, - body: IO[bytes], - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.ThreadRun: - """Creates a new run for an agent thread. - - :param thread_id: Required. - :type thread_id: str - :param body: Required. - :type body: IO[bytes] - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_run( - self, - thread_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - agent_id: str = _Unset, - model: Optional[str] = None, - instructions: Optional[str] = None, - additional_instructions: Optional[str] = None, - additional_messages: Optional[List[_models.ThreadMessageOptions]] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - **kwargs: Any, - ) -> _models.ThreadRun: - """Creates a new run for an agent thread. - - :param thread_id: Required. - :type thread_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword agent_id: The ID of the agent that should run the thread. Required. - :paramtype agent_id: str - :keyword model: The overridden model name that the agent should use to run the thread. Default - value is None. - :paramtype model: str - :keyword instructions: The overridden system instructions that the agent should use to run the - thread. Default value is None. - :paramtype instructions: str - :keyword additional_instructions: Additional instructions to append at the end of the - instructions for the run. This is useful for modifying the behavior - on a per-run basis without overriding other instructions. Default value is None. - :paramtype additional_instructions: str - :keyword additional_messages: Adds additional messages to the thread before creating the run. - Default value is None. - :paramtype additional_messages: list[~azure.ai.projects.models.ThreadMessageOptions] - :keyword tools: The overridden list of enabled tools that the agent should use to run the - thread. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort - to use only the number of completion tokens specified, across multiple turns of the run. If - the run exceeds the number of - completion tokens specified, the run will end with status ``incomplete``. See - ``incomplete_details`` for more info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode or - ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - if isinstance(body, dict): # Handle overload with JSON body. - content_type = kwargs.get("content_type", "application/json") - response = super().create_run(thread_id, body, include=include, content_type=content_type, **kwargs) - - elif agent_id is not _Unset: # Handle overload with keyword arguments. - response = super().create_run( - thread_id, - include=include, - agent_id=agent_id, - model=model, - instructions=instructions, - additional_instructions=additional_instructions, - additional_messages=additional_messages, - tools=tools, - stream_parameter=False, - stream=False, - temperature=temperature, - top_p=top_p, - max_prompt_tokens=max_prompt_tokens, - max_completion_tokens=max_completion_tokens, - truncation_strategy=truncation_strategy, - tool_choice=tool_choice, - response_format=response_format, - parallel_tool_calls=parallel_tool_calls, - metadata=metadata, - **kwargs, - ) - - elif isinstance(body, io.IOBase): # Handle overload with binary body. - content_type = kwargs.get("content_type", "application/json") - response = super().create_run(thread_id, body, include=include, content_type=content_type, **kwargs) - - else: - raise ValueError("Invalid combination of arguments provided.") - - return response - - @distributed_trace - def create_and_process_run( - self, - thread_id: str, - *, - agent_id: str, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - model: Optional[str] = None, - instructions: Optional[str] = None, - additional_instructions: Optional[str] = None, - additional_messages: Optional[List[_models.ThreadMessageOptions]] = None, - toolset: Optional[_models.ToolSet] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - sleep_interval: int = 1, - **kwargs: Any, - ) -> _models.ThreadRun: - """Creates a new run for an agent thread and processes the run. - - :param thread_id: Required. - :type thread_id: str - :keyword agent_id: The ID of the agent that should run the thread. Required. - :paramtype agent_id: str - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword model: The overridden model name that the agent should use to run the thread. - Default value is None. - :paramtype model: str - :keyword instructions: The overridden system instructions that the agent should use to run - the thread. Default value is None. - :paramtype instructions: str - :keyword additional_instructions: Additional instructions to append at the end of the - instructions for the run. This is useful for modifying the behavior - on a per-run basis without overriding other instructions. Default value is None. - :paramtype additional_instructions: str - :keyword additional_messages: Adds additional messages to the thread before creating the run. - Default value is None. - :paramtype additional_messages: list[~azure.ai.projects.models.ThreadMessageOptions] - :keyword toolset: The Collection of tools and resources (alternative to `tools` and - `tool_resources`). Default value is None. - :paramtype toolset: ~azure.ai.projects.models.ToolSet - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort - to use only the number of completion tokens specified, across multiple turns of the run. If - the run exceeds the number of - completion tokens specified, the run will end with status ``incomplete``. See - ``incomplete_details`` for more info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or - ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode or - ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or - ~azure.ai.projects.models.AgentsApiResponseFormatMode or - ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :keyword sleep_interval: The time in seconds to wait between polling the service for run status. - Default value is 1. - :paramtype sleep_interval: int - :return: AgentRunStream. AgentRunStream is compatible with Iterable and supports streaming. - :rtype: ~azure.ai.projects.models.AgentRunStream - :raises ~azure.core.exceptions.HttpResponseError: - """ - # Create and initiate the run with additional parameters - run = self.create_run( - thread_id=thread_id, - include=include, - agent_id=agent_id, - model=model, - instructions=instructions, - additional_instructions=additional_instructions, - additional_messages=additional_messages, - tools=toolset.definitions if toolset else None, - temperature=temperature, - top_p=top_p, - max_prompt_tokens=max_prompt_tokens, - max_completion_tokens=max_completion_tokens, - truncation_strategy=truncation_strategy, - tool_choice=tool_choice, - response_format=response_format, - parallel_tool_calls=parallel_tool_calls, - metadata=metadata, - **kwargs, - ) - - # Monitor and process the run status - current_retry = 0 - while run.status in [ - RunStatus.QUEUED, - RunStatus.IN_PROGRESS, - RunStatus.REQUIRES_ACTION, - ]: - time.sleep(sleep_interval) - run = self.get_run(thread_id=thread_id, run_id=run.id) - - if run.status == RunStatus.REQUIRES_ACTION and isinstance( - run.required_action, _models.SubmitToolOutputsAction - ): - tool_calls = run.required_action.submit_tool_outputs.tool_calls - if not tool_calls: - logging.warning("No tool calls provided - cancelling run") - self.cancel_run(thread_id=thread_id, run_id=run.id) - break - # We need tool set only if we are executing local function. In case if - # the tool is azure_function we just need to wait when it will be finished. - if any(tool_call.type == "function" for tool_call in tool_calls): - toolset = _models.ToolSet() - toolset.add(self._function_tool) - tool_outputs = toolset.execute_tool_calls(tool_calls) - - if self._has_errors_in_toolcalls_output(tool_outputs): - if current_retry >= self._function_tool_max_retry: # pylint:disable=no-else-return - logging.warning( - "Tool outputs contain errors - reaching max retry %s", self._function_tool_max_retry - ) - return self.cancel_run(thread_id=thread_id, run_id=run.id) - else: - logging.warning("Tool outputs contain errors - retrying") - current_retry += 1 - - logging.info("Tool outputs: %s", tool_outputs) - if tool_outputs: - run2 = self.submit_tool_outputs_to_run( - thread_id=thread_id, run_id=run.id, tool_outputs=tool_outputs - ) - logging.info("Tool outputs submitted to run: %s", run2.id) - - logging.info("Current run status: %s", run.status) - - return run - - def _has_errors_in_toolcalls_output(self, tool_outputs: List[Dict]) -> bool: - """ - Check if any tool output contains an error. - - :param List[Dict] tool_outputs: A list of tool outputs to check. - :return: True if any output contains an error, False otherwise. - :rtype: bool - """ - for tool_output in tool_outputs: - output = tool_output.get("output") - if isinstance(output, str): - try: - output_json = json.loads(output) - if "error" in output_json: - return True - except json.JSONDecodeError: - continue - return False - - @overload - def create_stream( - self, - thread_id: str, - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - agent_id: str, - content_type: str = "application/json", - model: Optional[str] = None, - instructions: Optional[str] = None, - additional_instructions: Optional[str] = None, - additional_messages: Optional[List[_models.ThreadMessageOptions]] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - event_handler: None = None, - **kwargs: Any, - ) -> _models.AgentRunStream[_models.AgentEventHandler]: - """Creates a new stream for an agent thread. - - :param thread_id: Required. - :type thread_id: str - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword agent_id: The ID of the agent that should run the thread. Required. - :paramtype agent_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword model: The overridden model name that the agent should use to run the thread. Default - value is None. - :paramtype model: str - :keyword instructions: The overridden system instructions that the agent should use to run the - thread. Default value is None. - :paramtype instructions: str - :keyword additional_instructions: Additional instructions to append at the end of the - instructions for the run. This is useful for modifying the behavior - on a per-run basis without overriding other instructions. Default value is None. - :paramtype additional_instructions: str - :keyword additional_messages: Adds additional messages to the thread before creating the run. - Default value is None. - :paramtype additional_messages: list[~azure.ai.projects.models.ThreadMessage] - :keyword tools: The overridden list of enabled tools that the agent should use to run the - thread. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort - to use only the number of completion tokens specified, across multiple turns of the run. If - the run exceeds the number of - completion tokens specified, the run will end with status ``incomplete``. See - ``incomplete_details`` for more info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode or - ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :keyword event_handler: None - :paramtype event_handler: None. _models.AgentEventHandler will be applied as default. - :return: AgentRunStream. AgentRunStream is compatible with Iterable and supports streaming. - :rtype: ~azure.ai.projects.models.AgentRunStream - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_stream( - self, - thread_id: str, - *, - agent_id: str, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - content_type: str = "application/json", - model: Optional[str] = None, - instructions: Optional[str] = None, - additional_instructions: Optional[str] = None, - additional_messages: Optional[List[_models.ThreadMessageOptions]] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - event_handler: _models.BaseAgentEventHandlerT, - **kwargs: Any, - ) -> _models.AgentRunStream[_models.BaseAgentEventHandlerT]: - """Creates a new stream for an agent thread. - - :param thread_id: Required. - :type thread_id: str - :keyword agent_id: The ID of the agent that should run the thread. Required. - :paramtype agent_id: str - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword model: The overridden model name that the agent should use to run the thread. Default - value is None. - :paramtype model: str - :keyword instructions: The overridden system instructions that the agent should use to run the - thread. Default value is None. - :paramtype instructions: str - :keyword additional_instructions: Additional instructions to append at the end of the - instructions for the run. This is useful for modifying the behavior - on a per-run basis without overriding other instructions. Default value is None. - :paramtype additional_instructions: str - :keyword additional_messages: Adds additional messages to the thread before creating the run. - Default value is None. - :paramtype additional_messages: list[~azure.ai.projects.models.ThreadMessage] - :keyword tools: The overridden list of enabled tools that the agent should use to run the - thread. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort - to use only the number of completion tokens specified, across multiple turns of the run. If - the run exceeds the number of - completion tokens specified, the run will end with status ``incomplete``. See - ``incomplete_details`` for more info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode or - ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :keyword event_handler: The event handler to use for processing events during the run. Default - value is None. - :paramtype event_handler: ~azure.ai.projects.models.AgentEventHandler - :return: AgentRunStream. AgentRunStream is compatible with Iterable and supports streaming. - :rtype: ~azure.ai.projects.models.AgentRunStream - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_stream( - self, - thread_id: str, - body: Union[JSON, IO[bytes]], - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - event_handler: None = None, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.AgentRunStream[_models.AgentEventHandler]: - """Creates a new run for an agent thread. - - Terminating when the Run enters a terminal state with a ``data: [DONE]`` message. - - :param thread_id: Required. - :type thread_id: str - :param body: Required. - :type body: IO[bytes] - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword event_handler: None - :paramtype event_handler: None. _models.AgentEventHandler will be applied as default. - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: AgentRunStream. AgentRunStream is compatible with Iterable and supports streaming. - :rtype: ~azure.ai.projects.models.AgentRunStream - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_stream( - self, - thread_id: str, - body: Union[JSON, IO[bytes]], - *, - event_handler: _models.BaseAgentEventHandlerT, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - content_type: str = "application/json", - **kwargs: Any, - ) -> _models.AgentRunStream[_models.BaseAgentEventHandlerT]: - """Creates a new run for an agent thread. - - Terminating when the Run enters a terminal state with a ``data: [DONE]`` message. - - :param thread_id: Required. - :type thread_id: str - :param body: Required. - :type body: IO[bytes] - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword event_handler: The event handler to use for processing events during the run. Default - value is None. - :paramtype event_handler: ~azure.ai.projects.models.AgentEventHandler - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :return: AgentRunStream. AgentRunStream is compatible with Iterable and supports streaming. - :rtype: ~azure.ai.projects.models.AgentRunStream - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_stream( # pyright: ignore[reportInconsistentOverload] - self, - thread_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - include: Optional[List[Union[str, _models.RunAdditionalFieldList]]] = None, - agent_id: str = _Unset, - model: Optional[str] = None, - instructions: Optional[str] = None, - additional_instructions: Optional[str] = None, - additional_messages: Optional[List[_models.ThreadMessageOptions]] = None, - tools: Optional[List[_models.ToolDefinition]] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - truncation_strategy: Optional[_models.TruncationObject] = None, - tool_choice: Optional["_types.AgentsApiToolChoiceOption"] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - parallel_tool_calls: Optional[bool] = None, - metadata: Optional[Dict[str, str]] = None, - event_handler: Optional[_models.BaseAgentEventHandlerT] = None, - **kwargs: Any, - ) -> _models.AgentRunStream[_models.BaseAgentEventHandlerT]: - """Creates a new run for an agent thread. - - Terminating when the Run enters a terminal state with a ``data: [DONE]`` message. - - :param thread_id: Required. - :type thread_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword include: A list of additional fields to include in the response. - Currently the only supported value is - ``step_details.tool_calls[*].file_search.results[*].content`` to fetch the file search result - content. Default value is None. - :paramtype include: list[str or ~azure.ai.projects.models.RunAdditionalFieldList] - :keyword agent_id: The ID of the agent that should run the thread. Required. - :paramtype agent_id: str - :keyword model: The overridden model name that the agent should use to run the thread. Default - value is None. - :paramtype model: str - :keyword instructions: The overridden system instructions that the agent should use to run the - thread. Default value is None. - :paramtype instructions: str - :keyword additional_instructions: Additional instructions to append at the end of the - instructions for the run. This is useful for modifying the behavior - on a per-run basis without overriding other instructions. Default value is None. - :paramtype additional_instructions: str - :keyword additional_messages: Adds additional messages to the thread before creating the run. - Default value is None. - :paramtype additional_messages: list[~azure.ai.projects.models.ThreadMessage] - :keyword tools: The overridden list of enabled tools that the agent should use to run the - thread. Default value is None. - :paramtype tools: list[~azure.ai.projects.models.ToolDefinition] - :keyword temperature: What sampling temperature to use, between 0 and 2. Higher values like 0.8 - will make the output - more random, while lower values like 0.2 will make it more focused and deterministic. Default - value is None. - :paramtype temperature: float - :keyword top_p: An alternative to sampling with temperature, called nucleus sampling, where the - model - considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens - comprising the top 10% probability mass are considered. - - We generally recommend altering this or temperature but not both. Default value is None. - :paramtype top_p: float - :keyword max_prompt_tokens: The maximum number of prompt tokens that may be used over the - course of the run. The run will make a best effort to use only - the number of prompt tokens specified, across multiple turns of the run. If the run exceeds - the number of prompt tokens specified, - the run will end with status ``incomplete``. See ``incomplete_details`` for more info. Default - value is None. - :paramtype max_prompt_tokens: int - :keyword max_completion_tokens: The maximum number of completion tokens that may be used over - the course of the run. The run will make a best effort - to use only the number of completion tokens specified, across multiple turns of the run. If - the run exceeds the number of - completion tokens specified, the run will end with status ``incomplete``. See - ``incomplete_details`` for more info. Default value is None. - :paramtype max_completion_tokens: int - :keyword truncation_strategy: The strategy to use for dropping messages as the context windows - moves forward. Default value is None. - :paramtype truncation_strategy: ~azure.ai.projects.models.TruncationObject - :keyword tool_choice: Controls whether or not and which tool is called by the model. Is one of - the following types: str, Union[str, "_models.AgentsApiToolChoiceOptionMode"], - AgentsNamedToolChoice Default value is None. - :paramtype tool_choice: str or str or ~azure.ai.projects.models.AgentsApiToolChoiceOptionMode or - ~azure.ai.projects.models.AgentsNamedToolChoice - :keyword response_format: Specifies the format that the model must output. Is one of the - following types: str, Union[str, "_models.AgentsApiResponseFormatMode"], - AgentsApiResponseFormat Default value is None. - :paramtype response_format: str or str or ~azure.ai.projects.models.AgentsApiResponseFormatMode - or ~azure.ai.projects.models.AgentsApiResponseFormat - :keyword parallel_tool_calls: If ``true`` functions will run in parallel during tool use. - Default value is None. - :paramtype parallel_tool_calls: bool - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :keyword event_handler: The event handler to use for processing events during the run. Default - value is None. - :paramtype event_handler: ~azure.ai.projects.models.AgentEventHandler - :return: AgentRunStream. AgentRunStream is compatible with Iterable and supports streaming. - :rtype: ~azure.ai.projects.models.AgentRunStream - :raises ~azure.core.exceptions.HttpResponseError: - """ - - if isinstance(body, dict): # Handle overload with JSON body. - content_type = kwargs.get("content_type", "application/json") - response = super().create_run(thread_id, body, include=include, content_type=content_type, **kwargs) - - elif agent_id is not _Unset: # Handle overload with keyword arguments. - response = super().create_run( - thread_id, - include=include, - agent_id=agent_id, - model=model, - instructions=instructions, - additional_instructions=additional_instructions, - additional_messages=additional_messages, - tools=tools, - stream_parameter=True, - stream=True, - temperature=temperature, - top_p=top_p, - max_prompt_tokens=max_prompt_tokens, - max_completion_tokens=max_completion_tokens, - truncation_strategy=truncation_strategy, - tool_choice=tool_choice, - response_format=response_format, - parallel_tool_calls=parallel_tool_calls, - metadata=metadata, - **kwargs, - ) - - elif isinstance(body, io.IOBase): # Handle overload with binary body. - content_type = kwargs.get("content_type", "application/json") - response = super().create_run(thread_id, body, include=include, content_type=content_type, **kwargs) - - else: - raise ValueError("Invalid combination of arguments provided.") - - response_iterator: Iterator[bytes] = cast(Iterator[bytes], response) - - if not event_handler: - event_handler = cast(_models.BaseAgentEventHandlerT, _models.AgentEventHandler()) - if isinstance(event_handler, _models.AgentEventHandler): - event_handler.set_max_retry(self._function_tool_max_retry) - return _models.AgentRunStream(response_iterator, self._handle_submit_tool_outputs, event_handler) - - # pylint: disable=arguments-differ - @overload - def submit_tool_outputs_to_run( # pylint: disable=arguments-differ - self, - thread_id: str, - run_id: str, - *, - tool_outputs: List[_models.ToolOutput], - content_type: str = "application/json", - event_handler: Optional[_models.AgentEventHandler] = None, - **kwargs: Any, - ) -> _models.ThreadRun: - """Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. - - :param thread_id: Required. - :type thread_id: str - :param run_id: Required. - :type run_id: str - :keyword tool_outputs: Required. - :paramtype tool_outputs: list[~azure.ai.projects.models.ToolOutput] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword event_handler: The event handler to use for processing events during the run. Default - value is None. - :paramtype event_handler: ~azure.ai.projects.models.AgentEventHandler - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def submit_tool_outputs_to_run( - self, thread_id: str, run_id: str, body: JSON, *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadRun: - """Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. - - :param thread_id: Required. - :type thread_id: str - :param run_id: Required. - :type run_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: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def submit_tool_outputs_to_run( - self, thread_id: str, run_id: str, body: IO[bytes], *, content_type: str = "application/json", **kwargs: Any - ) -> _models.ThreadRun: - """Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. - - :param thread_id: Required. - :type thread_id: str - :param run_id: Required. - :type run_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: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def submit_tool_outputs_to_run( - self, - thread_id: str, - run_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - tool_outputs: List[_models.ToolOutput] = _Unset, - **kwargs: Any, - ) -> _models.ThreadRun: - """Submits outputs from tools as requested by tool calls in a run. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. - - :param thread_id: Required. - :type thread_id: str - :param run_id: Required. - :type run_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword tool_outputs: Required. - :paramtype tool_outputs: list[~azure.ai.projects.models.ToolOutput] - :return: ThreadRun. The ThreadRun is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.ThreadRun - :raises ~azure.core.exceptions.HttpResponseError: - """ - - if isinstance(body, dict): - content_type = kwargs.get("content_type", "application/json") - response = super().submit_tool_outputs_to_run(thread_id, run_id, body, content_type=content_type, **kwargs) - - elif tool_outputs is not _Unset: - response = super().submit_tool_outputs_to_run( - thread_id, - run_id, - tool_outputs=tool_outputs, - stream_parameter=False, - stream=False, - **kwargs, - ) - - elif isinstance(body, io.IOBase): - content_type = kwargs.get("content_type", "application/json") - response = super().submit_tool_outputs_to_run(thread_id, run_id, body, content_type=content_type, **kwargs) - - else: - raise ValueError("Invalid combination of arguments provided.") - - return response - - @overload - def submit_tool_outputs_to_stream( - self, - thread_id: str, - run_id: str, - body: Union[JSON, IO[bytes]], - *, - event_handler: _models.BaseAgentEventHandler, - content_type: str = "application/json", - **kwargs: Any, - ) -> None: - """Submits outputs from tools as requested by tool calls in a stream. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. terminating when the Run enters a terminal state with a ``data: [DONE]`` message. - - :param thread_id: Required. - :type thread_id: str - :param run_id: Required. - :type run_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword event_handler: The event handler to use for processing events during the run. - :paramtype event_handler: ~azure.ai.projects.models.BaseAgentEventHandler - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def submit_tool_outputs_to_stream( - self, - thread_id: str, - run_id: str, - *, - tool_outputs: List[_models.ToolOutput], - content_type: str = "application/json", - event_handler: _models.BaseAgentEventHandler, - **kwargs: Any, - ) -> None: - """Submits outputs from tools as requested by tool calls in a stream. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. terminating when the Run enters a terminal state with a ``data: [DONE]`` message. - - :param thread_id: Required. - :type thread_id: str - :param run_id: Required. - :type run_id: str - :keyword tool_outputs: Required. - :paramtype tool_outputs: list[~azure.ai.projects.models.ToolOutput] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword event_handler: The event handler to use for processing events during the run. - :paramtype event_handler: ~azure.ai.projects.models.BaseAgentEventHandler - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def submit_tool_outputs_to_stream( # pyright: ignore[reportInconsistentOverload] - self, - thread_id: str, - run_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - tool_outputs: List[_models.ToolOutput] = _Unset, - event_handler: _models.BaseAgentEventHandler, - **kwargs: Any, - ) -> None: - """Submits outputs from tools as requested by tool calls in a stream. Runs that need submitted tool - outputs will have a status of 'requires_action' with a required_action.type of - 'submit_tool_outputs'. terminating when the Run enters a terminal state with a ``data: [DONE]`` message. - - :param thread_id: Required. - :type thread_id: str - :param run_id: Required. - :type run_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword tool_outputs: Required. - :paramtype tool_outputs: list[~azure.ai.projects.models.ToolOutput] - :keyword event_handler: The event handler to use for processing events during the run. - :paramtype event_handler: ~azure.ai.projects.models.BaseAgentEventHandler - :raises ~azure.core.exceptions.HttpResponseError: - """ - - if isinstance(body, dict): - content_type = kwargs.get("content_type", "application/json") - response = super().submit_tool_outputs_to_run(thread_id, run_id, body, content_type=content_type, **kwargs) - - elif tool_outputs is not _Unset: - response = super().submit_tool_outputs_to_run( - thread_id, run_id, tool_outputs=tool_outputs, stream_parameter=True, stream=True, **kwargs - ) - - elif isinstance(body, io.IOBase): - content_type = kwargs.get("content_type", "application/json") - response = super().submit_tool_outputs_to_run(thread_id, run_id, body, content_type=content_type, **kwargs) - - else: - raise ValueError("Invalid combination of arguments provided.") - - # Cast the response to Iterator[bytes] for type correctness - response_iterator: Iterator[bytes] = cast(Iterator[bytes], response) - - event_handler.initialize(response_iterator, self._handle_submit_tool_outputs) - - def _handle_submit_tool_outputs( - self, run: _models.ThreadRun, event_handler: _models.BaseAgentEventHandler, submit_with_error: bool - ) -> Any: - tool_outputs: Any = [] - if isinstance(run.required_action, _models.SubmitToolOutputsAction): - tool_calls = run.required_action.submit_tool_outputs.tool_calls - if not tool_calls: - logger.debug("No tool calls to execute.") - return tool_outputs - - # We need tool set only if we are executing local function. In case if - # the tool is azure_function we just need to wait when it will be finished. - if ( - any(tool_call.type == "function" for tool_call in tool_calls) - and len(self._function_tool.definitions) > 0 - ): - - toolset = _models.ToolSet() - toolset.add(self._function_tool) - tool_outputs = toolset.execute_tool_calls(tool_calls) - - if self._has_errors_in_toolcalls_output(tool_outputs): - if submit_with_error: - logging.warning("Tool outputs contain errors - retrying") - else: - logging.warning("Tool outputs contain errors - reaching max retry limit") - self.cancel_run(thread_id=run.thread_id, run_id=run.id) - return tool_outputs - - logger.info("Tool outputs: %s", tool_outputs) - if tool_outputs: - self.submit_tool_outputs_to_stream( - thread_id=run.thread_id, - run_id=run.id, - tool_outputs=tool_outputs, - event_handler=event_handler, - ) - return tool_outputs - - # pylint: disable=arguments-differ - @overload - def upload_file( # pylint: disable=arguments-differ - self, *, file_path: str, purpose: Union[str, _models.FilePurpose], **kwargs: Any - ) -> _models.OpenAIFile: - """Uploads a file for use by other operations. - - :keyword file_path: Required. - :type file_path: str - :keyword purpose: Known values are: "fine-tune", "fine-tune-results", "assistants", - "assistants_output", "batch", "batch_output", and "vision". Required. - :paramtype purpose: str or ~azure.ai.projects.models.FilePurpose - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - # pylint: disable=arguments-differ - @overload - def upload_file( # pylint: disable=arguments-differ - self, *, file: FileType, purpose: Union[str, _models.FilePurpose], filename: Optional[str] = None, **kwargs: Any - ) -> _models.OpenAIFile: - """Uploads a file for use by other operations. - - :keyword file: Required. - :paramtype file: ~azure.ai.projects._vendor.FileType - :keyword purpose: Known values are: "fine-tune", "fine-tune-results", "assistants", - "assistants_output", "batch", "batch_output", and "vision". Required. - :paramtype purpose: str or ~azure.ai.projects.models.FilePurpose - :keyword filename: Default value is None. - :paramtype filename: str - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def upload_file(self, body: JSON, **kwargs: Any) -> _models.OpenAIFile: - """Uploads a file for use by other operations. - - :param body: Required. - :type body: JSON - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def upload_file( - self, - body: Optional[JSON] = None, - *, - file: Optional[FileType] = None, - file_path: Optional[str] = None, - purpose: Union[str, _models.FilePurpose, None] = None, - filename: Optional[str] = None, - **kwargs: Any, - ) -> _models.OpenAIFile: - """ - Uploads a file for use by other operations, delegating to the generated operations. - - :param body: JSON. Required if `file` and `purpose` are not provided. - :type body: Optional[JSON] - :keyword file: File content. Required if `body` and `purpose` are not provided. - :paramtype file: Optional[FileType] - :keyword file_path: Path to the file. Required if `body` and `purpose` are not provided. - :paramtype file_path: Optional[str] - :keyword purpose: Known values are: "fine-tune", "fine-tune-results", "assistants", - "assistants_output", "batch", "batch_output", and "vision". Required if `body` and `file` are not provided. - :paramtype purpose: Union[str, _models.FilePurpose, None] - :keyword filename: The name of the file. - :paramtype filename: Optional[str] - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: _models.OpenAIFile - :raises FileNotFoundError: If the file_path is invalid. - :raises IOError: If there are issues with reading the file. - :raises: HttpResponseError for HTTP errors. - """ - # If a JSON body is provided directly, pass it along - if body is not None: - return super()._upload_file(body=body, **kwargs) - - # Convert FilePurpose enum to string if necessary - if isinstance(purpose, FilePurpose): - purpose = purpose.value - - # If file content is passed in directly - if file is not None and purpose is not None: - return super()._upload_file(body={"file": file, "purpose": purpose, "filename": filename}, **kwargs) - - # If a file path is provided - if file_path is not None and purpose is not None: - if not os.path.isfile(file_path): - raise FileNotFoundError(f"The file path provided does not exist: {file_path}") - - try: - with open(file_path, "rb") as f: - content = f.read() - - # If no explicit filename is provided, use the base name - base_filename = filename or os.path.basename(file_path) - file_content: FileType = (base_filename, content) - - return super()._upload_file(body={"file": file_content, "purpose": purpose}, **kwargs) - except IOError as e: - raise IOError(f"Unable to read file: {file_path}") from e - - raise ValueError("Invalid parameters for upload_file. Please provide the necessary arguments.") - - @overload - def upload_file_and_poll(self, body: JSON, *, sleep_interval: float = 1, **kwargs: Any) -> _models.OpenAIFile: - """Uploads a file for use by other operations. - - :param body: Required. - :type body: JSON - :keyword sleep_interval: Time to wait before polling for the status of the uploaded file. Default value - is 1. - :paramtype sleep_interval: float - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def upload_file_and_poll( - self, - *, - file: FileType, - purpose: Union[str, _models.FilePurpose], - filename: Optional[str] = None, - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.OpenAIFile: - """Uploads a file for use by other operations. - - :keyword file: Required. - :paramtype file: ~azure.ai.projects._vendor.FileType - :keyword purpose: Known values are: "fine-tune", "fine-tune-results", "assistants", - "assistants_output", "batch", "batch_output", and "vision". Required. - :paramtype purpose: str or ~azure.ai.projects.models.FilePurpose - :keyword filename: Default value is None. - :paramtype filename: str - :keyword sleep_interval: Time to wait before polling for the status of the uploaded file. Default value - is 1. - :paramtype sleep_interval: float - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def upload_file_and_poll( - self, *, file_path: str, purpose: Union[str, _models.FilePurpose], sleep_interval: float = 1, **kwargs: Any - ) -> _models.OpenAIFile: - """Uploads a file for use by other operations. - - :keyword file_path: Required. - :type file_path: str - :keyword purpose: Known values are: "fine-tune", "fine-tune-results", "assistants", - "assistants_output", "batch", "batch_output", and "vision". Required. - :paramtype purpose: str or ~azure.ai.projects.models.FilePurpose - :keyword sleep_interval: Time to wait before polling for the status of the uploaded file. Default value - is 1. - :paramtype sleep_interval: float - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.OpenAIFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def upload_file_and_poll( - self, - body: Optional[JSON] = None, - *, - file: Optional[FileType] = None, - file_path: Optional[str] = None, - purpose: Union[str, _models.FilePurpose, None] = None, - filename: Optional[str] = None, - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.OpenAIFile: - """ - Uploads a file for use by other operations, delegating to the generated operations. - - :param body: JSON. Required if `file` and `purpose` are not provided. - :type body: Optional[JSON] - :keyword file: File content. Required if `body` and `purpose` are not provided. - :paramtype file: Optional[FileType] - :keyword file_path: Path to the file. Required if `body` and `purpose` are not provided. - :paramtype file_path: Optional[str] - :keyword purpose: Known values are: "fine-tune", "fine-tune-results", "assistants", - "assistants_output", "batch", "batch_output", and "vision". Required if `body` and `file` are not provided. - :paramtype purpose: Union[str, _models.FilePurpose, None] - :keyword filename: The name of the file. - :paramtype filename: Optional[str] - :keyword sleep_interval: Time to wait before polling for the status of the uploaded file. Default value - is 1. - :paramtype sleep_interval: float - :return: OpenAIFile. The OpenAIFile is compatible with MutableMapping - :rtype: _models.OpenAIFile - :raises FileNotFoundError: If the file_path is invalid. - :raises IOError: If there are issues with reading the file. - :raises: HttpResponseError for HTTP errors. - """ - if body is not None: - uploaded_file = self.upload_file(body=body, **kwargs) - elif file is not None and purpose is not None: - uploaded_file = self.upload_file(file=file, purpose=purpose, filename=filename, **kwargs) - elif file_path is not None and purpose is not None: - uploaded_file = self.upload_file(file_path=file_path, purpose=purpose, **kwargs) - else: - raise ValueError( - "Invalid parameters for upload_file_and_poll. Please provide either 'body', " - "or both 'file' and 'purpose', or both 'file_path' and 'purpose'." - ) - - while uploaded_file.status in ["uploaded", "pending", "running"]: - time.sleep(sleep_interval) - uploaded_file = self.get_file(uploaded_file.id) - - return uploaded_file - - @overload - def create_vector_store_and_poll( - self, body: JSON, *, content_type: str = "application/json", sleep_interval: float = 1, **kwargs: Any - ) -> _models.VectorStore: - """Creates a vector store and poll. - - :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 - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_vector_store_and_poll( - self, - *, - content_type: str = "application/json", - file_ids: Optional[List[str]] = None, - name: Optional[str] = None, - data_sources: Optional[List[_models.VectorStoreDataSource]] = None, - expires_after: Optional[_models.VectorStoreExpirationPolicy] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - metadata: Optional[Dict[str, str]] = None, - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStore: - """Creates a vector store and poll. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword file_ids: A list of file IDs that the vector store should use. Useful for tools like - ``file_search`` that can access files. Default value is None. - :paramtype file_ids: list[str] - :keyword name: The name of the vector store. Default value is None. - :paramtype name: str - :keyword data_sources: List of Azure assets. Default value is None. - :paramtype data_sources: list[~azure.ai.projects.models.VectorStoreDataSource] - :keyword expires_after: Details on when this vector store expires. Default value is None. - :paramtype expires_after: ~azure.ai.projects.models.VectorStoreExpirationPolicy - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Only applicable if file_ids is non-empty. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_vector_store_and_poll( - self, body: IO[bytes], *, content_type: str = "application/json", sleep_interval: float = 1, **kwargs: Any - ) -> _models.VectorStore: - """Creates a vector store and poll. - - :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 - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_vector_store_and_poll( - self, - body: Union[JSON, IO[bytes]] = _Unset, - *, - content_type: str = "application/json", - file_ids: Optional[List[str]] = None, - name: Optional[str] = None, - data_sources: Optional[List[_models.VectorStoreDataSource]] = None, - expires_after: Optional[_models.VectorStoreExpirationPolicy] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - metadata: Optional[Dict[str, str]] = None, - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStore: - """Creates a vector store and poll. - - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". - :paramtype content_type: str - :keyword file_ids: A list of file IDs that the vector store should use. Useful for tools like - ``file_search`` that can access files. Default value is None. - :paramtype file_ids: list[str] - :keyword name: The name of the vector store. Default value is None. - :paramtype name: str - :keyword data_sources: List of Azure assets. Default value is None. - :paramtype data_sources: list[~azure.ai.projects.models.VectorStoreDataSource] - :keyword expires_after: Details on when this vector store expires. Default value is None. - :paramtype expires_after: ~azure.ai.projects.models.VectorStoreExpirationPolicy - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Only applicable if file_ids is non-empty. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :keyword metadata: A set of up to 16 key/value pairs that can be attached to an object, used - for storing additional information about that object in a structured format. Keys may be up to - 64 characters in length and values may be up to 512 characters in length. Default value is - None. - :paramtype metadata: dict[str, str] - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStore. The VectorStore is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStore - :raises ~azure.core.exceptions.HttpResponseError: - """ - - if body is not _Unset: - if isinstance(body, dict): - vector_store = super().create_vector_store( - body=body, content_type=content_type or "application/json", **kwargs - ) - elif isinstance(body, io.IOBase): - vector_store = super().create_vector_store(body=body, content_type=content_type, **kwargs) - else: - raise ValueError("Invalid 'body' type: must be a dictionary (JSON) or a file-like object (IO[bytes]).") - else: - store_configuration = None - if data_sources: - store_configuration = _models.VectorStoreConfiguration(data_sources=data_sources) - - vector_store = super().create_vector_store( - file_ids=file_ids, - store_configuration=store_configuration, - name=name, - expires_after=expires_after, - chunking_strategy=chunking_strategy, - metadata=metadata, - **kwargs, - ) - - while vector_store.status == "in_progress": - time.sleep(sleep_interval) - vector_store = super().get_vector_store(vector_store.id) - - return vector_store - - @overload - def create_vector_store_file_batch_and_poll( - self, - vector_store_id: str, - body: JSON, - *, - content_type: str = "application/json", - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStoreFileBatch: - """Create a vector store file batch and poll. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_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 - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_vector_store_file_batch_and_poll( - self, - vector_store_id: str, - *, - file_ids: Optional[List[str]] = None, - data_sources: Optional[List[_models.VectorStoreDataSource]] = None, - content_type: str = "application/json", - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStoreFileBatch: - """Create a vector store file batch and poll. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :keyword file_ids: List of file identifiers. Required. - :paramtype file_ids: list[str] - :keyword data_sources: List of Azure assets. Default value is None. - :paramtype data_sources: list[~azure.ai.projects.models.VectorStoreDataSource] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_vector_store_file_batch_and_poll( - self, - vector_store_id: str, - body: IO[bytes], - *, - content_type: str = "application/json", - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStoreFileBatch: - """Create a vector store file batch and poll. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_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 - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_vector_store_file_batch_and_poll( - self, - vector_store_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - file_ids: Optional[List[str]] = None, - data_sources: Optional[List[_models.VectorStoreDataSource]] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - content_type: str = "application/json", - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStoreFileBatch: - """Create a vector store file batch and poll. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword file_ids: List of file identifiers. Required. - :paramtype file_ids: list[str] - :keyword data_sources: List of Azure assets. Default value is None. - :paramtype data_sources: list[~azure.ai.client.models.VectorStoreDataSource] - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :keyword content_type: Body parameter content-type. Defaults to "application/json". - :paramtype content_type: str - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStoreFileBatch. The VectorStoreFileBatch is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFileBatch - :raises ~azure.core.exceptions.HttpResponseError: - """ - - if body is not _Unset: - if isinstance(body, dict): - vector_store_file_batch = super().create_vector_store_file_batch( - vector_store_id=vector_store_id, - body=body, - content_type=content_type or "application/json", - **kwargs, - ) - elif isinstance(body, io.IOBase): - vector_store_file_batch = super().create_vector_store_file_batch( - vector_store_id=vector_store_id, - body=body, - content_type=content_type, - **kwargs, - ) - else: - raise ValueError("Invalid type for 'body'. Must be a dict (JSON) or file-like (IO[bytes]).") - else: - vector_store_file_batch = super().create_vector_store_file_batch( - vector_store_id=vector_store_id, - file_ids=file_ids, - data_sources=data_sources, - chunking_strategy=chunking_strategy, - **kwargs, - ) - - while vector_store_file_batch.status == "in_progress": - time.sleep(sleep_interval) - vector_store_file_batch = super().get_vector_store_file_batch( - vector_store_id=vector_store_id, batch_id=vector_store_file_batch.id - ) - - return vector_store_file_batch - - @distributed_trace - def get_file_content(self, file_id: str, **kwargs: Any) -> Iterator[bytes]: - """ - Returns file content as byte stream for given file_id. - - :param file_id: The ID of the file to retrieve. Required. - :type file_id: str - :return: An iterator that yields bytes from the file content. - :rtype: Iterator[bytes] - :raises ~azure.core.exceptions.HttpResponseError: If the HTTP request fails. - """ - kwargs["stream"] = True - response = super()._get_file_content(file_id, **kwargs) - return cast(Iterator[bytes], response) - - @distributed_trace - def save_file(self, file_id: str, file_name: str, target_dir: Optional[Union[str, Path]] = None) -> None: - """ - Synchronously saves file content retrieved using a file identifier to the specified local directory. - - :param file_id: The unique identifier for the file to retrieve. - :type file_id: str - :param file_name: The name of the file to be saved. - :type file_name: str - :param target_dir: The directory where the file should be saved. Defaults to the current working directory. - :type target_dir: Optional[Union[str, Path]] - :raises ValueError: If the target path is not a directory or the file name is invalid. - :raises RuntimeError: If file content retrieval fails or no content is found. - :raises TypeError: If retrieved chunks are not bytes-like objects. - :raises IOError: If writing to the file fails. - """ - try: - # Determine and validate the target directory - path = Path(target_dir).expanduser().resolve() if target_dir else Path.cwd() - path.mkdir(parents=True, exist_ok=True) - if not path.is_dir(): - raise ValueError(f"The target path '{path}' is not a directory.") - - # Sanitize and validate the file name - sanitized_file_name = Path(file_name).name - if not sanitized_file_name: - raise ValueError("The provided file name is invalid.") - - # Retrieve the file content - file_content_stream = self.get_file_content(file_id) - if not file_content_stream: - raise RuntimeError(f"No content retrievable for file ID '{file_id}'.") - - target_file_path = path / sanitized_file_name - - # Write the file content to disk - with target_file_path.open("wb") as file: - for chunk in file_content_stream: - if isinstance(chunk, (bytes, bytearray)): - file.write(chunk) - else: - raise TypeError(f"Expected bytes or bytearray, got {type(chunk).__name__}") - - logger.debug("File '%s' saved successfully at '%s'.", sanitized_file_name, target_file_path) - - except (ValueError, RuntimeError, TypeError, IOError) as e: - logger.error("An error occurred in save_file: %s", e) - raise - - @overload - def create_vector_store_file_and_poll( - self, - vector_store_id: str, - body: JSON, - *, - content_type: str = "application/json", - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStoreFile: - """Create a vector store file by attaching a file to a vector store. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_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 - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStoreFile. The VectorStoreFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_vector_store_file_and_poll( - self, - vector_store_id: str, - *, - content_type: str = "application/json", - file_id: Optional[str] = None, - data_source: Optional[_models.VectorStoreDataSource] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStoreFile: - """Create a vector store file by attaching a file to a vector store. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". - :paramtype content_type: str - :keyword file_id: Identifier of the file. Default value is None. - :paramtype file_id: str - :keyword data_source: Azure asset ID. Default value is None. - :paramtype data_source: ~azure.ai.projects.models.VectorStoreDataSource - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStoreFile. The VectorStoreFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def create_vector_store_file_and_poll( - self, - vector_store_id: str, - body: IO[bytes], - *, - content_type: str = "application/json", - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStoreFile: - """Create a vector store file by attaching a file to a vector store. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_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 - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStoreFile. The VectorStoreFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @distributed_trace - def create_vector_store_file_and_poll( - self, - vector_store_id: str, - body: Union[JSON, IO[bytes]] = _Unset, - *, - content_type: str = "application/json", - file_id: Optional[str] = None, - data_source: Optional[_models.VectorStoreDataSource] = None, - chunking_strategy: Optional[_models.VectorStoreChunkingStrategyRequest] = None, - sleep_interval: float = 1, - **kwargs: Any, - ) -> _models.VectorStoreFile: - """Create a vector store file by attaching a file to a vector store. - - :param vector_store_id: Identifier of the vector store. Required. - :type vector_store_id: str - :param body: Is either a JSON type or a IO[bytes] type. Required. - :type body: JSON or IO[bytes] - :keyword content_type: Body Parameter content-type. Defaults to 'application/json'. - :paramtype content_type: str - :keyword file_id: Identifier of the file. Default value is None. - :paramtype file_id: str - :keyword data_source: Azure asset ID. Default value is None. - :paramtype data_source: ~azure.ai.projects.models.VectorStoreDataSource - :keyword chunking_strategy: The chunking strategy used to chunk the file(s). If not set, will - use the auto strategy. Default value is None. - :paramtype chunking_strategy: ~azure.ai.projects.models.VectorStoreChunkingStrategyRequest - :keyword sleep_interval: Time to wait before polling for the status of the vector store. Default value - is 1. - :paramtype sleep_interval: float - :return: VectorStoreFile. The VectorStoreFile is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.VectorStoreFile - :raises ~azure.core.exceptions.HttpResponseError: - """ - - if body is not _Unset: - if isinstance(body, dict): - vector_store_file = super().create_vector_store_file( - vector_store_id=vector_store_id, - body=body, - content_type=content_type or "application/json", - **kwargs, - ) - elif isinstance(body, io.IOBase): - vector_store_file = super().create_vector_store_file( - vector_store_id=vector_store_id, - body=body, - content_type=content_type, - **kwargs, - ) - else: - raise ValueError("Invalid type for 'body'. Must be a dict (JSON) or file-like object (IO[bytes]).") - else: - vector_store_file = super().create_vector_store_file( - vector_store_id=vector_store_id, - file_id=file_id, - data_source=data_source, - chunking_strategy=chunking_strategy, - **kwargs, - ) - - while vector_store_file.status == "in_progress": - time.sleep(sleep_interval) - vector_store_file = super().get_vector_store_file( - vector_store_id=vector_store_id, file_id=vector_store_file.id - ) - - return vector_store_file - - @distributed_trace - def delete_agent(self, agent_id: str, **kwargs: Any) -> _models.AgentDeletionStatus: - """Deletes an agent. - - :param agent_id: Identifier of the agent. Required. - :type agent_id: str - :return: AgentDeletionStatus. The AgentDeletionStatus is compatible with MutableMapping - :rtype: ~azure.ai.projects.models.AgentDeletionStatus - :raises ~azure.core.exceptions.HttpResponseError: - """ - return super().delete_agent(agent_id, **kwargs) - - @overload - def enable_auto_function_calls(self, *, functions: Set[Callable[..., Any]], max_retry: int = 10) -> None: - """Enables tool calls to be executed automatically during create_and_process_run or streaming. - If this is not set, functions must be called manually. - If automatic function calls fail, the agents will receive error messages allowing it to retry with another - function call or figure out the answer with its knowledge. - :keyword functions: A set of callable functions to be used as tools. - :type functions: Set[Callable[..., Any]] - :keyword max_retry: Maximum number of errors allowed and retry per run or stream. Default value is 10. - :type max_retry: int - """ - - @overload - def enable_auto_function_calls(self, *, function_tool: _models.FunctionTool, max_retry: int = 10) -> None: - """Enables tool calls to be executed automatically during create_and_process_run or streaming. - If this is not set, functions must be called manually. - If automatic function calls fail, the agents will receive error messages allowing it to retry with another - function call or figure out the answer with its knowledge. - :keyword function_tool: A FunctionTool object representing the tool to be used. - :type function_tool: Optional[_models.FunctionTool] - :keyword max_retry: Maximum number of errors allowed and retry per run or stream. Default value is 10. - :type max_retry: int - """ - - @overload - def enable_auto_function_calls(self, *, toolset: _models.ToolSet, max_retry: int = 10) -> None: - """Enables tool calls to be executed automatically during create_and_process_run or streaming. - If this is not set, functions must be called manually. - If automatic function calls fail, the agents will receive error messages allowing it to retry with another - function call or figure out the answer with its knowledge. - :keyword toolset: A ToolSet object representing the set of tools to be used. - :type toolset: Optional[_models.ToolSet] - :keyword max_retry: Maximum number of errors allowed and retry per run or stream. Default value is 10. - :type max_retry: int - """ - - @distributed_trace - def enable_auto_function_calls( - self, - *, - functions: Optional[Set[Callable[..., Any]]] = None, - function_tool: Optional[_models.FunctionTool] = None, - toolset: Optional[_models.ToolSet] = None, - max_retry: int = 10, - ) -> None: - """Enables tool calls to be executed automatically during create_and_process_run or streaming. - If this is not set, functions must be called manually. - If automatic function calls fail, the agents will receive error messages allowing it to retry with another - function call or figure out the answer with its knowledge. - :keyword functions: A set of callable functions to be used as tools. - :type functions: Set[Callable[..., Any]] - :keyword function_tool: A FunctionTool object representing the tool to be used. - :type function_tool: Optional[_models.FunctionTool] - :keyword toolset: A ToolSet object representing the set of tools to be used. - :type toolset: Optional[_models.ToolSet] - :keyword max_retry: Maximum number of errors allowed and retry per run or stream. Default value is 10. - :type max_retry: int - """ - if functions: - self._function_tool = _models.FunctionTool(functions) - elif function_tool: - self._function_tool = function_tool - elif toolset: - tool = toolset.get_tool(_models.FunctionTool) - self._function_tool = tool - - self._function_tool_max_retry = max_retry - - -__all__: List[str] = [ - "AgentsOperations", - "ConnectionsOperations", - "TelemetryOperations", - "InferenceOperations", -] # Add all objects you want publicly available to users at this package level +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/prompts/__init__.py b/sdk/ai/azure-ai-projects/azure/ai/projects/prompts/__init__.py deleted file mode 100644 index f1e98bf1be1a..000000000000 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/prompts/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -# pylint: disable=unused-import -try: - import prompty # pylint: disable=unused-import -except ImportError as exc: - raise ImportError( - "The 'prompty' package is required to use the 'azure.ai.projects.prompts' module. " - "Please install it by running 'pip install prompty'." - ) from exc - -from ._patch import patch_sdk as _patch_sdk, PromptTemplate - -_patch_sdk() diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/prompts/_patch.py b/sdk/ai/azure-ai-projects/azure/ai/projects/prompts/_patch.py deleted file mode 100644 index 13fd07bcac99..000000000000 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/prompts/_patch.py +++ /dev/null @@ -1,124 +0,0 @@ -# pylint: disable=line-too-long,useless-suppression -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -# pylint: disable=line-too-long,R,no-member -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" - -import traceback -from pathlib import Path -from typing import Any, Dict, List, Optional -from typing_extensions import Self -from prompty import headless, load, prepare -from prompty.core import Prompty -from ._utils import remove_leading_empty_space - - -class PromptTemplate: - """The helper class which takes variant of inputs, e.g. Prompty format or string, and returns the parsed prompt in an array. - Prompty library is required to be installed to use this class. - """ - - @classmethod - def from_prompty(cls, file_path: str) -> Self: - """Initialize a PromptTemplate object from a prompty file. - - :param file_path: The path to the prompty file. - :type file_path: str - :return: The PromptTemplate object. - :rtype: PromptTemplate - """ - if not file_path: - raise ValueError("Please provide file_path") - - # Get the absolute path of the file by `traceback.extract_stack()`, it's "-2" because: - # In the stack, the last function is the current function. - # The second last function is the caller function, which is the root of the file_path. - stack = traceback.extract_stack() - caller = Path(stack[-2].filename) - abs_file_path = Path(caller.parent / Path(file_path)).resolve().absolute() - - prompty = load(str(abs_file_path)) - prompty.template.type = "mustache" # For Azure, default to mustache instead of Jinja2 - return cls(prompty=prompty) - - @classmethod - def from_string(cls, prompt_template: str, api: str = "chat", model_name: Optional[str] = None) -> Self: - """Initialize a PromptTemplate object from a message template. - - :param prompt_template: The prompt template string. - :type prompt_template: str - :param api: The API type, e.g. "chat" or "completion". - :type api: str - :param model_name: The model name, e.g. "gpt-4o-mini". - :type model_name: str - :return: The PromptTemplate object. - :rtype: PromptTemplate - """ - prompt_template = remove_leading_empty_space(prompt_template) - prompty = headless(api=api, content=prompt_template) - prompty.template.type = "mustache" # For Azure, default to mustache instead of Jinja2 - prompty.template.parser = "prompty" - return cls( - api=api, - model_name=model_name, - prompty=prompty, - ) - - def __init__( - self, - *, - api: str = "chat", - prompty: Optional[Prompty] = None, - prompt_template: Optional[str] = None, - model_name: Optional[str] = None, - ) -> None: - self.prompty = prompty - if self.prompty is not None: - self.model_name = ( - self.prompty.model.configuration["azure_deployment"] - if "azure_deployment" in self.prompty.model.configuration - else None - ) - self.parameters = self.prompty.model.parameters - self._config = {} - elif prompt_template is not None: - self.model_name = model_name - self.parameters = {} - # _config is a dict to hold the internal configuration - self._config = { - "api": api if api is not None else "chat", - "prompt_template": prompt_template, - } - else: - raise ValueError("Please pass valid arguments for PromptTemplate") - - def create_messages(self, data: Optional[Dict[str, Any]] = None, **kwargs) -> List[Dict[str, Any]]: - """Render the prompt template with the given data. - - :param data: The data to render the prompt template with. - :type data: Optional[Dict[str, Any]] - :return: The rendered prompt template. - :rtype: List[Dict[str, Any]] - """ - if data is None: - data = kwargs - - if self.prompty is not None: - parsed = prepare(self.prompty, data) - return parsed # type: ignore - else: - raise ValueError("Please provide valid prompt template") - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/prompts/_utils.py b/sdk/ai/azure-ai-projects/azure/ai/projects/prompts/_utils.py deleted file mode 100644 index a85e193322e5..000000000000 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/prompts/_utils.py +++ /dev/null @@ -1,39 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -import sys - - -def remove_leading_empty_space(multiline_str: str) -> str: - """ - Processes a multiline string by: - 1. Removing empty lines - 2. Finding the minimum leading spaces - 3. Indenting all lines to the minimum level - - :param multiline_str: The input multiline string. - :type multiline_str: str - :return: The processed multiline string. - :rtype: str - """ - lines = multiline_str.splitlines() - start_index = 0 - while start_index < len(lines) and lines[start_index].strip() == "": - start_index += 1 - - # Find the minimum number of leading spaces - min_spaces = sys.maxsize - for line in lines[start_index:]: - if len(line.strip()) == 0: - continue - spaces = len(line) - len(line.lstrip()) - spaces += line.lstrip().count("\t") * 2 # Count tabs as 2 spaces - min_spaces = min(min_spaces, spaces) - - # Remove leading spaces and indent to the minimum level - processed_lines = [] - for line in lines[start_index:]: - processed_lines.append(line[min_spaces:]) - - return "\n".join(processed_lines) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_trace_function.py b/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_trace_function.py deleted file mode 100644 index 7a1284e88af5..000000000000 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/_trace_function.py +++ /dev/null @@ -1,204 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -import functools -import asyncio # pylint: disable=do-not-import-asyncio -from typing import Any, Callable, Optional, Dict - -try: - # pylint: disable = no-name-in-module - from opentelemetry import trace as opentelemetry_trace - - tracer = opentelemetry_trace.get_tracer(__name__) - _tracing_library_available = True -except ModuleNotFoundError: - _tracing_library_available = False - -if _tracing_library_available: - - def trace_function(span_name: Optional[str] = None): - """ - A decorator for tracing function calls using OpenTelemetry. - - This decorator handles various data types for function parameters and return values, - and records them as attributes in the trace span. The supported data types include: - - Basic data types: str, int, float, bool - - Collections: list, dict, tuple, set - - Special handling for collections: - - If a collection (list, dict, tuple, set) contains nested collections, the entire collection - is converted to a string before being recorded as an attribute. - - Sets and dictionaries are always converted to strings to ensure compatibility with span attributes. - - Object types are omitted, and the corresponding parameter is not traced. - - :param span_name: The name of the span. If not provided, the function name is used. - :type span_name: Optional[str] - :return: The decorated function with tracing enabled. - :rtype: Callable - """ - - def decorator(func: Callable) -> Callable: - @functools.wraps(func) - async def async_wrapper(*args: Any, **kwargs: Any) -> Any: - """ - Wrapper function for asynchronous functions. - - :param args: Positional arguments passed to the function. - :type args: Tuple[Any] - :return: The result of the decorated asynchronous function. - :rtype: Any - """ - name = span_name if span_name else func.__name__ - with tracer.start_as_current_span(name) as span: - try: - # Sanitize parameters and set them as attributes - sanitized_params = sanitize_parameters(func, *args, **kwargs) - span.set_attributes(sanitized_params) - result = await func(*args, **kwargs) - sanitized_result = sanitize_for_attributes(result) - if sanitized_result is not None: - if isinstance(sanitized_result, (list, dict, tuple, set)): - if any(isinstance(i, (list, dict, tuple, set)) for i in sanitized_result): - sanitized_result = str(sanitized_result) - span.set_attribute("code.function.return.value", sanitized_result) # type: ignore - return result - except Exception as e: - span.record_exception(e) - span.set_attribute("error.type", e.__class__.__qualname__) # type: ignore - raise - - @functools.wraps(func) - def sync_wrapper(*args: Any, **kwargs: Any) -> Any: - """ - Wrapper function for synchronous functions. - - :param args: Positional arguments passed to the function. - :type args: Tuple[Any] - :return: The result of the decorated synchronous function. - :rtype: Any - """ - name = span_name if span_name else func.__name__ - with tracer.start_as_current_span(name) as span: - try: - # Sanitize parameters and set them as attributes - sanitized_params = sanitize_parameters(func, *args, **kwargs) - span.set_attributes(sanitized_params) - result = func(*args, **kwargs) - sanitized_result = sanitize_for_attributes(result) - if sanitized_result is not None: - if isinstance(sanitized_result, (list, dict, tuple, set)): - if any(isinstance(i, (list, dict, tuple, set)) for i in sanitized_result): - sanitized_result = str(sanitized_result) - span.set_attribute("code.function.return.value", sanitized_result) # type: ignore - return result - except Exception as e: - span.record_exception(e) - span.set_attribute("error.type", e.__class__.__qualname__) # type: ignore - raise - - # Determine if the function is async - if asyncio.iscoroutinefunction(func): - return async_wrapper - return sync_wrapper - - return decorator - -else: - # Define a no-op decorator if OpenTelemetry is not available - def trace_function(span_name: Optional[str] = None): # pylint: disable=unused-argument - """ - A no-op decorator for tracing function calls when OpenTelemetry is not available. - - :param span_name: Not used in this version. - :type span_name: Optional[str] - :return: The original function. - :rtype: Callable - """ - - def decorator(func: Callable) -> Callable: - return func - - return decorator - - -def sanitize_parameters(func, *args, **kwargs) -> Dict[str, Any]: - """ - Sanitize function parameters to include only built-in data types. - - :param func: The function being decorated. - :type func: Callable - :param args: Positional arguments passed to the function. - :type args: Tuple[Any] - :return: A dictionary of sanitized parameters. - :rtype: Dict[str, Any] - """ - import inspect - - params = inspect.signature(func).parameters - sanitized_params = {} - - for i, (name, param) in enumerate(params.items()): - if param.default == inspect.Parameter.empty and i < len(args): - value = args[i] - else: - value = kwargs.get(name, param.default) - - sanitized_value = sanitize_for_attributes(value) - # Check if the collection has nested collections - if isinstance(sanitized_value, (list, dict, tuple, set)): - if any(isinstance(i, (list, dict, tuple, set)) for i in sanitized_value): - sanitized_value = str(sanitized_value) - if sanitized_value is not None: - sanitized_params["code.function.parameter." + name] = sanitized_value - - return sanitized_params - - -# pylint: disable=R0911 -def sanitize_for_attributes(value: Any, is_recursive: bool = False) -> Any: - """ - Sanitize a value to be used as an attribute. - - :param value: The value to sanitize. - :type value: Any - :param is_recursive: Indicates if the function is being called recursively. Default is False. - :type is_recursive: bool - :return: The sanitized value or None if the value is not a supported type. - :rtype: Any - """ - if isinstance(value, (str, int, float, bool)): - return value - if isinstance(value, list): - return [ - sanitize_for_attributes(item, True) - for item in value - if isinstance(item, (str, int, float, bool, list, dict, tuple, set)) - ] - if isinstance(value, dict): - retval = { - k: sanitize_for_attributes(v, True) - for k, v in value.items() - if isinstance(v, (str, int, float, bool, list, dict, tuple, set)) - } - # dict to compatible with span attribute, so return it as a string - if is_recursive: - return retval - return str(retval) - if isinstance(value, tuple): - return tuple( - sanitize_for_attributes(item, True) - for item in value - if isinstance(item, (str, int, float, bool, list, dict, tuple, set)) - ) - if isinstance(value, set): - retval_set = { - sanitize_for_attributes(item, True) - for item in value - if isinstance(item, (str, int, float, bool, list, dict, tuple, set)) - } - if is_recursive: - return retval_set - return str(retval_set) - return None diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/agents/_ai_agents_instrumentor.py b/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/agents/_ai_agents_instrumentor.py deleted file mode 100644 index 1bad54f7087a..000000000000 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/agents/_ai_agents_instrumentor.py +++ /dev/null @@ -1,2123 +0,0 @@ -# pylint: disable=too-many-lines,line-too-long,useless-suppression -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -import copy -import functools -import importlib -import json -import logging -import os -from datetime import datetime -from enum import Enum -from typing import Any, Callable, Dict, List, Optional, Tuple, Union, cast -from urllib.parse import urlparse - -from azure.ai.projects import _types -from azure.ai.projects.models import AgentRunStream, AsyncAgentRunStream, _models -from azure.ai.projects.models._enums import AgentsApiResponseFormatMode, MessageRole, RunStepStatus -from azure.ai.projects.models import ( - MessageAttachment, - MessageDeltaChunk, - MessageIncompleteDetails, - RunStep, - RunStepDeltaChunk, - RunStepError, - RunStepFunctionToolCall, - RunStepToolCallDetails, - RunStepCodeInterpreterToolCall, - RunStepBingGroundingToolCall, - ThreadMessage, - ThreadRun, - ToolDefinition, - ToolOutput, - ToolResources, -) -from azure.ai.projects.models._patch import AgentEventHandler, AsyncAgentEventHandler, ToolSet -from azure.ai.projects.telemetry.agents._utils import ( - AZ_AI_AGENT_SYSTEM, - ERROR_TYPE, - GEN_AI_AGENT_DESCRIPTION, - GEN_AI_AGENT_ID, - GEN_AI_AGENT_NAME, - GEN_AI_EVENT_CONTENT, - GEN_AI_MESSAGE_ID, - GEN_AI_MESSAGE_STATUS, - GEN_AI_RESPONSE_MODEL, - GEN_AI_SYSTEM, - GEN_AI_SYSTEM_MESSAGE, - GEN_AI_THREAD_ID, - GEN_AI_THREAD_RUN_ID, - GEN_AI_THREAD_RUN_STATUS, - GEN_AI_USAGE_INPUT_TOKENS, - GEN_AI_USAGE_OUTPUT_TOKENS, - GEN_AI_RUN_STEP_START_TIMESTAMP, - GEN_AI_RUN_STEP_END_TIMESTAMP, - GEN_AI_RUN_STEP_STATUS, - ERROR_MESSAGE, - OperationName, - start_span, -) -from azure.core import CaseInsensitiveEnumMeta # type: ignore -from azure.core.settings import settings -from azure.core.tracing import AbstractSpan - -_Unset: Any = object() - -try: - # pylint: disable = no-name-in-module - from opentelemetry.trace import Span, StatusCode - - _tracing_library_available = True -except ModuleNotFoundError: - _tracing_library_available = False - - -__all__ = [ - "AIAgentsInstrumentor", -] - - -_agents_traces_enabled: bool = False -_trace_agents_content: bool = False - - -class TraceType(str, Enum, metaclass=CaseInsensitiveEnumMeta): # pylint: disable=C4747 - """An enumeration class to represent different types of traces.""" - - AGENTS = "Agents" - - -class AIAgentsInstrumentor: - """ - A class for managing the trace instrumentation of AI Agents. - - This class allows enabling or disabling tracing for AI Agents. - and provides functionality to check whether instrumentation is active. - - """ - - def __init__(self): - if not _tracing_library_available: - raise ModuleNotFoundError( - "Azure Core Tracing Opentelemetry is not installed. " - "Please install it using 'pip install azure-core-tracing-opentelemetry'" - ) - # In the future we could support different versions from the same library - # and have a parameter that specifies the version to use. - self._impl = _AIAgentsInstrumentorPreview() - - def instrument(self, enable_content_recording: Optional[bool] = None) -> None: - """ - Enable trace instrumentation for AI Agents. - - :param enable_content_recording: Whether content recording is enabled as part - of the traces or not. Content in this context refers to chat message content - and function call tool related function names, function parameter names and - values. True will enable content recording, False will disable it. If no value - is provided, then the value read from environment variable - AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED is used. If the environment variable - is not found, then the value will default to False. Please note that successive calls - to instrument will always apply the content recording value provided with the most - recent call to instrument (including applying the environment variable if no value is - provided and defaulting to false if the environment variable is not found), even if - instrument was already previously called without uninstrument being called in between - the instrument calls. - :type enable_content_recording: bool, optional - - """ - self._impl.instrument(enable_content_recording) - - def uninstrument(self) -> None: - """ - Remove trace instrumentation for AI Agents. - - This method removes any active instrumentation, stopping the tracing - of AI Agents. - """ - self._impl.uninstrument() - - def is_instrumented(self) -> bool: - """ - Check if trace instrumentation for AI Agents is currently enabled. - - :return: True if instrumentation is active, False otherwise. - :rtype: bool - """ - return self._impl.is_instrumented() - - def is_content_recording_enabled(self) -> bool: - """This function gets the content recording value. - - :return: A bool value indicating whether content recording is enabled. - :rtype: bool - """ - return self._impl.is_content_recording_enabled() - - -class _AIAgentsInstrumentorPreview: - # pylint: disable=R0904 - """ - A class for managing the trace instrumentation of AI Agents. - - This class allows enabling or disabling tracing for AI Agents. - and provides functionality to check whether instrumentation is active. - """ - - def _str_to_bool(self, s): - if s is None: - return False - return str(s).lower() == "true" - - def instrument(self, enable_content_recording: Optional[bool] = None): - """ - Enable trace instrumentation for AI Agents. - - :param enable_content_recording: Whether content recording is enabled as part - of the traces or not. Content in this context refers to chat message content - and function call tool related function names, function parameter names and - values. True will enable content recording, False will disable it. If no value - is provided, then the value read from environment variable - AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED is used. If the environment variable - is not found, then the value will default to False. - - :type enable_content_recording: bool, optional - """ - if enable_content_recording is None: - var_value = os.environ.get("AZURE_TRACING_GEN_AI_CONTENT_RECORDING_ENABLED") - enable_content_recording = self._str_to_bool(var_value) - if not self.is_instrumented(): - self._instrument_agents(enable_content_recording) - else: - self._set_enable_content_recording(enable_content_recording=enable_content_recording) - - def uninstrument(self): - """ - Disable trace instrumentation for AI Agents. - - This method removes any active instrumentation, stopping the tracing - of AI Agents. - """ - if self.is_instrumented(): - self._uninstrument_agents() - - def is_instrumented(self): - """ - Check if trace instrumentation for AI Agents is currently enabled. - - :return: True if instrumentation is active, False otherwise. - :rtype: bool - """ - return self._is_instrumented() - - def set_enable_content_recording(self, enable_content_recording: bool = False) -> None: - """This function sets the content recording value. - - :param enable_content_recording: Indicates whether tracing of message content should be enabled. - This also controls whether function call tool function names, - parameter names and parameter values are traced. - :type enable_content_recording: bool - """ - self._set_enable_content_recording(enable_content_recording=enable_content_recording) - - def is_content_recording_enabled(self) -> bool: - """This function gets the content recording value. - - :return: A bool value indicating whether content tracing is enabled. - :rtype bool - """ - return self._is_content_recording_enabled() - - def _set_attributes(self, span: "AbstractSpan", *attrs: Tuple[str, Any]) -> None: - for attr in attrs: - key, value = attr - if value is not None: - span.add_attribute(key, value) - - def _parse_url(self, url): - parsed = urlparse(url) - server_address = parsed.hostname - port = parsed.port - return server_address, port - - def _remove_function_call_names_and_arguments(self, tool_calls: list) -> list: - tool_calls_copy = copy.deepcopy(tool_calls) - for tool_call in tool_calls_copy: - if "function" in tool_call: - if "name" in tool_call["function"]: - del tool_call["function"]["name"] - if "arguments" in tool_call["function"]: - del tool_call["function"]["arguments"] - if not tool_call["function"]: - del tool_call["function"] - return tool_calls_copy - - def _create_event_attributes( - self, - thread_id: Optional[str] = None, - agent_id: Optional[str] = None, - thread_run_id: Optional[str] = None, - message_id: Optional[str] = None, - message_status: Optional[str] = None, - run_step_status: Optional[str] = None, - created_at: Optional[datetime] = None, - completed_at: Optional[datetime] = None, - cancelled_at: Optional[datetime] = None, - failed_at: Optional[datetime] = None, - run_step_last_error: Optional[RunStepError] = None, - usage: Optional[_models.RunStepCompletionUsage] = None, - ) -> Dict[str, Any]: - attrs: Dict[str, Any] = {GEN_AI_SYSTEM: AZ_AI_AGENT_SYSTEM} - if thread_id: - attrs[GEN_AI_THREAD_ID] = thread_id - - if agent_id: - attrs[GEN_AI_AGENT_ID] = agent_id - - if thread_run_id: - attrs[GEN_AI_THREAD_RUN_ID] = thread_run_id - - if message_id: - attrs[GEN_AI_MESSAGE_ID] = message_id - - if message_status: - attrs[GEN_AI_MESSAGE_STATUS] = self._status_to_string(message_status) - - if run_step_status: - attrs[GEN_AI_RUN_STEP_STATUS] = self._status_to_string(run_step_status) - - if created_at: - if isinstance(created_at, datetime): - attrs[GEN_AI_RUN_STEP_START_TIMESTAMP] = created_at.isoformat() - else: - # fallback in case integer or string gets passed - attrs[GEN_AI_RUN_STEP_START_TIMESTAMP] = str(created_at) - - end_timestamp = None - if completed_at: - end_timestamp = completed_at - elif cancelled_at: - end_timestamp = cancelled_at - elif failed_at: - end_timestamp = failed_at - - if isinstance(end_timestamp, datetime): - attrs[GEN_AI_RUN_STEP_END_TIMESTAMP] = end_timestamp.isoformat() - elif end_timestamp: - # fallback in case int or string gets passed - attrs[GEN_AI_RUN_STEP_END_TIMESTAMP] = str(end_timestamp) - - if run_step_last_error: - attrs[ERROR_MESSAGE] = run_step_last_error.message - attrs[ERROR_TYPE] = run_step_last_error.code - - if usage: - attrs[GEN_AI_USAGE_INPUT_TOKENS] = usage.prompt_tokens - attrs[GEN_AI_USAGE_OUTPUT_TOKENS] = usage.completion_tokens - - return attrs - - def add_thread_message_event( - self, span, message: ThreadMessage, usage: Optional[_models.RunStepCompletionUsage] = None - ) -> None: - content_body = {} - if _trace_agents_content: - for content in message.content: - typed_content = content.get(content.type, None) - if typed_content: - content_details = {"value": self._get_field(typed_content, "value")} - annotations = self._get_field(typed_content, "annotations") - if annotations: - content_details["annotations"] = [a.as_dict() for a in annotations] - content_body[content.type] = content_details - - self._add_message_event( - span, - self._get_role(message.role), - content_body, - attachments=message.attachments, - thread_id=message.thread_id, - agent_id=message.agent_id, - message_id=message.id, - thread_run_id=message.run_id, - message_status=message.status, - incomplete_details=message.incomplete_details, - usage=usage, - ) - - def _process_tool_calls(self, step: RunStep) -> List[Dict[str, Any]]: - """ - Helper method to process tool calls and return a list of tool call dictionaries. - - :param step: The run step containing tool call details to be processed. - :type step: RunStep - :return: A list of dictionaries, each representing a processed tool call. - :rtype: List[Dict[str, Any]] - """ - tool_calls = [] - tool_call: Dict[str, Any] = {} - for t in cast(RunStepToolCallDetails, step.step_details).tool_calls: - if not _trace_agents_content: - tool_call = { - "id": t.id, - "type": t.type, - } - elif isinstance(t, RunStepFunctionToolCall): - try: - parsed_arguments = json.loads(t.function.arguments) - except json.JSONDecodeError: - parsed_arguments = {} - - tool_call = { - "id": t.id, - "type": t.type, - "function": { - "name": t.function.name, - "arguments": parsed_arguments, - }, - } - elif isinstance(t, RunStepCodeInterpreterToolCall): - tool_call = { - "id": t.id, - "type": t.type, - "code_interpreter": { - "input": t.code_interpreter.input, - "outputs": [output.as_dict() for output in t.code_interpreter.outputs], - }, - } - elif isinstance(t, RunStepBingGroundingToolCall): - tool_call = { - "id": t.id, - "type": t.type, - t.type: t.bing_grounding, - } - else: - tool_details = t.as_dict()[t.type] - - tool_call = { - "id": t.id, - "type": t.type, - t.type: tool_details, - } - tool_calls.append(tool_call) - return tool_calls - - def _add_tool_call_event( - self, - span, - step: RunStep, - event_name: str, - is_run_step_listing: bool = False, - ) -> None: - """ - Adds a tool call event to a span. - - This method processes tool calls from a given run step and adds them as an event - to the provided span. It includes relevant attributes such as the run step status, - timestamps, tool call details, and optionally the message status. - - :param span: The span instance where the tool call event will be recorded. - :type span: AbstractSpan - :param step: The run step containing details about the tool calls to be processed. - :type step: RunStep - :param event_name: The name of the event to be added to the span (e.g., "gen_ai.run_step.tool_calls"). - :type event_name: str - :param is_run_step_listing: A flag indicating whether the event is part of a run step listing. - If True, the run step status is included in the attributes; otherwise, the message status is included. - :type is_run_step_listing: bool - :return: None - """ - tool_calls = self._process_tool_calls(step) - - run_step_status = None - message_status = None - if is_run_step_listing: - run_step_status = step.status - else: - message_status = step.status - - attributes = self._create_event_attributes( - thread_id=step.thread_id, - agent_id=step.agent_id, - thread_run_id=step.run_id, - message_status=message_status, - run_step_status=run_step_status, - created_at=step.created_at, - completed_at=step.completed_at, - cancelled_at=step.cancelled_at, - failed_at=step.failed_at, - run_step_last_error=step.last_error, - usage=step.usage, - ) - - if tool_calls: - attributes[GEN_AI_EVENT_CONTENT] = json.dumps({"tool_calls": tool_calls}, ensure_ascii=False) - - span.span_instance.add_event(name=event_name, attributes=attributes) - - def add_run_step_event(self, span, step: RunStep) -> None: - """ - Adds a run step event to the span. - - This method determines the type of the run step and adds the appropriate event - to the provided span. It processes either a "message_creation" or "tool_calls" - run step and includes relevant attributes such as the run step status, timestamps, - and tool call or message details. - - :param span: The span instance where the run step event will be recorded. - :type span: AbstractSpan - :param step: The run step containing details about the event to be added. - :type step: RunStep - :return: None - """ - if step["type"] == "message_creation": - self._add_message_creation_run_step_event(span, step) - elif step["type"] == "tool_calls": - self._add_tool_call_event(span, step, "gen_ai.run_step.tool_calls", is_run_step_listing=True) - - def _add_message_creation_run_step_event(self, span, step: RunStep) -> None: - attributes = self._create_event_attributes( - thread_id=step.thread_id, - agent_id=step.agent_id, - thread_run_id=step.run_id, - message_id=step["step_details"]["message_creation"]["message_id"], - run_step_status=step.status, - created_at=step.created_at, - completed_at=step.completed_at, - cancelled_at=step.cancelled_at, - failed_at=step.failed_at, - run_step_last_error=step.last_error, - usage=step.usage, - ) - span.span_instance.add_event(name="gen_ai.run_step.message_creation", attributes=attributes) - - def _add_message_event( - self, - span, - role: str, - content: Any, - attachments: Any = None, # Optional[List[MessageAttachment]] or dict - thread_id: Optional[str] = None, - agent_id: Optional[str] = None, - message_id: Optional[str] = None, - thread_run_id: Optional[str] = None, - message_status: Optional[str] = None, - incomplete_details: Optional[MessageIncompleteDetails] = None, - usage: Optional[_models.RunStepCompletionUsage] = None, - ) -> None: - # TODO document new fields - - event_body = {} - if _trace_agents_content: - event_body["content"] = content - if attachments: - event_body["attachments"] = [] - for attachment in attachments: - attachment_body = {"id": attachment.file_id} - if attachment.tools: - attachment_body["tools"] = [self._get_field(tool, "type") for tool in attachment.tools] - event_body["attachments"].append(attachment_body) - - if incomplete_details: - event_body["incomplete_details"] = incomplete_details - event_body["role"] = role - - attributes = self._create_event_attributes( - thread_id=thread_id, - agent_id=agent_id, - thread_run_id=thread_run_id, - message_id=message_id, - message_status=message_status, - usage=usage, - ) - attributes[GEN_AI_EVENT_CONTENT] = json.dumps(event_body, ensure_ascii=False) - span.span_instance.add_event(name=f"gen_ai.{role}.message", attributes=attributes) - - def _get_field(self, obj: Any, field: str) -> Any: - if not obj: - return None - - if isinstance(obj, dict): - return obj.get(field, None) - - return getattr(obj, field, None) - - def _add_instructions_event( - self, - span: "AbstractSpan", - instructions: Optional[str], - additional_instructions: Optional[str], - agent_id: Optional[str] = None, - thread_id: Optional[str] = None, - ) -> None: - if not instructions: - return - - event_body: Dict[str, Any] = {} - if _trace_agents_content and (instructions or additional_instructions): - if instructions and additional_instructions: - event_body["content"] = f"{instructions} {additional_instructions}" - else: - event_body["content"] = instructions or additional_instructions - - attributes = self._create_event_attributes(agent_id=agent_id, thread_id=thread_id) - attributes[GEN_AI_EVENT_CONTENT] = json.dumps(event_body, ensure_ascii=False) - span.span_instance.add_event(name=GEN_AI_SYSTEM_MESSAGE, attributes=attributes) - - def _get_role(self, role: Optional[Union[str, MessageRole]]) -> str: - if role is None or role is _Unset: - return "user" - - if isinstance(role, MessageRole): - return role.value - - return role - - def _status_to_string(self, status: Any) -> str: - return status.value if hasattr(status, "value") else status - - def _add_tool_assistant_message_event(self, span, step: RunStep) -> None: - self._add_tool_call_event(span, step, "gen_ai.assistant.message", is_run_step_listing=False) - - def set_end_run(self, span: "AbstractSpan", run: Optional[ThreadRun]) -> None: - if run and span and span.span_instance.is_recording: - span.add_attribute(GEN_AI_THREAD_RUN_STATUS, self._status_to_string(run.status)) - span.add_attribute(GEN_AI_RESPONSE_MODEL, run.model) - if run and run.usage: - span.add_attribute(GEN_AI_USAGE_INPUT_TOKENS, run.usage.prompt_tokens) - span.add_attribute(GEN_AI_USAGE_OUTPUT_TOKENS, run.usage.completion_tokens) - - @staticmethod - def agent_api_response_to_str(response_format: Any) -> Optional[str]: - """ - Convert response_format to string. - - :param response_format: The response format. - :type response_format: ~azure.ai.projects._types.AgentsApiResponseFormatOption - :returns: string for the response_format. - :rtype: Optional[str] - :raises: Value error if response_format is not of type AgentsApiResponseFormatOption. - """ - if isinstance(response_format, str) or response_format is None: - return response_format - if isinstance(response_format, AgentsApiResponseFormatMode): - return response_format.value - if isinstance(response_format, _models.AgentsApiResponseFormat): - return response_format.type - if isinstance(response_format, _models.ResponseFormatJsonSchemaType): - return response_format.type - raise ValueError(f"Unknown response format {type(response_format)}") - - def start_thread_run_span( - self, - operation_name: OperationName, - project_name: str, - thread_id: Optional[str] = None, - agent_id: Optional[str] = None, - model: Optional[str] = None, - instructions: Optional[str] = None, - additional_instructions: Optional[str] = None, - additional_messages: Optional[List[ThreadMessage]] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - _tools: Optional[List[ToolDefinition]] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - ) -> "Optional[AbstractSpan]": - span = start_span( - operation_name, - project_name, - thread_id=thread_id, - agent_id=agent_id, - model=model, - temperature=temperature, - top_p=top_p, - max_prompt_tokens=max_prompt_tokens, - max_completion_tokens=max_completion_tokens, - response_format=_AIAgentsInstrumentorPreview.agent_api_response_to_str(response_format), - ) - if span and span.span_instance.is_recording and instructions and additional_instructions: - self._add_instructions_event( - span, instructions, additional_instructions, thread_id=thread_id, agent_id=agent_id - ) - - if additional_messages: - for message in additional_messages: - self.add_thread_message_event(span, message) - return span - - def start_submit_tool_outputs_span( - self, - project_name: str, - thread_id: Optional[str] = None, - run_id: Optional[str] = None, - tool_outputs: Optional[List[ToolOutput]] = None, - event_handler: Optional[Union[AgentEventHandler, AsyncAgentEventHandler]] = None, - ) -> "Optional[AbstractSpan]": - run_span = event_handler.span if isinstance(event_handler, _AgentEventHandlerTraceWrapper) else None - if run_span is None: - run_span = event_handler.span if isinstance(event_handler, _AsyncAgentEventHandlerTraceWrapper) else None - - if run_span: - recorded = self._add_tool_message_events(run_span, tool_outputs) - else: - recorded = False - - span = start_span(OperationName.SUBMIT_TOOL_OUTPUTS, project_name, thread_id=thread_id, run_id=run_id) - if not recorded: - self._add_tool_message_events(span, tool_outputs) - return span - - def _add_tool_message_events( - self, span: "Optional[AbstractSpan]", tool_outputs: Optional[List[ToolOutput]] - ) -> bool: - if span and span.span_instance.is_recording and tool_outputs: - for tool_output in tool_outputs: - if _trace_agents_content: - body = {"content": tool_output["output"], "id": tool_output["tool_call_id"]} - else: - body = {"content": "", "id": tool_output["tool_call_id"]} - span.span_instance.add_event( - "gen_ai.tool.message", {"gen_ai.event.content": json.dumps(body, ensure_ascii=False)} - ) - return True - - return False - - def start_create_agent_span( - self, - project_name: str, - model: Optional[str] = None, - name: Optional[str] = None, - description: Optional[str] = None, - instructions: Optional[str] = None, - _tools: Optional[List[ToolDefinition]] = None, - _tool_resources: Optional[ToolResources] = None, - _toolset: Optional[ToolSet] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - response_format: Optional["_types.AgentsApiResponseFormatOption"] = None, - ) -> "Optional[AbstractSpan]": - span = start_span( - OperationName.CREATE_AGENT, - project_name, - span_name=f"{OperationName.CREATE_AGENT.value} {name}", - model=model, - temperature=temperature, - top_p=top_p, - response_format=_AIAgentsInstrumentorPreview.agent_api_response_to_str(response_format), - ) - if span and span.span_instance.is_recording: - if name: - span.add_attribute(GEN_AI_AGENT_NAME, name) - if description: - span.add_attribute(GEN_AI_AGENT_DESCRIPTION, description) - self._add_instructions_event(span, instructions, None) - - return span - - def start_create_thread_span( - self, - project_name: str, - messages: Optional[List[ThreadMessage]] = None, - _tool_resources: Optional[ToolResources] = None, - ) -> "Optional[AbstractSpan]": - span = start_span(OperationName.CREATE_THREAD, project_name) - if span and span.span_instance.is_recording: - for message in messages or []: - self.add_thread_message_event(span, message) - - return span - - def start_list_messages_span(self, project_name: str, thread_id: Optional[str] = None) -> "Optional[AbstractSpan]": - return start_span(OperationName.LIST_MESSAGES, project_name, thread_id=thread_id) - - def start_list_run_steps_span( - self, project_name: str, run_id: Optional[str] = None, thread_id: Optional[str] = None - ) -> "Optional[AbstractSpan]": - return start_span(OperationName.LIST_RUN_STEPS, project_name, run_id=run_id, thread_id=thread_id) - - def trace_create_agent(self, function, *args, **kwargs): - project_name = args[ # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - 0 - ]._config.project_name - name = kwargs.get("name") - model = kwargs.get("model") - description = kwargs.get("description") - instructions = kwargs.get("instructions") - tools = kwargs.get("tools") - tool_resources = kwargs.get("tool_resources") - toolset = kwargs.get("toolset") - temperature = kwargs.get("temperature") - top_p = kwargs.get("top_p") - response_format = kwargs.get("response_format") - - span = self.start_create_agent_span( - project_name=project_name, - name=name, - model=model, - description=description, - instructions=instructions, - _tools=tools, - _tool_resources=tool_resources, - _toolset=toolset, - temperature=temperature, - top_p=top_p, - response_format=response_format, - ) - - if span is None: - return function(*args, **kwargs) - - with span: - try: - result = function(*args, **kwargs) - span.add_attribute(GEN_AI_AGENT_ID, result.id) - except Exception as exc: - # Set the span status to error - if isinstance(span.span_instance, Span): # pyright: ignore [reportPossiblyUnboundVariable] - span.span_instance.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - description=str(exc), - ) - module = getattr(exc, "__module__", "") - module = module if module != "builtins" else "" - error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__ - self._set_attributes(span, ("error.type", error_type)) - raise - - return result - - async def trace_create_agent_async(self, function, *args, **kwargs): - project_name = args[ # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - 0 - ]._config.project_name - name = kwargs.get("name") - model = kwargs.get("model") - description = kwargs.get("description") - instructions = kwargs.get("instructions") - tools = kwargs.get("tools") - tool_resources = kwargs.get("tool_resources") - toolset = kwargs.get("toolset") - temperature = kwargs.get("temperature") - top_p = kwargs.get("top_p") - response_format = kwargs.get("response_format") - - span = self.start_create_agent_span( - project_name=project_name, - name=name, - model=model, - description=description, - instructions=instructions, - _tools=tools, - _tool_resources=tool_resources, - _toolset=toolset, - temperature=temperature, - top_p=top_p, - response_format=response_format, - ) - - if span is None: - return await function(*args, **kwargs) - - with span: - try: - result = await function(*args, **kwargs) - span.add_attribute(GEN_AI_AGENT_ID, result.id) - except Exception as exc: - # Set the span status to error - if isinstance(span.span_instance, Span): # pyright: ignore [reportPossiblyUnboundVariable] - span.span_instance.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - description=str(exc), - ) - module = getattr(exc, "__module__", "") - module = module if module != "builtins" else "" - error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__ - self._set_attributes(span, ("error.type", error_type)) - raise - - return result - - def trace_create_thread(self, function, *args, **kwargs): - project_name = args[ # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - 0 - ]._config.project_name - messages = kwargs.get("messages") - - span = self.start_create_thread_span(project_name=project_name, messages=messages) - - if span is None: - return function(*args, **kwargs) - - with span: - try: - result = function(*args, **kwargs) - span.add_attribute(GEN_AI_THREAD_ID, result.get("id")) - except Exception as exc: - # Set the span status to error - if isinstance(span.span_instance, Span): # pyright: ignore [reportPossiblyUnboundVariable] - span.span_instance.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - description=str(exc), - ) - module = getattr(exc, "__module__", "") - module = module if module != "builtins" else "" - error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__ - self._set_attributes(span, ("error.type", error_type)) - raise - - return result - - async def trace_create_thread_async(self, function, *args, **kwargs): - project_name = args[ # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - 0 - ]._config.project_name - messages = kwargs.get("messages") - - span = self.start_create_thread_span(project_name=project_name, messages=messages) - - if span is None: - return await function(*args, **kwargs) - - with span: - try: - result = await function(*args, **kwargs) - span.add_attribute(GEN_AI_THREAD_ID, result.get("id")) - except Exception as exc: - # Set the span status to error - if isinstance(span.span_instance, Span): # pyright: ignore [reportPossiblyUnboundVariable] - span.span_instance.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - description=str(exc), - ) - module = getattr(exc, "__module__", "") - module = module if module != "builtins" else "" - error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__ - self._set_attributes(span, ("error.type", error_type)) - raise - - return result - - def trace_create_message(self, function, *args, **kwargs): - project_name = args[ # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - 0 - ]._config.project_name - thread_id = kwargs.get("thread_id") - role = kwargs.get("role") - content = kwargs.get("content") - attachments = kwargs.get("attachments") - - span = self.start_create_message_span( - project_name=project_name, thread_id=thread_id, content=content, role=role, attachments=attachments - ) - - if span is None: - return function(*args, **kwargs) - - with span: - try: - result = function(*args, **kwargs) - span.add_attribute(GEN_AI_MESSAGE_ID, result.get("id")) - except Exception as exc: - # Set the span status to error - if isinstance(span.span_instance, Span): # pyright: ignore [reportPossiblyUnboundVariable] - span.span_instance.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - description=str(exc), - ) - module = getattr(exc, "__module__", "") - module = module if module != "builtins" else "" - error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__ - self._set_attributes(span, ("error.type", error_type)) - raise - - return result - - async def trace_create_message_async(self, function, *args, **kwargs): - project_name = args[ # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - 0 - ]._config.project_name - thread_id = kwargs.get("thread_id") - role = kwargs.get("role") - content = kwargs.get("content") - attachments = kwargs.get("attachments") - - span = self.start_create_message_span( - project_name=project_name, thread_id=thread_id, content=content, role=role, attachments=attachments - ) - - if span is None: - return await function(*args, **kwargs) - - with span: - try: - result = await function(*args, **kwargs) - span.add_attribute(GEN_AI_MESSAGE_ID, result.get("id")) - except Exception as exc: - # Set the span status to error - if isinstance(span.span_instance, Span): # pyright: ignore [reportPossiblyUnboundVariable] - span.span_instance.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - description=str(exc), - ) - module = getattr(exc, "__module__", "") - module = module if module != "builtins" else "" - error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__ - self._set_attributes(span, ("error.type", error_type)) - raise - - return result - - def trace_create_run(self, operation_name, function, *args, **kwargs): - project_name = args[ # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - 0 - ]._config.project_name - thread_id = kwargs.get("thread_id") - agent_id = kwargs.get("agent_id") - model = kwargs.get("model") - instructions = kwargs.get("instructions") - additional_instructions = kwargs.get("additional_instructions") - additional_messages = kwargs.get("additional_messages") - temperature = kwargs.get("temperature") - tools = kwargs.get("tools") - top_p = kwargs.get("top_p") - max_prompt_tokens = kwargs.get("max_prompt_tokens") - max_completion_tokens = kwargs.get("max_completion_tokens") - response_format = kwargs.get("response_format") - - span = self.start_thread_run_span( - operation_name, - project_name, - thread_id, - agent_id, - model=model, - instructions=instructions, - additional_instructions=additional_instructions, - additional_messages=additional_messages, - temperature=temperature, - _tools=tools, - top_p=top_p, - max_prompt_tokens=max_prompt_tokens, - max_completion_tokens=max_completion_tokens, - response_format=response_format, - ) - - if span is None: - return function(*args, **kwargs) - - with span: - try: - result = function(*args, **kwargs) - self.set_end_run(span, result) - except Exception as exc: - # Set the span status to error - if isinstance(span.span_instance, Span): # pyright: ignore [reportPossiblyUnboundVariable] - span.span_instance.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - description=str(exc), - ) - module = getattr(exc, "__module__", "") - module = module if module != "builtins" else "" - error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__ - self._set_attributes(span, ("error.type", error_type)) - raise - - return result - - async def trace_create_run_async(self, operation_name, function, *args, **kwargs): - project_name = args[ # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - 0 - ]._config.project_name - thread_id = kwargs.get("thread_id") - agent_id = kwargs.get("agent_id") - model = kwargs.get("model") - instructions = kwargs.get("instructions") - additional_instructions = kwargs.get("additional_instructions") - additional_messages = kwargs.get("additional_messages") - temperature = kwargs.get("temperature") - tools = kwargs.get("tools") - top_p = kwargs.get("top_p") - max_prompt_tokens = kwargs.get("max_prompt_tokens") - max_completion_tokens = kwargs.get("max_completion_tokens") - response_format = kwargs.get("response_format") - - span = self.start_thread_run_span( - operation_name, - project_name, - thread_id, - agent_id, - model=model, - instructions=instructions, - additional_instructions=additional_instructions, - additional_messages=additional_messages, - temperature=temperature, - _tools=tools, - top_p=top_p, - max_prompt_tokens=max_prompt_tokens, - max_completion_tokens=max_completion_tokens, - response_format=response_format, - ) - - if span is None: - return await function(*args, **kwargs) - - with span: - try: - result = await function(*args, **kwargs) - if span.span_instance.is_recording: - span.add_attribute(GEN_AI_THREAD_RUN_STATUS, self._status_to_string(result.status)) - span.add_attribute(GEN_AI_RESPONSE_MODEL, result.model) - if result.usage: - span.add_attribute(GEN_AI_USAGE_INPUT_TOKENS, result.usage.prompt_tokens) - span.add_attribute(GEN_AI_USAGE_OUTPUT_TOKENS, result.usage.completion_tokens) - span.add_attribute(GEN_AI_MESSAGE_ID, result.get("id")) - except Exception as exc: - # Set the span status to error - if isinstance(span.span_instance, Span): # pyright: ignore [reportPossiblyUnboundVariable] - span.span_instance.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - description=str(exc), - ) - module = getattr(exc, "__module__", "") - module = module if module != "builtins" else "" - error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__ - self._set_attributes(span, ("error.type", error_type)) - raise - - return result - - def trace_submit_tool_outputs(self, stream, function, *args, **kwargs): - project_name = args[ # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - 0 - ]._config.project_name - thread_id = kwargs.get("thread_id") - run_id = kwargs.get("run_id") - tool_outputs = kwargs.get("tool_outputs") - event_handler = kwargs.get("event_handler") - - span = self.start_submit_tool_outputs_span( - project_name=project_name, - thread_id=thread_id, - run_id=run_id, - tool_outputs=tool_outputs, - event_handler=event_handler, - ) - - if span is None: - return function(*args, **kwargs) - - with span: - try: - if stream and event_handler: - kwargs["event_handler"] = self.wrap_handler(event_handler, span) - - result = function(*args, **kwargs) - if not isinstance(result, AgentRunStream): - self.set_end_run(span, result) - except Exception as exc: - # Set the span status to error - if isinstance(span.span_instance, Span): # pyright: ignore [reportPossiblyUnboundVariable] - span.span_instance.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - description=str(exc), - ) - module = getattr(exc, "__module__", "") - module = module if module != "builtins" else "" - error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__ - self._set_attributes(span, ("error.type", error_type)) - raise - - return result - - async def trace_submit_tool_outputs_async(self, stream, function, *args, **kwargs): - project_name = args[ # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - 0 - ]._config.project_name - thread_id = kwargs.get("thread_id") - run_id = kwargs.get("run_id") - tool_outputs = kwargs.get("tool_outputs") - event_handler = kwargs.get("event_handler") - - span = self.start_submit_tool_outputs_span( - project_name=project_name, - thread_id=thread_id, - run_id=run_id, - tool_outputs=tool_outputs, - event_handler=event_handler, - ) - - if span is None: - return await function(*args, **kwargs) - - with span: - try: - if stream: - kwargs["event_handler"] = self.wrap_async_handler(event_handler, span) - - result = await function(*args, **kwargs) - if not isinstance(result, AsyncAgentRunStream): - self.set_end_run(span, result) - except Exception as exc: - # Set the span status to error - if isinstance(span.span_instance, Span): # pyright: ignore [reportPossiblyUnboundVariable] - span.span_instance.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - description=str(exc), - ) - module = getattr(exc, "__module__", "") - module = module if module != "builtins" else "" - error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__ - self._set_attributes(span, ("error.type", error_type)) - raise - - return result - - def trace_handle_submit_tool_outputs(self, function, *args, **kwargs): - event_handler = kwargs.get("event_handler") - if event_handler is None: - event_handler = args[2] - span = getattr(event_handler, "span", None) - - if span is None: - return function(*args, **kwargs) - - with span.change_context(span.span_instance): - try: - result = function(*args, **kwargs) - except Exception as exc: - # Set the span status to error - if isinstance(span.span_instance, Span): # pyright: ignore [reportPossiblyUnboundVariable] - span.span_instance.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - description=str(exc), - ) - module = getattr(exc, "__module__", "") - module = module if module != "builtins" else "" - error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__ - self._set_attributes(span, ("error.type", error_type)) - raise - - return result - - async def trace_handle_submit_tool_outputs_async(self, function, *args, **kwargs): - event_handler = kwargs.get("event_handler") - if event_handler is None: - event_handler = args[2] - span = getattr(event_handler, "span", None) - - if span is None: - return await function(*args, **kwargs) - - with span.change_context(span.span_instance): - try: - result = await function(*args, **kwargs) - except Exception as exc: - # Set the span status to error - if isinstance(span.span_instance, Span): # pyright: ignore [reportPossiblyUnboundVariable] - span.span_instance.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - description=str(exc), - ) - module = getattr(exc, "__module__", "") - module = module if module != "builtins" else "" - error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__ - self._set_attributes(span, ("error.type", error_type)) - raise - - return result - - def trace_create_stream(self, function, *args, **kwargs): - operation_name = OperationName.PROCESS_THREAD_RUN - project_name = args[ # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - 0 - ]._config.project_name - thread_id = kwargs.get("thread_id") - agent_id = kwargs.get("agent_id") - model = kwargs.get("model") - instructions = kwargs.get("instructions") - additional_instructions = kwargs.get("additional_instructions") - additional_messages = kwargs.get("additional_messages") - temperature = kwargs.get("temperature") - tools = kwargs.get("tools") - top_p = kwargs.get("top_p") - max_prompt_tokens = kwargs.get("max_prompt_tokens") - max_completion_tokens = kwargs.get("max_completion_tokens") - response_format = kwargs.get("response_format") - event_handler = kwargs.get("event_handler") - - span = self.start_thread_run_span( - operation_name, - project_name, - thread_id, - agent_id, - model=model, - instructions=instructions, - additional_instructions=additional_instructions, - additional_messages=additional_messages, - temperature=temperature, - _tools=tools, - top_p=top_p, - max_prompt_tokens=max_prompt_tokens, - max_completion_tokens=max_completion_tokens, - response_format=response_format, - ) - - if span is None: - return function(*args, **kwargs) - - with span.change_context(span.span_instance): - try: - kwargs["event_handler"] = self.wrap_handler(event_handler, span) - result = function(*args, **kwargs) - except Exception as exc: - # Set the span status to error - if isinstance(span.span_instance, Span): # pyright: ignore [reportPossiblyUnboundVariable] - span.span_instance.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - description=str(exc), - ) - module = getattr(exc, "__module__", "") - module = module if module != "builtins" else "" - error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__ - self._set_attributes(span, ("error.type", error_type)) - raise - - return result - - async def trace_create_stream_async(self, function, *args, **kwargs): - operation_name = OperationName.PROCESS_THREAD_RUN - project_name = args[ # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - 0 - ]._config.project_name - thread_id = kwargs.get("thread_id") - agent_id = kwargs.get("agent_id") - model = kwargs.get("model") - instructions = kwargs.get("instructions") - additional_instructions = kwargs.get("additional_instructions") - additional_messages = kwargs.get("additional_messages") - temperature = kwargs.get("temperature") - tools = kwargs.get("tools") - top_p = kwargs.get("top_p") - max_prompt_tokens = kwargs.get("max_prompt_tokens") - max_completion_tokens = kwargs.get("max_completion_tokens") - response_format = kwargs.get("response_format") - event_handler = kwargs.get("event_handler") - - span = self.start_thread_run_span( - operation_name, - project_name, - thread_id, - agent_id, - model=model, - instructions=instructions, - additional_instructions=additional_instructions, - additional_messages=additional_messages, - temperature=temperature, - _tools=tools, - top_p=top_p, - max_prompt_tokens=max_prompt_tokens, - max_completion_tokens=max_completion_tokens, - response_format=response_format, - ) - - if span is None: - return await function(*args, **kwargs) - - # TODO: how to keep span active in the current context without existing? - # TODO: dummy span for none - with span.change_context(span.span_instance): - try: - kwargs["event_handler"] = self.wrap_async_handler(event_handler, span) - result = await function(*args, **kwargs) - except Exception as exc: - # Set the span status to error - if isinstance(span.span_instance, Span): # pyright: ignore [reportPossiblyUnboundVariable] - span.span_instance.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - description=str(exc), - ) - module = getattr(exc, "__module__", "") - module = module if module != "builtins" else "" - error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__ - self._set_attributes(span, ("error.type", error_type)) - raise - - return result - - def trace_list_messages(self, function, *args, **kwargs): - project_name = args[ # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - 0 - ]._config.project_name - thread_id = kwargs.get("thread_id") - - span = self.start_list_messages_span(project_name=project_name, thread_id=thread_id) - - if span is None: - return function(*args, **kwargs) - - with span: - try: - result = function(*args, **kwargs) - for message in result.data: - self.add_thread_message_event(span, message) - - except Exception as exc: - # Set the span status to error - if isinstance(span.span_instance, Span): # pyright: ignore [reportPossiblyUnboundVariable] - span.span_instance.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - description=str(exc), - ) - module = getattr(exc, "__module__", "") - module = module if module != "builtins" else "" - error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__ - self._set_attributes(span, ("error.type", error_type)) - raise - - return result - - def trace_list_run_steps(self, function, *args, **kwargs): - project_name = args[ # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - 0 - ]._config.project_name - run_id = kwargs.get("run_id") - thread_id = kwargs.get("thread_id") - - span = self.start_list_run_steps_span(project_name=project_name, run_id=run_id, thread_id=thread_id) - - if span is None: - return function(*args, **kwargs) - - with span: - try: - result = function(*args, **kwargs) - if hasattr(result, "data") and result.data is not None: - for step in result.data: - self.add_run_step_event(span, step) - - except Exception as exc: - # Set the span status to error - if isinstance(span.span_instance, Span): # pyright: ignore [reportPossiblyUnboundVariable] - span.span_instance.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - description=str(exc), - ) - module = getattr(exc, "__module__", "") - module = module if module != "builtins" else "" - error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__ - self._set_attributes(span, ("error.type", error_type)) - raise - - return result - - async def trace_list_run_steps_async(self, function, *args, **kwargs): - project_name = args[ # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - 0 - ]._config.project_name - run_id = kwargs.get("run_id") - thread_id = kwargs.get("thread_id") - - span = self.start_list_run_steps_span(project_name=project_name, run_id=run_id, thread_id=thread_id) - - if span is None: - return function(*args, **kwargs) - - with span: - try: - result = await function(*args, **kwargs) - if hasattr(result, "data") and result.data is not None: - for step in result.data: - self.add_run_step_event(span, step) - - except Exception as exc: - # Set the span status to error - if isinstance(span.span_instance, Span): # pyright: ignore [reportPossiblyUnboundVariable] - span.span_instance.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - description=str(exc), - ) - module = getattr(exc, "__module__", "") - module = module if module != "builtins" else "" - error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__ - self._set_attributes(span, ("error.type", error_type)) - raise - - return result - - async def trace_list_messages_async(self, function, *args, **kwargs): - project_name = args[ # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - 0 - ]._config.project_name - thread_id = kwargs.get("thread_id") - - span = self.start_list_messages_span(project_name=project_name, thread_id=thread_id) - - if span is None: - return await function(*args, **kwargs) - - with span: - try: - result = await function(*args, **kwargs) - for message in result.data: - self.add_thread_message_event(span, message) - - except Exception as exc: - # Set the span status to error - if isinstance(span.span_instance, Span): # pyright: ignore [reportPossiblyUnboundVariable] - span.span_instance.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - description=str(exc), - ) - module = getattr(exc, "__module__", "") - module = module if module != "builtins" else "" - error_type = f"{module}.{type(exc).__name__}" if module else type(exc).__name__ - self._set_attributes(span, ("error.type", error_type)) - raise - - return result - - def handle_run_stream_exit(self, _function, *args, **kwargs): - agent_run_stream = args[0] - exc_type = kwargs.get("exc_type") - exc_val = kwargs.get("exc_val") - exc_tb = kwargs.get("exc_tb") - # TODO: is it a good idea? - # if not, we'll need to wrap stream and call exit - if ( - agent_run_stream.event_handler - and agent_run_stream.event_handler.__class__.__name__ == "_AgentEventHandlerTraceWrapper" - ): - agent_run_stream.event_handler.__exit__(exc_type, exc_val, exc_tb) - elif ( - agent_run_stream.event_handler - and agent_run_stream.event_handler.__class__.__name__ == "_AsyncAgentEventHandlerTraceWrapper" - ): - agent_run_stream.event_handler.__aexit__(exc_type, exc_val, exc_tb) - - def wrap_handler( - self, handler: "Optional[AgentEventHandler]" = None, span: "Optional[AbstractSpan]" = None - ) -> "Optional[AgentEventHandler]": - # Do not create a handler wrapper if we do not have handler in the first place. - if not handler: - return None - - if isinstance(handler, _AgentEventHandlerTraceWrapper): - return handler - - if span and span.span_instance.is_recording: - return _AgentEventHandlerTraceWrapper(self, span, handler) - - return handler - - def wrap_async_handler( - self, handler: "Optional[AsyncAgentEventHandler]" = None, span: "Optional[AbstractSpan]" = None - ) -> "Optional[AsyncAgentEventHandler]": - # Do not create a handler wrapper if we do not have handler in the first place. - if not handler: - return None - - if isinstance(handler, _AsyncAgentEventHandlerTraceWrapper): - return handler - - if span and span.span_instance.is_recording: - return _AsyncAgentEventHandlerTraceWrapper(self, span, handler) - - return handler - - def start_create_message_span( - self, - project_name: str, - thread_id: Optional[str] = None, - content: Optional[str] = None, - role: Optional[Union[str, MessageRole]] = None, - attachments: Optional[List[MessageAttachment]] = None, - ) -> "Optional[AbstractSpan]": - role_str = self._get_role(role) - span = start_span(OperationName.CREATE_MESSAGE, project_name, thread_id=thread_id) - if span and span.span_instance.is_recording: - self._add_message_event(span, role_str, content, attachments=attachments, thread_id=thread_id) - return span - - def _trace_sync_function( - self, - function: Callable, - *, - _args_to_ignore: Optional[List[str]] = None, - _trace_type=TraceType.AGENTS, - _name: Optional[str] = None, - ) -> Callable: - """ - Decorator that adds tracing to a synchronous function. - - :param function: The function to be traced. - :type function: Callable - :param args_to_ignore: A list of argument names to be ignored in the trace. - Defaults to None. - :type: args_to_ignore: [List[str]], optional - :param trace_type: The type of the trace. Defaults to TraceType.AGENTS. - :type trace_type: TraceType, optional - :param name: The name of the trace, will set to func name if not provided. - :type name: str, optional - :return: The traced function. - :rtype: Callable - """ - - @functools.wraps(function) - def inner(*args, **kwargs): # pylint: disable=R0911 - span_impl_type = settings.tracing_implementation() # pylint: disable=E1102 - if span_impl_type is None: - return function(*args, **kwargs) - - class_function_name = function.__qualname__ - - if class_function_name.startswith("AgentsOperations.create_agent"): - kwargs.setdefault("merge_span", True) - return self.trace_create_agent(function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations.create_thread"): - kwargs.setdefault("merge_span", True) - return self.trace_create_thread(function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations.create_message"): - kwargs.setdefault("merge_span", True) - return self.trace_create_message(function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations.create_run"): - kwargs.setdefault("merge_span", True) - return self.trace_create_run(OperationName.START_THREAD_RUN, function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations.create_and_process_run"): - kwargs.setdefault("merge_span", True) - return self.trace_create_run(OperationName.PROCESS_THREAD_RUN, function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations.submit_tool_outputs_to_run"): - kwargs.setdefault("merge_span", True) - return self.trace_submit_tool_outputs(False, function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations.submit_tool_outputs_to_stream"): - kwargs.setdefault("merge_span", True) - return self.trace_submit_tool_outputs(True, function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations._handle_submit_tool_outputs"): - return self.trace_handle_submit_tool_outputs(function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations.create_stream"): - kwargs.setdefault("merge_span", True) - return self.trace_create_stream(function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations.list_messages"): - kwargs.setdefault("merge_span", True) - return self.trace_list_messages(function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations.list_run_steps"): - return self.trace_list_run_steps(function, *args, **kwargs) - if class_function_name.startswith("AgentRunStream.__exit__"): - return self.handle_run_stream_exit(function, *args, **kwargs) - # Handle the default case (if the function name does not match) - return None # Ensure all paths return - - return inner - - def _trace_async_function( - self, - function: Callable, - *, - _args_to_ignore: Optional[List[str]] = None, - _trace_type=TraceType.AGENTS, - _name: Optional[str] = None, - ) -> Callable: - """ - Decorator that adds tracing to an asynchronous function. - - :param function: The function to be traced. - :type function: Callable - :param args_to_ignore: A list of argument names to be ignored in the trace. - Defaults to None. - :type: args_to_ignore: [List[str]], optional - :param trace_type: The type of the trace. Defaults to TraceType.AGENTS. - :type trace_type: TraceType, optional - :param name: The name of the trace, will set to func name if not provided. - :type name: str, optional - :return: The traced function. - :rtype: Callable - """ - - @functools.wraps(function) - async def inner(*args, **kwargs): # pylint: disable=R0911 - span_impl_type = settings.tracing_implementation() # pylint: disable=E1102 - if span_impl_type is None: - return function(*args, **kwargs) - - class_function_name = function.__qualname__ - - if class_function_name.startswith("AgentsOperations.create_agent"): - kwargs.setdefault("merge_span", True) - return await self.trace_create_agent_async(function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations.create_thread"): - kwargs.setdefault("merge_span", True) - return await self.trace_create_thread_async(function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations.create_message"): - kwargs.setdefault("merge_span", True) - return await self.trace_create_message_async(function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations.create_run"): - kwargs.setdefault("merge_span", True) - return await self.trace_create_run_async(OperationName.START_THREAD_RUN, function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations.create_and_process_run"): - kwargs.setdefault("merge_span", True) - return await self.trace_create_run_async(OperationName.PROCESS_THREAD_RUN, function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations.submit_tool_outputs_to_run"): - kwargs.setdefault("merge_span", True) - return await self.trace_submit_tool_outputs_async(False, function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations.submit_tool_outputs_to_stream"): - kwargs.setdefault("merge_span", True) - return await self.trace_submit_tool_outputs_async(True, function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations._handle_submit_tool_outputs"): - return await self.trace_handle_submit_tool_outputs_async(function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations.create_stream"): - kwargs.setdefault("merge_span", True) - return await self.trace_create_stream_async(function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations.list_messages"): - kwargs.setdefault("merge_span", True) - return await self.trace_list_messages_async(function, *args, **kwargs) - if class_function_name.startswith("AgentsOperations.list_run_steps"): - kwargs.setdefault("merge_span", True) - return await self.trace_list_run_steps_async(function, *args, **kwargs) - if class_function_name.startswith("AsyncAgentRunStream.__aexit__"): - return self.handle_run_stream_exit(function, *args, **kwargs) - # Handle the default case (if the function name does not match) - return None # Ensure all paths return - - return inner - - def _inject_async(self, f, _trace_type, _name): - wrapper_fun = self._trace_async_function(f) - wrapper_fun._original = f # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - return wrapper_fun - - def _inject_sync(self, f, _trace_type, _name): - wrapper_fun = self._trace_sync_function(f) - wrapper_fun._original = f # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - return wrapper_fun - - def _agents_apis(self): - sync_apis = ( - ("azure.ai.projects.operations", "AgentsOperations", "create_agent", TraceType.AGENTS, "agent_create"), - ("azure.ai.projects.operations", "AgentsOperations", "create_thread", TraceType.AGENTS, "thread_create"), - ("azure.ai.projects.operations", "AgentsOperations", "create_message", TraceType.AGENTS, "message_create"), - ("azure.ai.projects.operations", "AgentsOperations", "create_run", TraceType.AGENTS, "create_run"), - ( - "azure.ai.projects.operations", - "AgentsOperations", - "create_and_process_run", - TraceType.AGENTS, - "create_and_process_run", - ), - ( - "azure.ai.projects.operations", - "AgentsOperations", - "submit_tool_outputs_to_run", - TraceType.AGENTS, - "submit_tool_outputs_to_run", - ), - ( - "azure.ai.projects.operations", - "AgentsOperations", - "submit_tool_outputs_to_stream", - TraceType.AGENTS, - "submit_tool_outputs_to_stream", - ), - ( - "azure.ai.projects.operations", - "AgentsOperations", - "_handle_submit_tool_outputs", - TraceType.AGENTS, - "_handle_submit_tool_outputs", - ), - ("azure.ai.projects.operations", "AgentsOperations", "create_stream", TraceType.AGENTS, "create_stream"), - ("azure.ai.projects.operations", "AgentsOperations", "list_messages", TraceType.AGENTS, "list_messages"), - ("azure.ai.projects.operations", "AgentsOperations", "list_run_steps", TraceType.AGENTS, "list_run_steps"), - ("azure.ai.projects.models", "AgentRunStream", "__exit__", TraceType.AGENTS, "__exit__"), - ) - async_apis = ( - ("azure.ai.projects.aio.operations", "AgentsOperations", "create_agent", TraceType.AGENTS, "agent_create"), - ( - "azure.ai.projects.aio.operations", - "AgentsOperations", - "create_thread", - TraceType.AGENTS, - "agents_thread_create", - ), - ( - "azure.ai.projects.aio.operations", - "AgentsOperations", - "create_message", - TraceType.AGENTS, - "agents_thread_message", - ), - ("azure.ai.projects.aio.operations", "AgentsOperations", "create_run", TraceType.AGENTS, "create_run"), - ( - "azure.ai.projects.aio.operations", - "AgentsOperations", - "create_and_process_run", - TraceType.AGENTS, - "create_and_process_run", - ), - ( - "azure.ai.projects.aio.operations", - "AgentsOperations", - "submit_tool_outputs_to_run", - TraceType.AGENTS, - "submit_tool_outputs_to_run", - ), - ( - "azure.ai.projects.aio.operations", - "AgentsOperations", - "submit_tool_outputs_to_stream", - TraceType.AGENTS, - "submit_tool_outputs_to_stream", - ), - ( - "azure.ai.projects.aio.operations", - "AgentsOperations", - "_handle_submit_tool_outputs", - TraceType.AGENTS, - "_handle_submit_tool_outputs", - ), - ( - "azure.ai.projects.aio.operations", - "AgentsOperations", - "create_stream", - TraceType.AGENTS, - "create_stream", - ), - ( - "azure.ai.projects.aio.operations", - "AgentsOperations", - "list_messages", - TraceType.AGENTS, - "list_messages", - ), - ( - "azure.ai.projects.aio.operations", - "AgentsOperations", - "list_run_steps", - TraceType.AGENTS, - "list_run_steps", - ), - ("azure.ai.projects.models", "AsyncAgentRunStream", "__aexit__", TraceType.AGENTS, "__aexit__"), - ) - return sync_apis, async_apis - - def _agents_api_list(self): - sync_apis, async_apis = self._agents_apis() - yield sync_apis, self._inject_sync - yield async_apis, self._inject_async - - def _generate_api_and_injector(self, apis): - for api, injector in apis: - for module_name, class_name, method_name, trace_type, name in api: - try: - module = importlib.import_module(module_name) - api = getattr(module, class_name) - if hasattr(api, method_name): - yield api, method_name, trace_type, injector, name - except AttributeError as e: - # Log the attribute exception with the missing class information - logging.warning( - "AttributeError: The module '%s' does not have the class '%s'. %s", - module_name, - class_name, - str(e), - ) - except Exception as e: # pylint: disable=broad-except - # Log other exceptions as a warning, as we are not sure what they might be - logging.warning("An unexpected error occurred: '%s'", str(e)) - - def _available_agents_apis_and_injectors(self): - """ - Generates a sequence of tuples containing Agents API classes, method names, and - corresponding injector functions. - - :return: A generator yielding tuples. - :rtype: tuple - """ - yield from self._generate_api_and_injector(self._agents_api_list()) - - def _instrument_agents(self, enable_content_tracing: bool = False): - """This function modifies the methods of the Agents API classes to - inject logic before calling the original methods. - The original methods are stored as _original attributes of the methods. - - :param enable_content_tracing: Indicates whether tracing of message content should be enabled. - This also controls whether function call tool function names, - parameter names and parameter values are traced. - :type enable_content_tracing: bool - """ - # pylint: disable=W0603 - global _agents_traces_enabled - global _trace_agents_content - if _agents_traces_enabled: - raise RuntimeError("Traces already started for AI Agents") - _agents_traces_enabled = True - _trace_agents_content = enable_content_tracing - for ( - api, - method, - trace_type, - injector, - name, - ) in self._available_agents_apis_and_injectors(): - # Check if the method of the api class has already been modified - if not hasattr(getattr(api, method), "_original"): - setattr(api, method, injector(getattr(api, method), trace_type, name)) - - def _uninstrument_agents(self): - """This function restores the original methods of the Agents API classes - by assigning them back from the _original attributes of the modified methods. - """ - # pylint: disable=W0603 - global _agents_traces_enabled - global _trace_agents_content - _trace_agents_content = False - for api, method, _, _, _ in self._available_agents_apis_and_injectors(): - if hasattr(getattr(api, method), "_original"): - setattr(api, method, getattr(getattr(api, method), "_original")) - _agents_traces_enabled = False - - def _is_instrumented(self): - """This function returns True if Agents API has already been instrumented - for tracing and False if it has not been instrumented. - - :return: A value indicating whether the Agents API is currently instrumented or not. - :rtype: bool - """ - return _agents_traces_enabled - - def _set_enable_content_recording(self, enable_content_recording: bool = False) -> None: - """This function sets the content recording value. - - :param enable_content_recording: Indicates whether tracing of message content should be enabled. - This also controls whether function call tool function names, - parameter names and parameter values are traced. - :type enable_content_recording: bool - """ - global _trace_agents_content # pylint: disable=W0603 - _trace_agents_content = enable_content_recording - - def _is_content_recording_enabled(self) -> bool: - """This function gets the content recording value. - - :return: A bool value indicating whether content tracing is enabled. - :rtype bool - """ - return _trace_agents_content - - -class _AgentEventHandlerTraceWrapper(AgentEventHandler): - def __init__( - self, - instrumentor: _AIAgentsInstrumentorPreview, - span: "AbstractSpan", - inner_handler: Optional[AgentEventHandler] = None, - ): - super().__init__() - self.span = span - self.inner_handler = inner_handler - self.ended = False - self.last_run: Optional[ThreadRun] = None - self.last_message: Optional[ThreadMessage] = None - self.instrumentor = instrumentor - - def initialize( - self, - response_iterator, - submit_tool_outputs, - ) -> None: - self.submit_tool_outputs = submit_tool_outputs - if self.inner_handler: - self.inner_handler.initialize(response_iterator=response_iterator, submit_tool_outputs=submit_tool_outputs) - - def __next__(self) -> Any: - if self.inner_handler: - event_bytes = self.inner_handler.__next_impl__() - return self._process_event(event_bytes.decode("utf-8")) - return None - - # pylint: disable=R1710 - def on_message_delta(self, delta: "MessageDeltaChunk") -> None: # type: ignore[func-returns-value] - if self.inner_handler: - return self.inner_handler.on_message_delta(delta) # type: ignore - - def on_thread_message(self, message: "ThreadMessage") -> None: # type: ignore[func-returns-value] - retval = None - if self.inner_handler: - retval = self.inner_handler.on_thread_message(message) # type: ignore - - if message.status in {"completed", "incomplete"}: - self.last_message = message - - return retval # type: ignore - - def on_thread_run(self, run: "ThreadRun") -> None: # type: ignore[func-returns-value] - retval = None - - if self.inner_handler: - retval = self.inner_handler.on_thread_run(run) # type: ignore - self.last_run = run - - return retval # type: ignore - - def on_run_step(self, step: "RunStep") -> None: # type: ignore[func-returns-value] - retval = None - if self.inner_handler: - retval = self.inner_handler.on_run_step(step) # type: ignore - - if ( - step.type == "tool_calls" - and isinstance(step.step_details, RunStepToolCallDetails) - and step.status == RunStepStatus.COMPLETED - ): - self.instrumentor._add_tool_assistant_message_event( # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - self.span, step - ) - elif step.type == "message_creation" and step.status == RunStepStatus.COMPLETED: - self.instrumentor.add_thread_message_event(self.span, cast(ThreadMessage, self.last_message), step.usage) - self.last_message = None - - return retval # type: ignore - - def on_run_step_delta(self, delta: "RunStepDeltaChunk") -> None: # type: ignore[func-returns-value] - if self.inner_handler: - return self.inner_handler.on_run_step_delta(delta) # type: ignore - - def on_error(self, data: str) -> None: # type: ignore[func-returns-value] - if self.inner_handler: - return self.inner_handler.on_error(data) # type: ignore - - def on_done(self) -> None: # type: ignore[func-returns-value] - if self.inner_handler: - return self.inner_handler.on_done() # type: ignore - # it could be called multiple tines (for each step) __exit__ - - def on_unhandled_event(self, event_type: str, event_data: Any) -> None: # type: ignore[func-returns-value] - if self.inner_handler: - return self.inner_handler.on_unhandled_event(event_type, event_data) # type: ignore - - # pylint: enable=R1710 - - def __exit__(self, exc_type, exc_val, exc_tb): - if not self.ended: - self.ended = True - self.instrumentor.set_end_run(self.span, self.last_run) - - if self.last_run and self.last_run.last_error: - self.span.span_instance.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - self.last_run.last_error.message, - ) - self.span.add_attribute(ERROR_TYPE, self.last_run.last_error.code) - - self.span.__exit__(exc_type, exc_val, exc_tb) - self.span.finish() - - -class _AsyncAgentEventHandlerTraceWrapper(AsyncAgentEventHandler): - def __init__( - self, - instrumentor: _AIAgentsInstrumentorPreview, - span: "AbstractSpan", - inner_handler: Optional[AsyncAgentEventHandler] = None, - ): - super().__init__() - self.span = span - self.inner_handler = inner_handler - self.ended = False - self.last_run: Optional[ThreadRun] = None - self.last_message: Optional[ThreadMessage] = None - self.instrumentor = instrumentor - - def initialize( - self, - response_iterator, - submit_tool_outputs, - ) -> None: - self.submit_tool_outputs = submit_tool_outputs - if self.inner_handler: - self.inner_handler.initialize(response_iterator=response_iterator, submit_tool_outputs=submit_tool_outputs) - - # cspell:disable-next-line - async def __anext__(self) -> Any: - if self.inner_handler: - # cspell:disable-next-line - event_bytes = await self.inner_handler.__anext_impl__() - return await self._process_event(event_bytes.decode("utf-8")) - - # pylint: disable=R1710 - async def on_message_delta(self, delta: "MessageDeltaChunk") -> None: # type: ignore[func-returns-value] - if self.inner_handler: - return await self.inner_handler.on_message_delta(delta) # type: ignore - - async def on_thread_message(self, message: "ThreadMessage") -> None: # type: ignore[func-returns-value] - retval = None - if self.inner_handler: - retval = await self.inner_handler.on_thread_message(message) # type: ignore - - if message.status in {"completed", "incomplete"}: - self.last_message = message - - return retval # type: ignore - - async def on_thread_run(self, run: "ThreadRun") -> None: # type: ignore[func-returns-value] - retval = None - - if self.inner_handler: - retval = await self.inner_handler.on_thread_run(run) # type: ignore - self.last_run = run - - return retval # type: ignore - - async def on_run_step(self, step: "RunStep") -> None: # type: ignore[func-returns-value] - retval = None - if self.inner_handler: - retval = await self.inner_handler.on_run_step(step) # type: ignore - - if ( - step.type == "tool_calls" - and isinstance(step.step_details, RunStepToolCallDetails) - and step.status == RunStepStatus.COMPLETED - ): - self.instrumentor._add_tool_assistant_message_event( # pylint: disable=protected-access # pyright: ignore [reportFunctionMemberAccess] - self.span, step - ) - elif step.type == "message_creation" and step.status == RunStepStatus.COMPLETED: - self.instrumentor.add_thread_message_event(self.span, cast(ThreadMessage, self.last_message), step.usage) - self.last_message = None - - return retval # type: ignore - - async def on_run_step_delta(self, delta: "RunStepDeltaChunk") -> None: # type: ignore[func-returns-value] - if self.inner_handler: - return await self.inner_handler.on_run_step_delta(delta) # type: ignore - - async def on_error(self, data: str) -> None: # type: ignore[func-returns-value] - if self.inner_handler: - return await self.inner_handler.on_error(data) # type: ignore - - async def on_done(self) -> None: # type: ignore[func-returns-value] - if self.inner_handler: - return await self.inner_handler.on_done() # type: ignore - # it could be called multiple tines (for each step) __exit__ - - async def on_unhandled_event(self, event_type: str, event_data: Any) -> None: # type: ignore[func-returns-value] - if self.inner_handler: - return await self.inner_handler.on_unhandled_event(event_type, event_data) # type: ignore - - # pylint: enable=R1710 - - def __aexit__(self, exc_type, exc_val, exc_tb): - if not self.ended: - self.ended = True - self.instrumentor.set_end_run(self.span, self.last_run) - - if self.last_run and self.last_run.last_error: - self.span.set_status( - StatusCode.ERROR, # pyright: ignore [reportPossiblyUnboundVariable] - self.last_run.last_error.message, - ) - self.span.add_attribute(ERROR_TYPE, self.last_run.last_error.code) - - self.span.__exit__(exc_type, exc_val, exc_tb) - self.span.finish() diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/agents/_utils.py b/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/agents/_utils.py deleted file mode 100644 index 04d0e3b36801..000000000000 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/agents/_utils.py +++ /dev/null @@ -1,144 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -from enum import Enum -from typing import Optional - -from azure.core.tracing import AbstractSpan, SpanKind # type: ignore -from azure.core.settings import settings # type: ignore - -try: - from opentelemetry.trace import StatusCode, Span # noqa: F401 # pylint: disable=unused-import - - _span_impl_type = settings.tracing_implementation() # pylint: disable=not-callable -except ModuleNotFoundError: - _span_impl_type = None - - -GEN_AI_MESSAGE_ID = "gen_ai.message.id" -GEN_AI_MESSAGE_STATUS = "gen_ai.message.status" -GEN_AI_THREAD_ID = "gen_ai.thread.id" -GEN_AI_THREAD_RUN_ID = "gen_ai.thread.run.id" -GEN_AI_AGENT_ID = "gen_ai.agent.id" -GEN_AI_AGENT_NAME = "gen_ai.agent.name" -GEN_AI_AGENT_DESCRIPTION = "gen_ai.agent.description" -GEN_AI_OPERATION_NAME = "gen_ai.operation.name" -GEN_AI_THREAD_RUN_STATUS = "gen_ai.thread.run.status" -GEN_AI_REQUEST_MODEL = "gen_ai.request.model" -GEN_AI_REQUEST_TEMPERATURE = "gen_ai.request.temperature" -GEN_AI_REQUEST_TOP_P = "gen_ai.request.top_p" -GEN_AI_REQUEST_MAX_INPUT_TOKENS = "gen_ai.request.max_input_tokens" -GEN_AI_REQUEST_MAX_OUTPUT_TOKENS = "gen_ai.request.max_output_tokens" -GEN_AI_RESPONSE_MODEL = "gen_ai.response.model" -GEN_AI_SYSTEM = "gen_ai.system" -SERVER_ADDRESS = "server.address" -AZ_AI_AGENT_SYSTEM = "az.ai.agents" -GEN_AI_TOOL_NAME = "gen_ai.tool.name" -GEN_AI_TOOL_CALL_ID = "gen_ai.tool.call.id" -GEN_AI_REQUEST_RESPONSE_FORMAT = "gen_ai.request.response_format" -GEN_AI_USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens" -GEN_AI_USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens" -GEN_AI_SYSTEM_MESSAGE = "gen_ai.system.message" -GEN_AI_EVENT_CONTENT = "gen_ai.event.content" -GEN_AI_RUN_STEP_START_TIMESTAMP = "gen_ai.run_step.start.timestamp" -GEN_AI_RUN_STEP_END_TIMESTAMP = "gen_ai.run_step.end.timestamp" -GEN_AI_RUN_STEP_STATUS = "gen_ai.run_step.status" -ERROR_TYPE = "error.type" -ERROR_MESSAGE = "error.message" - - -class OperationName(Enum): - CREATE_AGENT = "create_agent" - CREATE_THREAD = "create_thread" - CREATE_MESSAGE = "create_message" - START_THREAD_RUN = "start_thread_run" - EXECUTE_TOOL = "execute_tool" - LIST_MESSAGES = "list_messages" - LIST_RUN_STEPS = "list_run_steps" - SUBMIT_TOOL_OUTPUTS = "submit_tool_outputs" - PROCESS_THREAD_RUN = "process_thread_run" - - -def trace_tool_execution( - tool_call_id: str, - tool_name: str, - thread_id: Optional[str] = None, # TODO: would be nice to have this, but need to propagate somehow - agent_id: Optional[str] = None, # TODO: would be nice to have this, but need to propagate somehow - run_id: Optional[str] = None, # TODO: would be nice to have this, but need to propagate somehow -) -> "Optional[AbstractSpan]": - span = start_span( - OperationName.EXECUTE_TOOL, - server_address=None, - span_name=f"execute_tool {tool_name}", - thread_id=thread_id, - agent_id=agent_id, - run_id=run_id, - gen_ai_system=None, - ) # it's a client code execution, not GenAI span - if span is not None and span.span_instance.is_recording: - span.add_attribute(GEN_AI_TOOL_CALL_ID, tool_call_id) - span.add_attribute(GEN_AI_TOOL_NAME, tool_name) - - return span - - -def start_span( - operation_name: OperationName, - server_address: Optional[str], - span_name: Optional[str] = None, - thread_id: Optional[str] = None, - agent_id: Optional[str] = None, - run_id: Optional[str] = None, - model: Optional[str] = None, - temperature: Optional[float] = None, - top_p: Optional[float] = None, - max_prompt_tokens: Optional[int] = None, - max_completion_tokens: Optional[int] = None, - response_format: Optional[str] = None, - gen_ai_system: Optional[str] = AZ_AI_AGENT_SYSTEM, - kind: SpanKind = SpanKind.CLIENT, -) -> "Optional[AbstractSpan]": - if _span_impl_type is None: - return None - - span = _span_impl_type(name=span_name or operation_name.value, kind=kind) - - if span and span.span_instance.is_recording: - if gen_ai_system: - span.add_attribute(GEN_AI_SYSTEM, AZ_AI_AGENT_SYSTEM) - - span.add_attribute(GEN_AI_OPERATION_NAME, operation_name.value) - - if server_address: - span.add_attribute(SERVER_ADDRESS, server_address) - - if thread_id: - span.add_attribute(GEN_AI_THREAD_ID, thread_id) - - if agent_id: - span.add_attribute(GEN_AI_AGENT_ID, agent_id) - - if run_id: - span.add_attribute(GEN_AI_THREAD_RUN_ID, run_id) - - if model: - span.add_attribute(GEN_AI_REQUEST_MODEL, model) - - if temperature: - span.add_attribute(GEN_AI_REQUEST_TEMPERATURE, str(temperature)) - - if top_p: - span.add_attribute(GEN_AI_REQUEST_TOP_P, str(top_p)) - - if max_prompt_tokens: - span.add_attribute(GEN_AI_REQUEST_MAX_INPUT_TOKENS, max_prompt_tokens) - - if max_completion_tokens: - span.add_attribute(GEN_AI_REQUEST_MAX_OUTPUT_TOKENS, max_completion_tokens) - - if response_format: - span.add_attribute(GEN_AI_REQUEST_RESPONSE_FORMAT, response_format) - - return span diff --git a/sdk/ai/azure-ai-projects/generated_tests/conftest.py b/sdk/ai/azure-ai-projects/generated_tests/conftest.py new file mode 100644 index 000000000000..dd8e527abab1 --- /dev/null +++ b/sdk/ai/azure-ai-projects/generated_tests/conftest.py @@ -0,0 +1,35 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + aiproject_subscription_id = os.environ.get("AIPROJECT_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + aiproject_tenant_id = os.environ.get("AIPROJECT_TENANT_ID", "00000000-0000-0000-0000-000000000000") + aiproject_client_id = os.environ.get("AIPROJECT_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + aiproject_client_secret = os.environ.get("AIPROJECT_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=aiproject_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=aiproject_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=aiproject_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=aiproject_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_connections_operations.py b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_connections_operations.py new file mode 100644 index 000000000000..d93e0e240cca --- /dev/null +++ b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_connections_operations.py @@ -0,0 +1,22 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils import recorded_by_proxy +from testpreparer import AIProjectClientTestBase, AIProjectPreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAIProjectConnectionsOperations(AIProjectClientTestBase): + @AIProjectPreparer() + @recorded_by_proxy + def test_connections_list(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.connections.list() + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_connections_operations_async.py b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_connections_operations_async.py new file mode 100644 index 000000000000..cc08499be0ee --- /dev/null +++ b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_connections_operations_async.py @@ -0,0 +1,23 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import AIProjectPreparer +from testpreparer_async import AIProjectClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAIProjectConnectionsOperationsAsync(AIProjectClientTestBaseAsync): + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_connections_list(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = client.connections.list() + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_datasets_operations.py b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_datasets_operations.py new file mode 100644 index 000000000000..0a78a921b6d4 --- /dev/null +++ b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_datasets_operations.py @@ -0,0 +1,106 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils import recorded_by_proxy +from testpreparer import AIProjectClientTestBase, AIProjectPreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAIProjectDatasetsOperations(AIProjectClientTestBase): + @AIProjectPreparer() + @recorded_by_proxy + def test_datasets_list_versions(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.datasets.list_versions( + name="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy + def test_datasets_list(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.datasets.list() + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy + def test_datasets_get(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.datasets.get( + name="str", + version="str", + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy + def test_datasets_delete(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.datasets.delete( + name="str", + version="str", + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy + def test_datasets_create_or_update(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.datasets.create_or_update( + name="str", + version="str", + dataset_version={ + "dataUri": "str", + "name": "str", + "type": "uri_file", + "version": "str", + "description": "str", + "id": "str", + "isReference": bool, + "tags": {"str": "str"}, + }, + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy + def test_datasets_pending_upload(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.datasets.pending_upload( + name="str", + version="str", + body={"pendingUploadType": "str", "connectionName": "str", "pendingUploadId": "str"}, + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy + def test_datasets_get_credentials(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.datasets.get_credentials( + name="str", + version="str", + body={}, + content_type="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_datasets_operations_async.py b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_datasets_operations_async.py new file mode 100644 index 000000000000..30d1b626ec75 --- /dev/null +++ b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_datasets_operations_async.py @@ -0,0 +1,107 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import AIProjectPreparer +from testpreparer_async import AIProjectClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAIProjectDatasetsOperationsAsync(AIProjectClientTestBaseAsync): + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_datasets_list_versions(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = client.datasets.list_versions( + name="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_datasets_list(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = client.datasets.list() + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_datasets_get(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = await client.datasets.get( + name="str", + version="str", + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_datasets_delete(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = await client.datasets.delete( + name="str", + version="str", + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_datasets_create_or_update(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = await client.datasets.create_or_update( + name="str", + version="str", + dataset_version={ + "dataUri": "str", + "name": "str", + "type": "uri_file", + "version": "str", + "description": "str", + "id": "str", + "isReference": bool, + "tags": {"str": "str"}, + }, + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_datasets_pending_upload(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = await client.datasets.pending_upload( + name="str", + version="str", + body={"pendingUploadType": "str", "connectionName": "str", "pendingUploadId": "str"}, + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_datasets_get_credentials(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = await client.datasets.get_credentials( + name="str", + version="str", + body={}, + content_type="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_deployments_operations.py b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_deployments_operations.py new file mode 100644 index 000000000000..b0e1e586d866 --- /dev/null +++ b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_deployments_operations.py @@ -0,0 +1,33 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils import recorded_by_proxy +from testpreparer import AIProjectClientTestBase, AIProjectPreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAIProjectDeploymentsOperations(AIProjectClientTestBase): + @AIProjectPreparer() + @recorded_by_proxy + def test_deployments_get(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.deployments.get( + name="str", + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy + def test_deployments_list(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.deployments.list() + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_deployments_operations_async.py b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_deployments_operations_async.py new file mode 100644 index 000000000000..3958d83eab29 --- /dev/null +++ b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_deployments_operations_async.py @@ -0,0 +1,34 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import AIProjectPreparer +from testpreparer_async import AIProjectClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAIProjectDeploymentsOperationsAsync(AIProjectClientTestBaseAsync): + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_deployments_get(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = await client.deployments.get( + name="str", + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_deployments_list(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = client.deployments.list() + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_evaluations_operations.py b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_evaluations_operations.py new file mode 100644 index 000000000000..d6f6c0869b48 --- /dev/null +++ b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_evaluations_operations.py @@ -0,0 +1,71 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils import recorded_by_proxy +from testpreparer import AIProjectClientTestBase, AIProjectPreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAIProjectEvaluationsOperations(AIProjectClientTestBase): + @AIProjectPreparer() + @recorded_by_proxy + def test_evaluations_get(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.evaluations.get( + name="str", + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy + def test_evaluations_list(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.evaluations.list() + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy + def test_evaluations_create_run(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.evaluations.create_run( + evaluation={ + "data": "input_data", + "evaluators": {"str": {"id": "str", "dataMapping": {"str": "str"}, "initParams": {"str": {}}}}, + "id": "str", + "description": "str", + "displayName": "str", + "properties": {"str": "str"}, + "status": "str", + "tags": {"str": "str"}, + }, + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy + def test_evaluations_create_agent_evaluation(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.evaluations.create_agent_evaluation( + evaluation={ + "appInsightsConnectionString": "str", + "evaluators": {"str": {"id": "str", "dataMapping": {"str": "str"}, "initParams": {"str": {}}}}, + "runId": "str", + "redactionConfiguration": {"redactScoreProperties": bool}, + "samplingConfiguration": {"maxRequestRate": 0.0, "name": "str", "samplingPercent": 0.0}, + "threadId": "str", + }, + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_evaluations_operations_async.py b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_evaluations_operations_async.py new file mode 100644 index 000000000000..3cf97659ac44 --- /dev/null +++ b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_evaluations_operations_async.py @@ -0,0 +1,72 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import AIProjectPreparer +from testpreparer_async import AIProjectClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAIProjectEvaluationsOperationsAsync(AIProjectClientTestBaseAsync): + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_evaluations_get(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = await client.evaluations.get( + name="str", + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_evaluations_list(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = client.evaluations.list() + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_evaluations_create_run(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = await client.evaluations.create_run( + evaluation={ + "data": "input_data", + "evaluators": {"str": {"id": "str", "dataMapping": {"str": "str"}, "initParams": {"str": {}}}}, + "id": "str", + "description": "str", + "displayName": "str", + "properties": {"str": "str"}, + "status": "str", + "tags": {"str": "str"}, + }, + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_evaluations_create_agent_evaluation(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = await client.evaluations.create_agent_evaluation( + evaluation={ + "appInsightsConnectionString": "str", + "evaluators": {"str": {"id": "str", "dataMapping": {"str": "str"}, "initParams": {"str": {}}}}, + "runId": "str", + "redactionConfiguration": {"redactScoreProperties": bool}, + "samplingConfiguration": {"maxRequestRate": 0.0, "name": "str", "samplingPercent": 0.0}, + "threadId": "str", + }, + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_indexes_operations.py b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_indexes_operations.py new file mode 100644 index 000000000000..8570e8c44453 --- /dev/null +++ b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_indexes_operations.py @@ -0,0 +1,79 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils import recorded_by_proxy +from testpreparer import AIProjectClientTestBase, AIProjectPreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAIProjectIndexesOperations(AIProjectClientTestBase): + @AIProjectPreparer() + @recorded_by_proxy + def test_indexes_list_versions(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.indexes.list_versions( + name="str", + ) + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy + def test_indexes_list(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.indexes.list() + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy + def test_indexes_get(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.indexes.get( + name="str", + version="str", + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy + def test_indexes_delete(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.indexes.delete( + name="str", + version="str", + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy + def test_indexes_create_or_update(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.indexes.create_or_update( + name="str", + version="str", + pending_upload_request={ + "connectionName": "str", + "indexName": "str", + "name": "str", + "type": "AzureSearch", + "version": "str", + "description": "str", + "id": "str", + "tags": {"str": "str"}, + }, + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_indexes_operations_async.py b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_indexes_operations_async.py new file mode 100644 index 000000000000..27ecb53d9702 --- /dev/null +++ b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_indexes_operations_async.py @@ -0,0 +1,80 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import AIProjectPreparer +from testpreparer_async import AIProjectClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAIProjectIndexesOperationsAsync(AIProjectClientTestBaseAsync): + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_indexes_list_versions(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = client.indexes.list_versions( + name="str", + ) + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_indexes_list(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = client.indexes.list() + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_indexes_get(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = await client.indexes.get( + name="str", + version="str", + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_indexes_delete(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = await client.indexes.delete( + name="str", + version="str", + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_indexes_create_or_update(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = await client.indexes.create_or_update( + name="str", + version="str", + pending_upload_request={ + "connectionName": "str", + "indexName": "str", + "name": "str", + "type": "AzureSearch", + "version": "str", + "description": "str", + "id": "str", + "tags": {"str": "str"}, + }, + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_red_teams_operations.py b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_red_teams_operations.py new file mode 100644 index 000000000000..4611d9ba846f --- /dev/null +++ b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_red_teams_operations.py @@ -0,0 +1,56 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils import recorded_by_proxy +from testpreparer import AIProjectClientTestBase, AIProjectPreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAIProjectRedTeamsOperations(AIProjectClientTestBase): + @AIProjectPreparer() + @recorded_by_proxy + def test_red_teams_get(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.red_teams.get( + name="str", + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy + def test_red_teams_list(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.red_teams.list() + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy + def test_red_teams_create_run(self, aiproject_endpoint): + client = self.create_client(endpoint=aiproject_endpoint) + response = client.red_teams.create_run( + red_team={ + "attackStrategies": ["str"], + "id": "str", + "numTurns": 0, + "riskCategories": ["str"], + "simulationOnly": bool, + "targetConfig": "target_config", + "applicationScenario": "str", + "properties": {"str": "str"}, + "scanName": "str", + "status": "str", + "tags": {"str": "str"}, + }, + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_red_teams_operations_async.py b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_red_teams_operations_async.py new file mode 100644 index 000000000000..c65c7dc2a63a --- /dev/null +++ b/sdk/ai/azure-ai-projects/generated_tests/test_ai_project_red_teams_operations_async.py @@ -0,0 +1,57 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import AIProjectPreparer +from testpreparer_async import AIProjectClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestAIProjectRedTeamsOperationsAsync(AIProjectClientTestBaseAsync): + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_red_teams_get(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = await client.red_teams.get( + name="str", + ) + + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_red_teams_list(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = client.red_teams.list() + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @AIProjectPreparer() + @recorded_by_proxy_async + async def test_red_teams_create_run(self, aiproject_endpoint): + client = self.create_async_client(endpoint=aiproject_endpoint) + response = await client.red_teams.create_run( + red_team={ + "attackStrategies": ["str"], + "id": "str", + "numTurns": 0, + "riskCategories": ["str"], + "simulationOnly": bool, + "targetConfig": "target_config", + "applicationScenario": "str", + "properties": {"str": "str"}, + "scanName": "str", + "status": "str", + "tags": {"str": "str"}, + }, + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/ai/azure-ai-projects/generated_tests/testpreparer.py b/sdk/ai/azure-ai-projects/generated_tests/testpreparer.py new file mode 100644 index 000000000000..69c9aaa6e8d1 --- /dev/null +++ b/sdk/ai/azure-ai-projects/generated_tests/testpreparer.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from azure.ai.projects import AIProjectClient +from devtools_testutils import AzureRecordedTestCase, PowerShellPreparer +import functools + + +class AIProjectClientTestBase(AzureRecordedTestCase): + + def create_client(self, endpoint): + credential = self.get_credential(AIProjectClient) + return self.create_client_from_credential( + AIProjectClient, + credential=credential, + endpoint=endpoint, + ) + + +AIProjectPreparer = functools.partial( + PowerShellPreparer, "aiproject", aiproject_endpoint="https://fake_aiproject_endpoint.com" +) diff --git a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/__init__.py b/sdk/ai/azure-ai-projects/generated_tests/testpreparer_async.py similarity index 51% rename from sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/__init__.py rename to sdk/ai/azure-ai-projects/generated_tests/testpreparer_async.py index a5e9e67bf233..56353f9fdd65 100644 --- a/sdk/ai/azure-ai-projects/azure/ai/projects/telemetry/__init__.py +++ b/sdk/ai/azure-ai-projects/generated_tests/testpreparer_async.py @@ -5,10 +5,16 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from azure.ai.projects.aio import AIProjectClient +from devtools_testutils import AzureRecordedTestCase -from ._trace_function import trace_function -__all__ = [ - "trace_function", -] -__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore +class AIProjectClientTestBaseAsync(AzureRecordedTestCase): + + def create_async_client(self, endpoint): + credential = self.get_credential(AIProjectClient, is_async=True) + return self.create_client_from_credential( + AIProjectClient, + credential=credential, + endpoint=endpoint, + ) diff --git a/sdk/ai/azure-ai-projects/samples/agents/sample_agents_connected_agent.py b/sdk/ai/azure-ai-projects/samples/agents/sample_agents_connected_agent.py index 935539815591..bfe269aaffca 100644 --- a/sdk/ai/azure-ai-projects/samples/agents/sample_agents_connected_agent.py +++ b/sdk/ai/azure-ai-projects/samples/agents/sample_agents_connected_agent.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. diff --git a/sdk/ai/azure-ai-projects/sdk_packaging.toml b/sdk/ai/azure-ai-projects/sdk_packaging.toml new file mode 100644 index 000000000000..e7687fdae93b --- /dev/null +++ b/sdk/ai/azure-ai-projects/sdk_packaging.toml @@ -0,0 +1,2 @@ +[packaging] +auto_update = false \ No newline at end of file diff --git a/sdk/ai/azure-ai-projects/setup.py b/sdk/ai/azure-ai-projects/setup.py index 28b6a92413c5..0e77efb5eebe 100644 --- a/sdk/ai/azure-ai-projects/setup.py +++ b/sdk/ai/azure-ai-projects/setup.py @@ -1,4 +1,3 @@ -# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,7 +5,7 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -# coding: utf-8 + import os import re @@ -14,17 +13,7 @@ PACKAGE_NAME = "azure-ai-projects" -PACKAGE_PPRINT_NAME = "Azure AI Projects" - -PIPY_LONG_DESCRIPTION_BEGIN = "" -PIPY_LONG_DESCRIPTION_END = "" -LINKS_DIVIDER = "" - -GITHUB_URL = f"https://aka.ms/azsdk/azure-ai-projects/python/code" - -# Define the regular expression pattern to match links in the format [section name](#section_header) -pattern = re.compile(r"\[([^\]]+)\]\(#([^\)]+)\)") - +PACKAGE_PPRINT_NAME = "Azure Ai Projects" # a-b-c => a/b/c package_folder_path = PACKAGE_NAME.replace("-", "/") @@ -37,49 +26,27 @@ raise RuntimeError("Cannot find version information") -long_description = "" - -# When you click the links in the Table of Content which has the format of {URL/#section_header}, you are supposed to be redirected to the section header. -# However, this is not supported when the README is rendered in pypi.org. The README doesn't render with id={section_header} in HTML. -# To resolve this broken link, we make the long description to have top of the README content, the Table of Content, and the links at the bottom of the README -# And replace the links in Table of Content to redirect to github.com. -with open("README.md", "r") as f: - readme_content = f.read() - start_index = readme_content.find(PIPY_LONG_DESCRIPTION_BEGIN) + len(PIPY_LONG_DESCRIPTION_BEGIN) - end_index = readme_content.find(PIPY_LONG_DESCRIPTION_END) - long_description = readme_content[start_index:end_index].strip() - long_description = long_description.replace("{{package_name}}", PACKAGE_PPRINT_NAME) - long_description = re.sub(pattern, rf"[\1]({GITHUB_URL})", long_description) - links_index = readme_content.find(LINKS_DIVIDER) - long_description += "\n\n" + readme_content[links_index:].strip() - -with open("CHANGELOG.md", "r") as f: - long_description += "\n\n" + f.read() - setup( name=PACKAGE_NAME, version=version, - description="Microsoft {} Client Library for Python".format(PACKAGE_PPRINT_NAME), - long_description=long_description, + description="Microsoft Corporation {} Client Library for Python".format(PACKAGE_PPRINT_NAME), + long_description=open("README.md", "r").read(), long_description_content_type="text/markdown", license="MIT License", author="Microsoft Corporation", author_email="azpysdkhelp@microsoft.com", - url="https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/ai/azure-ai-projects", - keywords="azure sdk, azure, ai, agents, foundry, inference, chat completion, project, evaluation", + url="https://github.com/Azure/azure-sdk-for-python/tree/main/sdk", + keywords="azure, azure sdk", classifiers=[ "Development Status :: 4 - Beta", "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", - "Programming Language :: Python :: 3.13", "License :: OSI Approved :: MIT License", - "Topic :: Scientific/Engineering :: Artificial Intelligence", ], zip_safe=False, packages=find_packages( @@ -97,10 +64,7 @@ install_requires=[ "isodate>=0.6.1", "azure-core>=1.30.0", - "typing-extensions>=4.12.2", + "typing-extensions>=4.6.0", ], - python_requires=">=3.8", - extras_require={ - "prompts": ["prompty"], - }, + python_requires=">=3.9", ) diff --git a/sdk/ai/azure-ai-projects/tsp-location.yaml b/sdk/ai/azure-ai-projects/tsp-location.yaml index 7aa8fb854ef9..90ee14a41207 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/Azure.AI.Projects -commit: 0c16eaab2ab3fb6379871f77353251bd6f5c643a +commit: 24ce4ac67ab3aa64c19de3fede264310426131ee repo: Azure/azure-rest-api-specs additionalDirectories: