web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

Community site session details

Community site session details

Session Id :
Power Platform Community / Forums / Copilot Studio / Error when replacing p...
Copilot Studio
Answered

Error when replacing placeholders in Word document using Custom Prompt in Power Automate

(3) ShareShare
ReportReport
Posted on by 12

Problem Description:

I’m using the Custom Prompt feature in Power Automate to generate content via AI and insert the results into a Word template (.docx) that contains placeholders in the format {{FieldName}}.

Flow steps:

  1. AI action (Custom Prompt) applies a prompt with an attached document and generates content.
  2. The next action attempts to build a Word document by replacing the {{...}} placeholders with the AI-generated content.
  3. The Word template is stored locally and contains placeholders such as {{Verificacao}}, {{Seletividade}}, etc.
 
As soon as I place the template .docx file, and perform the tests, it works!! as shown in the image below, however when I try to save the prompt to use in my flow, the error below occurs.
 
 
 

Error Message:

{error: {code: "0x80048d0f",…}}
code: "0x80048d0f"
message: {"operationStatus":"Error","error":{"type":"Error","code":"DependencyFailure","message":"An error occurred while replacing output document placeholders.","properties":{"BackendErrorCode":"InternalServerError","DependencyHttpStatusCode":"500"}}}

Reproduction Scenario:

  • Word template with placeholders:
    {{InfoMaterial}}, {{Verificacao}}, {{Seletividade}}, {{Linearidade}}, {{Precisao}}, {{Exatidao}}, {{LimiteDeteccao}}, {{LimiteQuantificacao}}, {{Robustez}}, {{NaoConformidades}}, {{Classificacao}}, {{Corretivas}}.
  • When I run the action, it fails with status 500 and the error above.

What I’ve Checked/Tested:

  • Confirmed that placeholders exist in the document and names are case-sensitive.
  • Tested with simple placeholders (no accents, no spaces).
  • Document is clean (no Track Changes, no comments).
  • Placeholders are in a single run (not split by formatting).

Questions:

  • Is this behavior expected?
  • Does the action fail completely if any placeholder is missing from the JSON?
  • Is there an official way to define default values (fallback) for missing placeholders?
  • Is there documentation on limitations for the {{...}} replacement mechanism (e.g., supported characters, optional placeholders, null handling)?

Impact:

This error prevents document generation when the model does not return all fields (e.g., optional fields). I need to know:

  • Do I always need to send all keys (even empty)?
  • Or is there a configuration to ignore unfilled placeholders?

Attachments:

  • Word template (.docx) with placeholders.
  • Example Prompt.

 

  • Recommended tags (e.g., Power Automate, AI Builder, Word Template, Custom Prompt)
I have the same question (5)
  • Verified answer
    Jerry-IN Profile Picture
    295 on at
     
    Greetings!
     
    It looks like you're encountering a common but tricky issue when using a custom AI prompt in Power Automate to populate a Word template. The error occurs because the "Populate a Microsoft Word template" action requires a value for every placeholder field you've defined in the template. If your AI model doesn't return a value for an optional field (like {{NaoConformidades}}), the action fails because it receives a null or missing input for that field.
     
    The key to solving this is to handle the potentially null values before they get to the Word connector. You can do this using the coalesce() expression in Power Automate. This function checks if a value is null and, if it is, provides a default value you specify (like an empty string).
     
    Here’s how you can apply this to your flow:
     
    1. Parse the AI Output: First, ensure you are parsing the JSON output from your "Create text with GPT on Azure OpenAI Service" action using a "Parse JSON" step. This will make it easier to access each field.
    2. Use coalesce() in the Word Action: In your "Populate a Microsoft Word template" action, instead of directly mapping the dynamic content from the AI output, you will use an expression for each field. For a field like Verificacao, you would use :coalesce(outputs('Parse_JSON')?['body']?['Verificacao'], '')
     
    This expression does the following:
    • outputs('Parse_JSON')?['body']?['Verificacao']: Attempts to get the value of the Verificacao field from the parsed AI output.
    • coalesce(..., ''): If the Verificacao field is null or doesn't exist, it will return an empty string ('') instead.
    You will need to apply this coalesce() expression for every placeholder in your Word template action, including {{Seletividade}}, {{Linearidade}}, and all the others. This ensures that even if the AI model omits an optional field, the Word connector receives a valid (empty) string instead of a null value, preventing the error and allowing your flow to complete successfully.
     
    By implementing this, your flow will become robust enough to handle cases where the AI-generated content is missing optional fields.
     
    I hope this solution gets your document generation process running smoothly!
     
    Best regards,
    Jerald Felix
  • ME-08091808-0 Profile Picture
    12 on at
    Hello @Jerry-IN
    Thank you for your response.
    I’m not using the "Populate a Microsoft Word template" action or JSON output.
    In my case, I’m using the "Run a Prompt" action, which requires a prompt and a .docx template file.

    If I run a test without saving the flow, it works perfectly!
    However, once I save the flow and try to run it again, it fails and shows a message asking to "try again later."

    Eventually, it throws an error stating that it was unable to replace the output document placeholders.
    I’m currently using a different action in Power Automate.
    I’m leveraging the AI Capabilities > Run a Prompt feature:
     
     
    This Model
     
    This allows me to define a custom prompt and configure how the output should be returned:
     
     
     
    In my case, I’m selecting the "Document" output type, which requires a Word document template. As shown below, I populate the template using placeholders like {{...}}, which are correctly recognized:
     
     
    Within the prompt itself, I specify exactly where each response should be inserted. For example:
    “Answer the questions above, including the question (skipping one line between each), the answer, parameter classification, and corrective actions in a single text block at: {{Verificacao}}”
    Here’s the issue I’m encountering:
    If I create the action from scratch, define the prompt, upload the document template, and run a test without saving the flow, everything works perfectly. The output is generated as expected:
    However, once I save the flow and try to run it again, I receive the following error:
     

    Mensagem de erro:

    {error: {code: "0x80048d0f",…}}
    code: "0x80048d0f"
    message: {"operationStatus":"Error","error":{"type":"Error","code":"DependencyFailure","message":"An error occurred while replacing output document placeholders.","properties":{"BackendErrorCode":"InternalServerError","DependencyHttpStatusCode":"500"}}}
    My question is: What changes after saving the flow that could be causing this error? Is there any specific requirement that my document template might not be fulfilling?
    Any guidance or documentation you can provide would be greatly appreciated.
    Best regards,
    Marcos Eduardo Soares Santana
     
     
  • AA-21091718-0 Profile Picture
    2 on at
    Hello ,
    Did you find any solution? I’m facing the same issue.
  • KM-12111835-0 Profile Picture
    2 on at
    Unfortunately, @Jerry-IN didn't answer the exact problem people are struggling with.
    I'm having the same problem.
     
    I perform these steps all within a single session testing a custom AI prompt:
    - I create a prompt to extract data from a text input.
    - I output the AI response to text in the test window to confirm all variables in my template are identified
    - I upload my document template and run again to output to the document and SUCCESS!!
    - I immediately try to run the test a second time, and receive a FAILURE to replace document placeholders
    - I delete the document template and upload it again -- and success.
     
    In my testing, only the VERY FIRST attempt to run the prompt after uploading the template works. All subsequent attempts fail.
     
    unfortunately, power platform seems very immature. Sometimes my prompt saves -- sometimes it doesn't. Sometimes it exports to my document template, sometimes it doesn't, and I can't find any logs or useful troubleshooting info.
     
     
  • SK-05122056-0 Profile Picture
    2 on at
    I face the exact same issue and it is disappointing as this scenario is the reason why I considered using AI Builder and Power Automate.

    I will not explain my steps in detail as they are identical to what the author of the original post wrote. Test works the first time, then fails with "An error occurred while replacing output document placeholders.", and whenever I run it from Power Automate using "Run a prompt" action of AI Builder I get "Bad Gateway" instantly on the first run attempt and then it hangs indefinitely on the second automatic attempt is launches. Frustrating to say the least.
  • Suggested answer
    ME-08091808-0 Profile Picture
    12 on at
    Em resposta à minha solicitação, consegui resolver o problema de uma maneira mais fácil, utilizando a sugestão do meu colega @Jerry-IN.
    Depois de ler e entender melhor, percebi que era a melhor solução para o meu problema.
     
    ===
     
    Veja como você pode aplicar isso ao seu fluxo de trabalho:
     
    1. Analise a saída da IA: Primeiro, certifique-se de analisar a saída JSON da sua ação "Criar texto com GPT no serviço Azure OpenAI" usando uma etapa "Analisar JSON". Isso facilitará o acesso a cada campo.
    2. Use a função coalesce() na ação do Word: Na sua ação "Preencher um modelo do Microsoft Word", em vez de mapear diretamente o conteúdo dinâmico da saída da IA, você usará uma expressão para cada campo. Para um campo como Verificação, você usaria: :coalesce(outputs('Parse_JSON')?['body']?['Verificação'], '')
     
    Essa expressão faz o seguinte:
    • outputs('Parse_JSON')?['body']?['Verificacao']: Tenta obter o valor do campo Verificacao da saída de IA analisada.
    • coalesce(..., ''): Se o campo Verificacao for nulo ou não existir, retornará uma string vazia ('').
    Você precisará aplicar essa expressão coalesce() para cada marcador de posição na sua ação de modelo do Word, incluindo {{Seletividade}}, {{Linearidade}} e todos os outros. Isso garante que, mesmo que o modelo de IA omita um campo opcional, o conector do Word receba uma string válida (vazia) em vez de um valor nulo, evitando o erro e permitindo que seu fluxo seja concluído com sucesso.
     
    A ação "Preencher um modelo do Microsoft Word" com coalesce() resolveu meu problema.
     
    Code View.
     
    {
      "type": "OpenApiConnection",
      "inputs": {
        "parameters": {
          "source": "sites/bionovis.sharepoint.com,21f92a2d-2741-4303-b46e-0236e8a7ae7f,65347ae8-d52d-43b5-8f35-a26082204eb3",
          "drive": "b!LSr5IUEnA0O0bgI26Keuf-h6NGUt1bVDjzWiYIIgTrO5C63uQXjYRZMaqRQjC1y_",
          "file": "/IA_CQ/ENG_Modelo_procedimento_GAP.docx",
          "dynamicFileSchema/333882974": "@coalesce(outputs('Analisar_JSON')?['body']?['produto_tipo'], '')",
          "dynamicFileSchema/334627280": "@coalesce(outputs('Analisar_JSON')?['body']?['referencia_documento'], '')",
          "dynamicFileSchema/590676100": "@coalesce(outputs('Analisar_JSON')?['body']?['referencia_documento'], '')",
          "dynamicFileSchema/701760397": "@coalesce(outputs('Analisar_JSON')?['body']?['produto_nome'], '')",
          "dynamicFileSchema/856927616": "@coalesce(outputs('Analisar_JSON')?['body']?['referencia_documento'], '')",
          "dynamicFileSchema/1004424263": "@coalesce(outputs('Analisar_JSON')?['body']?['tipo_ensaio'], '')",
          "dynamicFileSchema/1185403305": "@coalesce(outputs('Analisar_JSON')?['body']?['referencia_documento'], '')",
          "dynamicFileSchema/1296799855": "@coalesce(outputs('Analisar_JSON')?['body']?['referencia_documento'], '')",
          "dynamicFileSchema/1337351402": "@coalesce(outputs('Analisar_JSON')?['body']?['doc_numero'], '')",
          "dynamicFileSchema/1340661576": "@coalesce(outputs('Analisar_JSON')?['body']?['referencia_documento'], '')",
          "dynamicFileSchema/1759313155": "@coalesce(outputs('Analisar_JSON')?['body']?['from_documento'], '')",
          "dynamicFileSchema/1903163204": "@coalesce(outputs('Analisar_JSON')?['body']?['referencia_documento'], '')",
          "dynamicFileSchema/1935549777": "@coalesce(outputs('Analisar_JSON')?['body']?['referencia_documento'], '')",
          "dynamicFileSchema/2035710877": "@coalesce(outputs('Analisar_JSON')?['body']?['from_documento'], '')",
          "dynamicFileSchema/-1358345278": "@coalesce(outputs('Analisar_JSON')?['body']?['from_documento'], '')",
          "dynamicFileSchema/-1748101529": "@coalesce(outputs('Analisar_JSON')?['body']?['referencia_documento'], '')",
          "dynamicFileSchema/-1853942667": "@coalesce(outputs('Analisar_JSON')?['body']?['produto_tipo'], '')",
          "dynamicFileSchema/-924801060": "@coalesce(outputs('Analisar_JSON')?['body']?['from_documento'], '')",
          "dynamicFileSchema/-1238007674": "@coalesce(outputs('Analisar_JSON')?['body']?['doc_versao'], '')",
          "dynamicFileSchema/-57871705": "@coalesce(outputs('Analisar_JSON')?['body']?['doc_titulo'], '')",
          "dynamicFileSchema/-1595700484": "@coalesce(outputs('Analisar_JSON')?['body']?['produto_nome'], '')",
          "dynamicFileSchema/-963105415": "@body('Analisar_JSON')?['materiais']?['equipment']",
          "dynamicFileSchema/-1139793489": "@body('Analisar_JSON')?['materiais']?['rawMaterials']",
          "dynamicFileSchema/-457491746": "@coalesce(outputs('Analisar_JSON')?['body']?['tipo_ensaio'], '')",
          "dynamicFileSchema/-509834408": "@coalesce(outputs('Analisar_JSON')?['body']?['produto_tipo'], '')"
        },
        "host": {
          "apiId": "/providers/Microsoft.PowerApps/apis/shared_wordonlinebusiness",
          "connection": "shared_wordonlinebusiness",
          "operationId": "CreateFileItem"
        }
      },
      "metadata": {
        "016FB6PRN43SFZMDHVQZB3PR6HRSXX4PMH": "/IA_CQ/ENG_Modelo_relatorio_GAP.docx"
      }
    }

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Forum hierarchy changes are complete!

In our never-ending quest to improve we are simplifying the forum hierarchy…

Ajay Kumar Gannamaneni – Community Spotlight

We are honored to recognize Ajay Kumar Gannamaneni as our Community Spotlight for December…

Leaderboard > Copilot Studio

#1
Michael E. Gernaey Profile Picture

Michael E. Gernaey 250 Super User 2025 Season 2

#2
Romain The Low-Code Bearded Bear Profile Picture

Romain The Low-Code... 197 Super User 2025 Season 2

#3
S-Venkadesh Profile Picture

S-Venkadesh 103 Moderator

Last 30 days Overall leaderboard