azure document intelligence API PRebuilt-layout with KeyValuePairs feature (C# SDK)

Diallo, Mouhamadou S 5 Reputation points
2024-01-20T19:05:22.5633333+00:00

The following code is throwing an Invalid argument error on KeyValuePairs while keyValuePairs feature exists and is valid. Can you help explain?

AnalyzeDocumentOperation operation = await client.AnalyzeDocumentFromUriAsync(WaitUntil.Completed, "prebuilt-layout", fileUri, new AnalyzeDocumentOptions() { Features = { DocumentAnalysisFeature.KeyValuePairs } });

Error message: Azure.RequestFailedException: 'Invalid argument. Status: 400 (Bad Request) ErrorCode: InvalidArgument Content: {"error":{"code":"InvalidArgument","message":"Invalid argument.","innererror":{"code":"InvalidParameter","message":"The parameter keyValuePairs is invalid: The feature is invalid or not supported."}}} I tried all below feature and they work, but keyvaluepairs feature don't work.

AnalyzeDocumentOptions options = new AnalyzeDocumentOptions();
options.Features.Add(DocumentAnalysisFeature.Barcodes);
options.Features.Add(DocumentAnalysisFeature.Formulas);
options.Features.Add(DocumentAnalysisFeature.Languages);
options.Features.Add(DocumentAnalysisFeature.FontStyling);
options.Features.Add(DocumentAnalysisFeature.OcrHighResolution);
Azure AI Document Intelligence
Azure AI Document Intelligence
An Azure service that turns documents into usable data. Previously known as Azure Form Recognizer.
2,100 questions
0 comments No comments
{count} votes

9 answers

Sort by: Most helpful
  1. Konstantinos Passadis 19,586 Reputation points MVP
    2024-01-20T19:31:37.68+00:00

    Hello @Diallo, Mouhamadou S !

    Welcome to Microsoft QnA!

    The error you're encountering in your client in C# seems to be related to the specific feature DocumentAnalysisFeature.KeyValuePairs not being supported / recognized.

    Try

    API Version:

    **2023-07-31** 
    ```Reference : [https://learn.microsoft.com/en-us/azure/ai-services/document-intelligence/sdk-overview-v3-0?view=doc-intel-3.0.0&tabs=csharp](https://learn.microsoft.com/en-us/azure/ai-services/document-intelligence/sdk-overview-v3-0?view=doc-intel-3.0.0&tabs=csharp)
    
    [https://learn.microsoft.com/en-us/rest/api/aiservices/document-models/analyze-document?view=rest-aiservices-2023-07-31&preserve-view=true&tabs=HTTP](https://learn.microsoft.com/en-us/rest/api/aiservices/document-models/analyze-document?view=rest-aiservices-2023-07-31&preserve-view=true&tabs=HTTP)
    
    ---
    
    I hope this helps!
    
    Kindly mark the answer as __Accepted__ and __Upvote__ in case it helped!
    Regards
    
    1 person found this answer helpful.

  2. Konstantinos Passadis 19,586 Reputation points MVP
    2024-01-20T20:23:23.9933333+00:00

    Hello @Diallo, Mouhamadou S !

    Thank you for your input !

    Make sure you have the latest Packages first

    dotnet add package Azure.AI.FormRecognizer
    

    Sample code ( This is a sample , please adjust it as per requirements ! )

    using Azure.AI.FormRecognizer.DocumentAnalysis;
    using Azure.Identity;
    
    var endpoint = "<your-form-recognizer-endpoint>";
    var credential = new DefaultAzureCredential();
    
    var client = new DocumentAnalysisClient(new Uri(endpoint), credential);
    
    var fileUri = new Uri("<your-document-uri>");
    
    AnalyzeDocumentOptions options = new AnalyzeDocumentOptions()
    {
        Features = { DocumentAnalysisFeature.KeyValuePairs }
    };
    
    AnalyzeDocumentOperation operation = await client.AnalyzeDocumentFromUriAsync(
        "prebuilt-layout", fileUri, options);
    
    await operation.WaitForCompletionAsync();
    
    AnalyzeResult result = operation.Value;
    
    // Process the results
    foreach (var pair in result.KeyValuePairs)
    {
        Console.WriteLine($"Key: {pair.Key.Content}, Value: {pair.Value.Content}");
    }
    
    
    

    KEY POINTS

    I have seen deviations from the Code produced from Studio to the actual supported , i think because the Packages are updated more often as well as minor changes on approach

    Using DefaultAzureCredential for Auth , make sure you get Authenticated , i prefer Managed Identity whenever possible!

    Kindly send us your feedback !


    I hope this helps!

    The answer or portions of it may have been assisted by AI Source: ChatGPT Subscription

    Kindly mark the answer as Accepted and Upvote in case it helped! Regards

    1 person found this answer helpful.
    0 comments No comments

  3. Diallo, Mouhamadou S 5 Reputation points
    2024-01-21T13:25:43.4733333+00:00

    Hi Konstantinos Passadis, Thanks for your reply! I'm using my local development machine and was logged in to the Visual Studio with the incorrect Azure account. I'm logged in now with the account that has access to the Form Recognizer resource. Now the Tenant error is gone, but I'm getting now the error below at the following code line.
    AnalyzeDocumentOperation operation = await client.AnalyzeDocumentAsync(WaitUntil.Completed, "prebuilt-layout", fileStream, optionkv);

    Azure.RequestFailedException: 'Principal does not have access to API/Operation. Status: 401 (PermissionDenied) ErrorCode: PermissionDenied

    1 person found this answer helpful.

  4. Diallo, Mouhamadou S 5 Reputation points
    2024-01-21T01:46:38.8866667+00:00

    Hi Konstantinos Passadis,
    I've changed my code to use DefaultAzureCredential for Auth, but now I'm gettting error below.

    Azure.RequestFailedException: 'Token tenant does not match resource tenant. Status: 400 (BadRequest) ErrorCode: Tenant provided in token does not match resource token My code is below.

    var endpoint = "My_endpoint";
    var credential = new DefaultAzureCredential();  //new AzureKeyCredential(key);
    var client = new DocumentAnalysisClient(new Uri(endpoint), credential);
    
    AnalyzeDocumentOptions optionkv = new AnalyzeDocumentOptions()
    {
        Features = { DocumentAnalysisFeature.KeyValuePairs }
    };
    
    AnalyzeDocumentOperation operation = await client.AnalyzeDocumentAsync(WaitUntil.Completed, "prebuilt-document", fileStream, optionkv);
    await operation.WaitForCompletionAsync();
    
    AnalyzeResult result = operation.Value;
    foreach (var pair in result.KeyValuePairs) 
    {     
          Console.WriteLine($"Key: {pair.Key.Content}, Value: {pair.Value.Content}"); 
    }
    
    0 comments No comments

  5. Konstantinos Passadis 19,586 Reputation points MVP
    2024-01-21T03:19:22.65+00:00

    Hello @Diallo, Mouhamadou S !

    The error message you're seeing typically indicates a mismatch between the Azure Active Directory (AAD) tenant of your service principal (or user account) and the tenant that your Azure resource (in this case, the Form Recognizer resource) is associated with.

    The DefaultAzureCredential class attempts to acquire a token using a number of methods in a specific order, which includes checking environment variables, managed identity, and the shared token cache (Visual Studio, VS Code, or Azure CLI logged in credentials). If you're using a development environment or if your Azure resources are in different directories (tenants), you might encounter this error. Here are some steps to troubleshoot and resolve this issue: Specify Tenant ID: If you know the tenant ID of your Azure resource, you can specify it when creating the DefaultAzureCredential:

    csharp
    
    1. var options = new DefaultAzureCredentialOptions { SharedTokenCacheTenantId = "<your-resource-tenant-id>", VisualStudioTenantId = "<your-resource-tenant-id>", VisualStudioCodeTenantId = "<your-resource-tenant-id>", AzureCliTenantId = "<your-resource-tenant-id>" }; var credential = new DefaultAzureCredential(options); Replace "<your-resource-tenant-id>" with the tenant ID where your Form Recognizer resource is located.
    2. Environment Variables: You can also set the AZURE_TENANT_ID environment variable to the correct tenant ID before running your application.
    3. Check Subscription: Ensure that the Form Recognizer resource is in the same Azure subscription as the identity you are using with DefaultAzureCredential. If they are in different subscriptions, they might belong to different AAD tenants.
    4. Use Specific Credentials: If DefaultAzureCredential isn't working for your scenario, consider using more specific credential types that allow you to explicitly specify the tenant ID, such as ClientSecretCredential or UsernamePasswordCredential.
    5. Service Principal Permissions: If you are using a service principal, make sure that it has the correct permissions on the Form Recognizer resource and that it's associated with the correct tenant.
    6. Managed Identity: If your code is running within an Azure service that supports Managed Identities (like Azure VMs, Azure Functions, etc.), make sure that the Managed Identity is properly configured and has access to the Form Recognizer resource.
    7. Development Environment: If you are running the code on your local development machine, ensure that you are logged in to the Azure CLI or Visual Studio with the correct Azure account and that the account has access to the Form Recognizer resource.

    --

    I hope this helps!

    The answer or portions of it may have been assisted by AI Source: ChatGPT Subscription

    Kindly mark the answer as Accepted and Upvotein case it helped!

    Regards

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.