MSBA-272 · Lesson 5 of 12 · 19 min

Adding AI with prompts and AI functions in code

▶ Video coming soon A video version of this lesson is on the way.

Transcript requests have a free-text box labeled "Special instructions". Over the pilot, Maribeth had read hundreds of them. Most said nothing useful, but some mattered a great deal: a request to hold the transcript until final grades were posted, a sealed copy for a licensing body, a second address for a copy to an employer, a note that the student had changed their name. Clerks read every one, and some were missed on busy days. In MSBA-251 Maribeth had learned to build prompts; now she built one called Classify Transcript Instructions that sorted the text into a few categories and pulled out any second address. The question for this session was how code could use it, and when it should.

Two ways to add generative AI to platform logic

Power Platform offers two families of AI building blocks that developers can reach from code and from low-code extensions. Prompts are reusable instructions with typed inputs, built in the prompt builder in Power Apps, Power Automate or Copilot Studio and stored in Dataverse as AI models. They can ground on Dataverse data and return text or JSON. Prebuilt prompts, which Microsoft also calls AI functions, are ready-made operations such as summarizing or classifying text, called by name with no prompt to write.

Prompts and prebuilt prompts, with where Microsoft documents they can be used.
Building blockWhat it doesWhere code and low-code can call it
Custom promptRuns instructions the maker wrote, with typed inputs, optional Dataverse grounding and text or JSON outputPower Automate, canvas apps, Copilot Studio, and code through the Predict message
AISummarizeSummarizes textLow-code plug-ins, Power Apps, Power Automate
AISentimentClassifies the sentiment of textLow-code plug-ins, Power Apps, Power Automate
AIReplyDrafts a reply to a messageLow-code plug-ins, Power Apps, Power Automate
AIClassifyAssigns text to one of a set of categoriesLow-code plug-ins, Power Apps, Power Automate
AIExtractExtracts a named kind of information from textLow-code plug-ins, Power Apps, Power Automate
AITranslateTranslates textLow-code plug-ins only, according to Microsoft's current list

Signe stressed that the details of where each function works change often, and that the table reflected Microsoft's documentation at the time of the session. Before designing around a function, a developer should check the current page.

Billing and capacity

Generative AI calls consume capacity. Since November 1, 2026, AI Builder credits are no longer the currency for these features; prompts and prebuilt prompts draw on Copilot Credits, as MSBA-251 described. Lumenvale's Power Platform administrator, Rupert Ellingsworth, assigned capacity to environments and watched consumption in the admin center. For developers, that had two consequences. Every call costs something, so code should call a prompt only when it needs to, never on every save of a row whatever changed. And a call can fail because capacity has run out, so code must handle that case without breaking the user's work.

Calling a prompt from code: the Predict message

A prompt is stored as a row in the AI Model table, msdyn_aimodel, and code runs it with the Dataverse Predict message. Microsoft documents the message for both the SDK and the Web API. The request names the prompt by an entity reference to its AI model row, passes the prompt's inputs as an entity in a parameter called requestv2, and sets version to 2.0. The response contains a predictionOutput with the generated text and, for prompts that return JSON, a structured output.

Running Classify Transcript Instructions with the Predict message from a plug-in. The prompt ID comes from an environment variable; parameter names follow Microsoft's Predict documentation.
var request = new OrganizationRequest("Predict");
request["Target"] = new EntityReference("msdyn_aimodel", classifyPromptId);
request["version"] = "2.0";

var inputs = new Entity();
inputs["Instructions"] = instructionsText;   // input name as defined in the prompt
request["requestv2"] = inputs;

OrganizationResponse response = service.Execute(request);
var output = (Entity)response.Results["responsev2"];
var prediction = (Entity)output["predictionOutput"];
string json = prediction.GetAttributeValue<string>("text");
local.Trace("Prompt returned {0} characters", json?.Length ?? 0);

Through the Web API, the call is a POST to the Predict action bound to the AI model row. Microsoft documents that the service can answer with 202 Accepted when the result is not ready yet, in which case the response says where to poll and how long to wait before polling. A client must honor the retry interval rather than polling in a tight loop. The SDK call from inside Dataverse returns when the result is available, which is one reason the calling code has to be in the right place, as the next section explains.

The prompt ID was not hard-coded. Prompts are solution components, and the same prompt has the same ID across environments when it is deployed in a solution, but Signe still stored it in an environment variable called lcc_ClassifyInstructionsPromptId so the code made no assumptions and a test environment could point at a test version of the prompt.

Where the call belongs

Wiremu's first instinct was to call the prompt in the transcript fee plug-in's PreOperation step, so the category would be saved with the request. Signe stopped him. A generative AI call takes seconds, sometimes many seconds, and can fail for reasons outside anyone's control. In a synchronous step, the clerk would wait for it on every save, the call would count against the two-minute budget for the whole operation, and a capacity error would roll back the request. The fee was business-critical; the classification was a helpful extra.

Two lanes. The upper lane, marked "avoid", shows a synchronous PreOperation step calling a prompt while the user waits, with a red note that latency and failures block the save. The lower lane, marked "use", shows the save completing, then an asynchronous PostOperation step calling the prompt and writing the category and a review flag back to the request.
Keep generative AI calls out of the user's save.

The design they settled on used an asynchronous PostOperation step on Create and on Update filtered to the special instructions column. The step skipped empty or very short instructions without calling the prompt, called Classify Transcript Instructions otherwise, and wrote the category, an extracted second address if any, and a flag called Needs review to the request. The clerk saw the classification a few seconds after saving, and the Transcript Office app's view of requests needing attention picked it up. If the call failed, the step traced the error, set Needs review to yes so a person would read the text, and did not retry endlessly.

A custom API was the other sensible home. Signe sketched lcc_ClassifyInstructions, an action the Request a Transcript app could call to show the adviser a suggested category while they were still typing. That kept the AI call out of the save as well, because the adviser asked for it explicitly. They agreed to build the asynchronous step first and leave the API as an option.

Handling the response

Classify Transcript Instructions returned JSON with three fields: category, secondAddress and confidence. Wiremu parsed it with a small class that refused anything it did not expect. If the category was not one of the five known values, the code treated the result as unclassified. If the JSON did not parse, the same. A model is not a database, and code that consumes its output has to be defensive in ways it would not need to be with data from Dataverse.

An example of the JSON returned by the prompt. Field names were defined in the prompt's output format.
{
  "category": "HoldForGrades",
  "secondAddress": null,
  "confidence": "high"
}

Microsoft documents specific errors from the Predict message that code should handle. A 403 with an error such as EntitlementNotAvailable means the environment has no capacity for the call. A 500 indicating that the maximum number of concurrent calls has been reached means the code should back off and try later. Wiremu's step handled both by tracing, setting Needs review and returning normally, so the system job succeeded and the request moved on. Signe preferred that to letting the job fail, because a failed job would retry and consume capacity for nothing.

Human review

The classification was advice to a clerk, not a decision. It never changed the request's status, never sent anything to anyone, and never changed the fee. The Transcript Office form showed the suggested category next to the original text with a label saying it was AI-generated, and the clerk confirmed or corrected it. Corrections were stored, which gave Maribeth a growing test set: by the end of the session she had 50 anonymized instructions with their correct categories, and the prompt sorted 46 of them correctly in Wiremu's environment. The four it missed were all ambiguous to a human reader too.

Dr. Philippa Ondaatje-Ruiz reviewed the design because special instructions sometimes contained personal information. Her conditions were that the prompt's instructions told the model not to repeat personal details beyond the extracted address, that the output was stored only on the request it came from, and that no prompt input or output appeared in plug-in traces. Those conditions went into the design document beside the code.

Worked problem

Choosing the AI building block

Three requests came to the developer team in the same week. (1) The Transcript Office app should show a one-paragraph summary of a long email thread attached to a request. (2) A nightly job should classify the day's instructions that were entered before the classifier existed. (3) A canvas app for international students should translate a short fee explanation into the student's language.

Show solution
  1. Request 1 needs a generic summary of text, with no custom instructions: the prebuilt AISummarize function fits, called from the app when the clerk opens the thread, not on every save.
  2. Request 2 needs Maribeth's custom categories: run the existing Classify Transcript Instructions prompt, from a scheduled flow or a background job that processes rows in small batches and stops cleanly when capacity runs short.
  3. Request 3 needs translation. Microsoft's list at the time did not include AITranslate for Power Apps, so the team would either use a prompt that translates, or call the function from a low-code plug-in, and check the current documentation first.

Answer: Prebuilt AISummarize on demand for 1, the custom prompt in batches for 2, and for 3 a translation prompt or a check of current AITranslate support before building.

Designing a prompt for code to call

A prompt that a person reads in a chat window can be loose. A prompt that code calls needs to behave like an interface. Maribeth and Wiremu worked on Classify Transcript Instructions together, and Signe gave them a short list of rules that came from experience. The prompt should have exactly the inputs the code will send, with clear names, because the code refers to them by name. Its output should use the JSON output format, with a fixed set of field names and a closed list of allowed values for any category, written into the instructions. It should say what to return when the input is empty, unclear or unrelated, so the code receives an explicit "Unclear" category rather than an improvised sentence. And its instructions should be stable: every change to wording was tested against the test set before the new version was deployed, because a change that improves one case can quietly break three others.

Grounding was the other design question. A prompt can include Dataverse data as knowledge, for example the list of recipient organizations the registrar sends transcripts to. Maribeth tried adding it so the prompt could recognize a licensing body by name. It helped on a few cases, but it made every call larger and slower, and the organization list was better matched by ordinary code after the prompt had extracted a name. They removed the grounding and let the plug-in do the lookup, which also made the behavior easier to explain to the privacy officer.

Estimating the load before building

Before the design review signed off, Rupert asked how many calls the feature would make. Wiremu worked it out from pilot data rather than guessing. The registrar received about 60 requests a week during the pilot and expected several times that after full rollout in January. About a third of requests had special instructions long enough to classify, and the filtering attribute meant a call happened only when the instructions changed, which was rare after creation. That put the steady load at a few hundred calls a month after rollout, plus a one-time batch for older requests. Rupert compared the figure with the capacity he had assigned to the Registrar environments and agreed, on condition that the batch job ran in small chunks outside office hours and stopped when it saw a capacity error.

Signe pointed out that this estimate was itself part of the design. It went into the design document with the assumptions written out, so that if consumption later looked wrong, the team could see which assumption had failed rather than starting from nothing.

Testing AI features

Wiremu asked how to unit test code that calls a prompt. Signe's answer was to separate the two concerns, as before. The code that builds the request and parses the response is ordinary code, tested with fake responses that include the awkward cases: an unknown category, malformed JSON, a missing field, an empty string. The prompt's quality is tested separately, with Maribeth's test set, whenever the prompt changes. Mixing the two produces tests that fail at random because a model phrased something differently.

Common mistakes

  • MistakeCalling a prompt in a synchronous PreOperation step.

    InsteadCall it from an asynchronous step, a flow or an explicitly invoked custom API.

  • MistakeTrusting prompt output as if it were validated data.

    InsteadParse defensively and treat unexpected values as unclassified.

  • MistakeCalling the prompt on every update of the row.

    InsteadFilter on the column that matters and skip empty input.

  • MistakeLetting an AI result change status or send messages on its own.

    InsteadShow it as a suggestion and let a person confirm.

  • MistakeHard-coding the prompt ID in the plug-in.

    InsteadRead it from an environment variable.

Summary and key terms

  • Prompts are reusable, typed instructions stored as AI models; prebuilt prompts such as AISummarize and AIClassify need no prompt writing.
  • Code runs a prompt with the Predict message, passing inputs in requestv2 with version 2.0 and reading predictionOutput.
  • Generative AI calls are slow and can fail, so they belong in asynchronous steps, flows or explicitly called APIs, not in synchronous saves.
  • Calls consume Copilot Credits; handle capacity and concurrency errors without failing the user's work.
  • Treat output as a suggestion for human review, parse it defensively and keep personal data out of traces.
Prompt
A reusable set of instructions with typed inputs, stored in Dataverse as an AI model.
Prebuilt prompt
A ready-made AI function such as AISummarize, called by name.
Predict message
The Dataverse message that runs an AI model, including a prompt, from code.
Copilot Credits
The capacity unit consumed by prompts and prebuilt prompts.
Structured output
Prompt output in a defined JSON format.

Practice problems

Work each problem on paper first, then reveal the answer to check.

  1. Which Dataverse table stores prompts?

    Show answer

    The AI Model table, msdyn_aimodel.

  2. What should a Web API client do on a 202 response from Predict?

    Show answer

    Poll the location given, after waiting the interval the response specifies.

  3. Why did Lumenvale use an asynchronous step for classification?

    Show answer

    So latency or failure of the AI call could not block or roll back the user's save.

Lesson quiz · 5 questions

Score 60% or more to complete this lesson.

Take the quiz