Edit

Share via


Code interpreter for developers

As described in Use code interpreter to generate and execute Python code, code interpreter provides a way for agents to execute python code for data analysis, Word, Excel, PowerPoint, and PDF processing, and visualizations. Refer to that article to understand:

  • Licensing requirements and supported regions
  • General code interpreter capabilities
  • How to enable code interpreter for a prompt
  • How to use code interpreter capabilities with a prompt

This article describes how developers can use the Dataverse Predict message to pass parameters to code interpreter enabled prompts and process the responses.

Note

A common scenario for code interpreter enabled prompts is to generate UI experiences for model-driven applications using Power Apps Component (PCF) components. Refer to the Code interpreter PCF component sample for an example.

Enable code interpreter for the environment

Code interpreter must be enabled for each environment before you can use it. The default setting is Off. Learn how to enable code interpreter using the Power Platform Admin center

Developers can use the Power Platform Environment Management Settings APIs to read or set the CopilotStudio_CodeInterpreter boolean property to enable code interpreter for an environment.

Code interpreter enabled prompts

Every prompt created using Microsoft Copilot Studio or AI Builder creates a new record in the Dataverse AI Model (msdyn_AIModel) table. You need the ID of the row when you invoke the Predict message.

You can't create a prompt by creating a new row in the msdyn_AIModel. Prompts are created updated using the AIModelPublish message. This public message is for internal use only. You must use the UI to create code interpreter enabled prompts. You must also make sure that each prompt is enabled for code interpreter. Enabling a prompt is slightly different depending on whether you edit the prompt in Power Apps or Copilot Studio. See these instructions:

You can query the msdyn_AIModel table using the msdyn_Name column value to identify code interpreter enabled prompts by name. The msdyn_AIModel doesn't have a property you can use to filter only those prompts that are code interpreter enabled.

Retrieve AI Model data

Use queries like the following to retrieve data from the msdyn_AIModel table using the name of the model as a filter.

/// <summary>
/// Retrieves AI models from Dataverse that match the specified model name pattern.
/// </summary>
/// <param name="service">The IOrganizationService instance used to connect to Dataverse</param>
/// <param name="modelName">The model name prefix to search for (uses BeginsWith matching)</param>
/// <remarks>
/// This method queries the msdyn_aimodel table using a BeginsWith condition, which means it will find
/// models whose names start with the specified modelName string. The search is case-insensitive.
/// If no matching models are found, a message is displayed to the console.
/// </remarks>
/// <example>
/// <code>
/// RetrieveAIModelsExample(service, "GPT");
/// // This will find all AI models whose names start with "GPT"
/// </code>
/// </example>
static void RetrieveAIModelsExample(IOrganizationService service, string modelName)
{
    var query = new QueryExpression("msdyn_aimodel")
    {
        ColumnSet = new ColumnSet("msdyn_name", "msdyn_aimodelid"),
        Criteria = new FilterExpression(LogicalOperator.And)
        {
            Conditions = {
                new ConditionExpression(
                    attributeName:"msdyn_name",
                    conditionOperator: ConditionOperator.BeginsWith,
                    value: modelName
                 )
            }
        }
    };

    var results = service.RetrieveMultiple(query);

    if (results.Entities.Any())
    {
        foreach (var entity in results.Entities)
        {
            Console.WriteLine($"Model Name: {entity["msdyn_name"]}, ID: {entity["msdyn_aimodelid"]}");
        }
    }
    else
    {
        Console.WriteLine($"No model with a name starting with '{modelName}' was found.");
    }
}

Learn how to query data using QueryExpression

Predict message

The Predict message is available in both the Dataverse SDK for .NET and Web API.

Sending the request

Regardless of how you send the request, the Predict message requires three parameters:

  • The ID of the msdyn_AIModel record. How you set this value depends on whether you use the SDK for .NET or Web API.
  • The data that contains the parameters that the prompt is configured to accept. This is passed as a parameter named requestv2. Learn more about the requestv2 parameter
  • The version parameter. The value is always "2.0".

requestv2 parameter

This parameter is configured as an open type. Learn more about how to use open types in general

An open type is a dictionary that contains keys and values. The values can also be dictionaries, so it's possible to send complex, hierarchical data using an open type parameter.

With the SDK for .NET, use the Entity class and set the Attributes collection with the values. The key difference in this scenario is that the Entity instance doesn't have a LogicalName set, so it doesn't refer to a specific Dataverse table.

The following PredictActionExample sample method uses the OrganizationRequest class to use the Predict message as described in Use messages with the SDK for .NET. Alternatively, you can generate a pair of typed PredictRequest and PredictResponse classes. Learn how to generate early-bound classes for the SDK for .NET

This example also shows how to set the Target parameter with an EntityReference that refers to the msdyn_AIModel record using the ID.

static PredictActionExample (IOrganizationService service, Guid yourAiModelId)
{
 // Create the nested 'patient' entity
 var patientEntity = new Entity
 {
     Attributes =
     {
         { "firstname", "John" },
         { "lastname", "Smith" }
     }
 };
 
 // Create the main 'requestv2' entity
 var requestV2Entity = new Entity
 {
     Attributes =
     {
         { "pai_sex", 1 },
         { "pai_age", 10 },
         { "patient", patientEntity }
     }
 };
 
 // Create the Predict action request
 var predictRequest = new OrganizationRequest("Predict")
 {
     Parameters = new ParameterCollection
     {
         { "version", "2.0" },
         { "requestv2", requestV2Entity },
         { "Target", new EntityReference("msdyn_aimodel", new Guid(yourAiModelId)) }
     }
 };
 
 // Execute the request
 var response = service.Execute(predictRequest);
 
 Console.WriteLine("Prediction Result:");
 Console.WriteLine(response.Results);
}

Processing the response

The PredictResponse complex type contains the response from the Predict message in web API. The SDK for .NET has similar response properties. Refer to the previous Web API response example for details.

Property Type Description
overrideHttpStatusCode String In case the prediction isn't completed, 202 indicates that a polling is necessary, otherwise null.
overrideLocation String Null except when overrideHttpStatusCode isn't null. The location of the polling. Sent a GET request to this location to poll for the result.
overrideRetryAfter String Null except when overrideHttpStatusCode isn't null. Suggestion on when to try polling.
response String This property is obsolete since the introduction of the responsev2 property and should always be null.
responsev2 Entity/expando See PredictResponse responsev2 properties

PredictResponse responsev2 properties

The responsev2 property has two properties:

  • operationStatus: A string value showing whether the operation succeeded. Expected value is Success.

  • predictionOutput: A dictionary with the following properties:

    Property Type Description
    text string Primary generated content. Content depends on the type of value returned by the prompt.
    mimetype string Text MIME type.
    textMimeType string Duplicate/confirming MIME type
    finishReason string The reason the reasoning finished. This is usually stop.
    code string Python Source code or placeholder describing executed code.
    signature string a Base64‑encoded, versioned metadata and integrity token
    logs string Python code execution log output (if provided).
    codeThinking object Empty/internal placeholder object.
    files array of objects Generated file artifacts with file_name, content_type, and base64_content properties.
    structuredOutput object Canonical form of main output with mimetype and text properties.
    artifacts object Map of artifact identifiers to metadata & base64 content. This object contains properties specific to the output and these properties are objects that have the following properties: artifactName, mimeType, and base64Content

Troubleshooting

The following are some errors you might encounter while using the Predict action with code interpreter enabled prompts.

Insufficient capacity

When you don't have any remaining AI Builder capacity, you'll get this 403 Forbidden EntitlementNotAvailable error:

{ 
   "error": { 
       "code": "0x80048d06", 
       "message": "{\"operationStatus\":\"Error\",\"error\":{\"type\":\"Error\",\"code\":\"EntitlementNotAvailable\",\"innerErrors\":[{\"scope\":\"Generic\",\"target\":null,\"code\":\"NoCapacity\",\"type\":\"Error\",\"message\":\"No capacity was found.\"}]},\"predictionId\":null}" 
   } 
}

A PCF control that encounters this error displays this message: Access denied. You don't have permission to use this model.

The resolution to this error is to purchase more AI Builder capacity. Learn more about how to get entitlement to AI Builder credits

Max concurrency calls reached

When you're sending too many requests concurrently per environment or tenant, you'll get this 500 Internal Server Error MaxConcurrentPlexCallsReachedException error:

{ 
   "error": { 
       "code": "0x80048d0a", 
       "message": "{\"operationStatus\":\"Error\",\"error\":{\"type\":\"Error\",\"code\":\"Unknown\",\"message\":\"Unhandled exception: Microsoft.PowerAI.MiddleEarth.HttpService.CodeInterpreter.Exceptions.MaxConcurrentPlexCallsReachedException\"},\"predictionId\":null}" 
   } 
}

A PCF control that encounters this error displays this message: Server error. Please try again later or contact administrator.

The resolution of this error is to send fewer requests. Wait a short time and try again. There's no RetryAfter response header to recommend how long you should wait.

More information

Code interpreter PCF component sample