An enterprise-grade, autonomous Python AI agent framework designed to convert natural language business briefsβfrom structured project proposals to ambiguous, multi-departmental policiesβinto publication-grade, professionally formatted Microsoft Word (.docx) deliverables.
Built with a Plan β Execute β Reflect β Compile autonomous agent architecture, typed Pydantic contracts, hybrid LLM connectivity (Google Gemini, Groq, and offline deterministic fallback), and an interactive Web Studio UI.
- System Architecture & Workflow
- Key Capabilities & Engineering Highlights
- The 4-Phase Autonomous Pipeline
- Advanced Engineering: Reflection & Self-Check Loop
- Interactive Web Studio UI
- Repository Structure
- Getting Started & Installation
- API Specification & Endpoints
- Running Benchmark Scenarios & Tests
- Engineering Tradeoffs & Technical Insights
- Author & Acknowledgments
The agent operates across four discrete, human-readable execution phases to prevent hallucination, enforce strict quality standards, and generate reliable outputs:
flowchart TD
A[Natural Language Request] --> B[Phase 1: Autonomous Planning & Ambiguity Analysis]
B -->|Classify Document Type| C{Conflicting / Vague?}
C -->|Yes| D[Formulate Explicit Assumptions & Decision Rationale]
C -->|No| E[Extract Scope & Core Objectives]
D --> F[Generate Ordered 6-Stage Dynamic Plan / TODO List]
E --> F
F --> G[Phase 2: Sequential Step Execution]
G -->|Iterate Tasks| H[Draft Narrative, Action Bullets & Tabular Matrices]
H --> I[Phase 3: Reflection & Self-Check Quality Gate]
I -->|Audit Completeness & SLAs| J{Gaps Detected?}
J -->|Yes| K[Synthesize Adaptive Checklist & Milestones]
J -->|No| L[Verify Criteria & Compute Quality Score]
K --> L
L --> M[Phase 4: Word Document Compilation .docx]
M -->|Apply Corporate Palette & XML Shading| N[Save Formatted Artifact & Serve via REST API / UI]
- Autonomous Task Planning: Decomposes open-ended requests into structured, trackable execution phases rather than relying on one-shot raw prompt generation.
- Intelligent Ambiguity & Conflict Resolution: Identifies contradictions across departments (e.g., Support demanding instant refunds vs. Finance requiring fraud prevention) and formulates explicit, documented assumptions.
- Publication-Grade Word (
.docx) Styling:- Corporate Navy Blue (
#1B365D) typography and branding. - Formatted tables with shaded headers, alternating row fills, and custom XML cell margins.
- Executive metadata summary cards and highlighted assumption callouts.
- Corporate Navy Blue (
- Zero-Friction Hybrid LLM Engine:
- Native integration with Google Gemini API (
google-genaiSDK). - Fast inference via Groq Cloud API (
httpxclient). - Built-in Smart Deterministic Fallback Engine ensuring 100% offline functionality without API keys.
- Native integration with Google Gemini API (
- Developer-Friendly RESTful API: High-performance FastAPI server with automatic OpenAPI Swagger documentation.
- Interactive Web Studio: Built-in responsive dashboard (Tailwind CSS, FontAwesome) for interactive prompt testing, real-time log monitoring, and direct document downloads.
- Classifies document type (
Project Proposal,Standard Operating Procedure (SOP),Technical Specification, orExecutive Brief). - Analyzes prompt for conflicting business rules and missing thresholds.
- Generates an initial dynamic 6-step TODO list with granular titles, descriptions, and initial
pendingstatuses.
- Iterates through each task in the TODO plan, updating state:
pending$\rightarrow$ in_progress$\rightarrow$ completed. - Synthesizes tailored content sections:
- Executive Overview: High-level problem statement and objectives.
- Governance & Team Matrix: Detailed role-responsibility tables.
- Operational Workflow: Phased chronological milestones.
- Risk Assessment & Mitigation: Severity matrix and contingency plans.
- Financial & Compliance Controls: Explicit sign-off requirements.
- Conducts an automated post-generation audit against enterprise documentation standards:
- Checks for structured timelines, Service Level Agreements (SLAs), and quantitative milestones.
- Confirms governance hierarchy and escalation pathways.
- Validates that all ambiguous constraints have documented assumptions.
- Injects an Actionable Implementation Checklist to bridge operational gaps.
- Generates an objective Quality Score (e.g.,
10/10) with verification logs.
- Transforms structured memory models into a
.docxdocument viapython-docx:- Sets standard 1-inch margins and clear typographical hierarchy.
- Builds an Executive Metadata Table at the document header.
- Adds an Autonomous Planning Note callout highlighting the agent's assumptions.
- Applies low-level XML styling to table cells for borders and padding.
Autonomous agents frequently encounter "first-draft myopia"βproducing high-level summaries while missing critical operational parameters (SLAs, escalation steps, compliance checkpoints).
To solve this, the agent incorporates an explicit Self-Check & Adaptive Refinement Loop:
Draft Sections Collected
β
βΌ
[Completeness Audit] ββ> Check for Timelines, SLAs, Escalation Rules & Tax Guidelines
β
βββ> Omission Detected: Ingest Explicit Assumptions & Add Missing Milestones
β
βΌ
[Adaptive Refinement] β> Generate "Actionable Implementation Checklist"
β
βΌ
[Quality Verification] β> Assign Objective Score (1-10) & Finalize Schema
The repository includes a modern, zero-dependency browser studio served directly by FastAPI at /:
- Preset Scenarios: One-click buttons to load benchmark test cases.
- Execution Plan Visualizer: Dynamic cards reflecting task status transitions in real time.
- Terminal Log Simulator: Chronological trace of agent reasoning and phase transitions.
- Direct File Download: Instant download button for generated
.docxartifacts.
To launch the studio:
python -m uvicorn app.main:app --host 127.0.0.1 --port 8000 --reloadNavigate to http://127.0.0.1:8000 in your web browser.
Python-AI-Engineer-Autonomous-Agents/
β
βββ app/
β βββ __init__.py # Package marker and version info
β βββ config.py # Paths, environment configs, logger setup
β βββ models.py # Typed Pydantic schemas (AgentRequest, Plan, Task, etc.)
β βββ llm_client.py # Dual provider (Gemini / Groq) + deterministic fallback
β βββ agent.py # Core agent pipeline (Plan -> Execute -> Reflect)
β βββ document_generator.py # python-docx corporate styling engine (XML formatting)
β βββ main.py # FastAPI REST API & static file routing
β βββ static/
β βββ index.html # Web Studio frontend (Tailwind CSS, FontAwesome)
β
βββ generated_docs/ # Output directory for generated Word (.docx) files
β βββ .gitkeep # Preserves directory in git tracking
β
βββ test_runner.py # Standalone test runner for benchmark test cases
βββ test_api.py # API integration test suite using FastAPI TestClient
βββ requirements.txt # Production Python dependencies
βββ .env.example # Environment configuration template
βββ .gitignore # Git ignore configuration
βββ README.md # Comprehensive project documentation
- Python 3.10, 3.11, or 3.12
- Windows, Linux, or macOS
git clone https://github.com/harshrameshnerkar/Python-AI-Engineer-Autonomous-Agents.git
cd Python-AI-Engineer-Autonomous-Agents
# Create virtual environment
python -m venv venv
# Activate virtual environment
# On Windows (PowerShell):
.\venv\Scripts\Activate.ps1
# On Linux/macOS:
source venv/bin/activate
# Install dependencies
pip install -r requirements.txtThe system runs out of the box with zero setup using its built-in deterministic fallback engine. To enable live inference with external providers:
cp .env.example .envEdit .env:
# Google Gemini API (Recommended free tier)
GEMINI_API_KEY=your_gemini_api_key_here
# OR Groq API (High-speed inference)
GROQ_API_KEY=your_groq_api_key_hereStart the API server:
python -m uvicorn app.main:app --host 127.0.0.1 --port 8000 --reloadInteractive Swagger documentation is available at: http://127.0.0.1:8000/docs
Executes autonomous task breakdown, step execution, quality reflection, and document compilation.
Request:
curl -X POST "http://127.0.0.1:8000/agent" \
-H "Content-Type: application/json" \
-d '{"request": "Create a comprehensive project proposal for migrating our customer database from MySQL to PostgreSQL in 3 months."}'Response (Summary):
{
"request": "Create a comprehensive project proposal...",
"status": "success",
"document_type": "Project Proposal",
"plan": [
{
"task_id": 1,
"title": "Requirement & Scope Decomposition",
"description": "Analyze input prompt, define goals, identify deliverables...",
"status": "completed",
"result_summary": "Generated section: 'Executive Summary & Strategic Objectives'"
}
],
"execution_logs": [
"Phase 1: Analyzing user request and generating autonomous execution plan.",
"Phase 2: Executing planned tasks sequentially...",
"Phase 3: Performing quality reflection and self-check verification...",
"Phase 4: Compiling polished Microsoft Word (.docx) document."
],
"reflection": {
"quality_score": 10,
"assumptions_made": [
"Project execution schedule is estimated at 3 calendar months across 4 phased sprints.",
"Target production environment is managed PostgreSQL with multi-AZ failover."
],
"identified_gaps": [],
"improvements_applied": [
"Integrated explicit assumptions into document callout.",
"Appended actionable implementation checklist (Next Steps)."
],
"verification_status": "PASSED & REFINED"
},
"document": {
"file_name": "project_proposal__enterprise_database_mi_20261105_125352.docx",
"file_size_bytes": 40440,
"download_url": "/download/project_proposal__enterprise_database_mi_20261105_125352.docx",
"document_title": "Project Proposal: Enterprise Database Migration to PostgreSQL",
"section_count": 7
}
}Streams the generated .docx binary directly to the client.
Returns server operational health, active LLM provider, and total document count.
"Create a comprehensive project proposal for migrating our customer database from on-premise MySQL to Cloud PostgreSQL. The migration must have a 3-month timeline, dedicated team structure, risk assessment, and zero data loss."
"Draft an urgent SOP for handling unexpected customer payment disputes and chargebacks. Our customer support team wants instant no-questions-asked refunds, but finance demands strict manager sign-offs and evidence collection to prevent fraud. We also sell in multiple countries with cross-border tax implications, and we don't have a clear escalation threshold yet."
python test_runner.pyValidates document classification, plan generation, reflection scoring, and verifies .docx file integrity (paragraph and table counts).
python test_api.pyExecutes comprehensive end-to-end integration tests using FastAPI TestClient.
- Challenge: Giving LLMs unconstrained authority over document layout frequently leads to inconsistent heading hierarchies, missing compliance sections, and broken file syntax. Conversely, hardcoded templates lack the flexibility to handle nuanced, ambiguous prompts.
- Solution: A Hybrid Architecture. The planning, assumption reasoning, and section generation remain dynamic and agentic, while the document compilation, table formatting, and reflection checks are governed by typed Pydantic contracts and low-level
python-docxstyling rules.
- Challenge: Standard Python execution on Windows consoles often defaults to Code Page 1252 (
cp1252), leading toUnicodeEncodeErrorwhen emitting modern Unicode symbols or emoji markers. - Solution: Implemented proactive standard output stream reconfiguration (
sys.stdout.reconfigure(encoding="utf-8")) and resilient ASCII status formatting ([OK],[FAIL],[AGENT]) to ensure seamless execution across Windows, Linux containers, and CI/CD pipelines.
- Developer: Harsh Nerkar
- Portfolio: harshnerkar.vercel.app
- Specialization: AI/ML Engineering β’ Autonomous Multi-Agent Systems β’ GenAI & Computer Vision
This project is licensed under the MIT License.