microsoft / microsoft/simplechat
Populate DOCX and fillable PDF templates from agent or workflow analysis
- Dominant language
- Python
- Stars
- 152
- Forks
- 116
- Avg merge
- 7h 7m
- Merged PRs (30d)
- 122
Description
## Summary
Enable an authorized agent or workflow to populate a user-supplied document template with completed analysis and return the filled document directly as a secure downloadable chat artifact.
The input template must remain authoritative for layout, section order, branding, tables, headers/footers, and field placement. The model should not rewrite or approximate the binary document. It should produce schema-bound field values; a deterministic server-side renderer should validate those values and fill a copy of the template.
Initial format targets:
- Word `.docx` templates with an explicit, documented named-field contract.
- Fillable PDF templates that use named AcroForm fields.
## User Value
Teams often need analysis reports delivered in an existing organizational, regulatory, legal, or customer template. Returning only prose forces users to copy content manually, risks omissions and formatting drift, and prevents a workflow from producing the actual required deliverable.
A completed file in the original template format makes the agent/workflow output immediately usable while preserving the template as the source of truth.
## Proposed Behavior
1. The user uploads or selects an authorized DOCX or fillable PDF template for an analysis request.
2. SimpleChat inventories the supported named fields and creates a bounded field schema containing names, types, required state, length or choice constraints, and template revision identity.
3. The analysis agent, action, or orchestration finalizer returns structured values against that schema, with explicit missing or unresolved fields and evidence lineage where available.
4. SimpleChat rejects unknown fields and validates required fields, types, choices, and size constraints before generation. Missing or unsupported fields produce a clear review state rather than a silently incomplete document.
5. A server-side renderer fills a copy of the original template without mutating the source template or rebuilding its visual structure from extracted text.
6. The completed file appears directly in the current chat through the existing generated-analysis artifact download flow. Existing workspace-promotion behavior can be reused when the user wants to retain the output as a workspace document.
7. When invoked through governed orchestration, artifact generation follows the applicable approval, cancellation, retry, and evidence policies.
## Required Design And Implementation Scope
### Template contract
- Define and document the supported Word authoring contract. Recommended first option is named plain-text content controls; explicit placeholder tags may be supported if they can be filled reliably across paragraphs, tables, headers, footers, and split Word runs.
- Support named PDF AcroForm text, multiline text, checkbox, radio, and choice fields where the installed PDF library can preserve valid appearances.
- Decide whether completed PDFs remain editable or are flattened, and validate the choice across supported viewers.
- Preserve unaffected template content and formatting.
- Bind generation to the exact authorized template revision used to build the field schema.
- Treat repeating sections, dynamic page insertion, conditional layout, images/signatures, calculations, and nested structures as separately designed capabilities rather than letting the model improvise them.
### Structured output and validation
- Introduce a versioned template-population contract containing template/revision identity, field schema, field values, unresolved fields, and validation results.
- Use exact server-discovered field identifiers. Do not trust model-authored blob paths, scope IDs, user IDs, or invented field names.
- Support deterministic normalization for common value types such as text, multiline text, number, date, boolean, and enumerated choice.
- Detect missing required values, unknown fields, incompatible types, invalid choices, field-length overflow, malformed templates, and unsupported constructs before publishing an artifact.
- Preserve evidence references from the analysis ledger where practical without embedding unsupported claims into the report.
### Agent, action, and orchestration integration
- Add a narrowly scoped template-population operation to the existing `SimpleChatPlugin`, or introduce a dedicated document-template plugin if separate configuration and policy boundaries justify it.
- Resolve the current user, conversation, workspace/group context, and authorized template document on the server. Model tool arguments should contain only the safe template reference and structured values needed for rendering.
- Reuse the current generated DOCX and chat-scoped artifact foundations in `functions_simplechat_operations.py` and `functions_workflow_runner.py` instead of adding a parallel download/storage system.
- Provide an output profile or post-processing step that allows document analysis and central synthesis to emit the versioned field-value contract.
- Keep the renderer independently callable through a local Semantic Kernel action. Automatic coordinated invocation can integrate with generalized orchestration artifact finalization and approval as those policies become active.
### Authorization, security, and operations
- Reauthorize template access at execution time for personal, group, public, and chat-upload scopes using existing document access boundaries.
- Never accept an arbitrary storage container/path from the model, and never send raw template bytes to the model when a field schema is sufficient.
- Keep the source template immutable and write output to a new artifact with a sanitized file name, supported MIME type, configured size limit, and existing retention rules.
- Do not execute macros, PDF JavaScript, external relationships, or embedded active content while inspecting or filling a template.
- Record bounded activity/telemetry for template revision, renderer type, validation outcome, and artifact identity without logging template contents or populated sensitive values.
- Make retries idempotent for the same approved generation request so transient failures do not create duplicate artifacts.
## Implementation Direction
### Local action and renderer boundary
- Target local SimpleChat agents and actions. Foundry-hosted agent or workflow invocation is out of scope.
- Implement a dedicated Document Template action, or an equivalently isolated SimpleChat action surface, backed by a renderer module that does not depend on Flask request objects.
- Keep the action contract stable: inspect an authorized template into a bounded field schema, then populate that exact template revision from validated structured values and publish the completed artifact.
- Keep orchestration optional. It can gather evidence, produce the field-value contract, and apply approval policy, but direct local-agent use must not depend on generalized orchestration.
### Python package assessment
- Use the existing `python-docx` package plus OOXML access for named Word content controls. `python-docx` does not expose a first-class public content-control API, so the implementation must isolate and test its `lxml`-based XML handling. Pin `lxml` directly if application code imports it rather than relying on a transitive dependency.
- Use the existing `pypdf` package for AcroForm discovery, value updates, appearance generation, and the selected flattening behavior.
- Use existing `PyMuPDF` only where preview or post-generation validation is useful; it is not required for basic field population.
- Do not add `docxtpl` for the initial named-field contract. Reconsider it only if Jinja-style templates or repeating sections become an approved requirement.
- DOCX-to-PDF conversion is not part of this capability and would require an additional rendering engine or external service.
### Execution and scaling decision
- Run bounded DOCX and AcroForm population locally in the SimpleChat application for the initial implementation. Ordinary template filling is an in-memory binary transform and does not justify a separate service by default.
- Enforce configurable source size, expanded DOCX package size, page count, field count, output size, execution time, and per-instance concurrency limits.
- Upload the completed bytes through the existing authorized chat-artifact path. Do not queue normal rendering through Flask-Executor merely to make it asynchronous; process-local futures are not a durable job boundary.
- Put the renderer behind a provider interface so a future external implementation can preserve the same action and validation contracts.
- Treat #669 as an optional future execution backend, not a dependency. Externalize workloads when measured latency/concurrency exceeds local limits or when capabilities require heavyweight engines, such as Office-to-PDF conversion, visual fidelity rendering, large repeating sections, or independent durable retries and scaling.
- Capture bounded telemetry for format, source/output byte counts, page/field counts, render duration, validation outcome, and failure category so any externalization decision is evidence-based.
## Acceptance Criteria
- [ ] A user can select an authorized `.docx` template or named-field AcroForm `.pdf` template as the required format for an analysis report.
- [ ] SimpleChat inventories supported fields into a versioned schema tied to the exact template revision.
- [ ] Analysis output is converted to schema-bound field values; unknown, missing required, invalid, or overflowing values are surfaced before generation.
- [ ] A deterministic renderer fills a copy of the template and preserves unaffected layout, styles, tables, headers/footers, images, and field ordering supported by the chosen contract.
- [ ] The original template remains unchanged.
- [ ] The completed DOCX or PDF appears in the current chat as an authorized downloadable generated-analysis artifact, with existing workspace promotion available.
- [ ] Personal/group/chat-upload authorization is revalidated at execution, and cross-user, cross-group, arbitrary-path, and stale-revision attempts fail closed.
- [ ] Unsupported formats or constructs return actionable errors and never silently fall back to a visually similar regenerated document.
- [ ] The capability is available to authorized local SimpleChat agents as an attachable action; orchestration may call the same renderer contract without being required for direct agent use.
- [ ] Retries do not publish duplicate artifacts for the same generation request.
- [ ] Functional tests cover representative DOCX fields in body/table/header/footer locations, PDF text/choice/checkbox fields, formatting preservation, required-field failures, malformed/unsupported templates, authorization denials, stale revisions, artifact download authorization, and idempotent retry.
- [ ] Feature documentation explains how to author supported templates, known limitations, security behavior, and agent/workflow setup.
## Non-Goals For The First Release
- Inferring fields from arbitrary visually blank documents with no explicit machine-readable field contract.
- OCR-based placement into scanned or image-only PDFs.
- XFA PDFs, password-protected templates, legacy `.doc`, macro-enabled `.docm`, or executing embedded active content.
- Repeating sections, signature workflows, arbitrary image placement, or pixel-perfect generation outside the supported named-field contract.
- Foundry-hosted agent or workflow invocation; this issue targets local SimpleChat agents and attachable actions.
- PowerPoint template theming, which remains tracked separately.
## Existing Foundations And Dependencies
- `functions_simplechat_operations.py` already creates DOCX files from markdown-like content and uploads generated analysis artifacts.
- `semantic_kernel_plugins/simplechat_plugin.py` already exposes Word generation as a local Semantic Kernel action.
- `functions_workflow_runner.py` and the chat UI already support secure generated-analysis artifact delivery.
- Chat turn orchestration already has output-neutral evidence and central-synthesis contracts; generalized artifact finalizers and approval are the integration point for automatic coordinated execution, not a prerequisite for the core renderer/action.
## Related Work
- Related to #968, which tracks user-provided Word and PowerPoint templates for generated files, including template selection/storage and general placeholder mapping.
- This issue is intentionally narrower on execution semantics and broader on report forms: deterministic schema-driven population of DOCX and fillable PDF fields from analysis, validation, authorization, and direct chat artifact delivery.
Contributor guide
Assessment
This issue has not been assessed yet.