Skip to content

About

Autonomous Python AI Agent framework that converts natural language business requests into publication-grade Microsoft Word (.docx) documents with dynamic planning, reflection, and corporate styling.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

1 Commit

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Python AI Engineer – Autonomous Agents: Business Document Generator

Python Version FastAPI LLM Support Pydantic python-docx License

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.


πŸ“‘ Table of Contents

  1. System Architecture & Workflow
  2. Key Capabilities & Engineering Highlights
  3. The 4-Phase Autonomous Pipeline
  4. Advanced Engineering: Reflection & Self-Check Loop
  5. Interactive Web Studio UI
  6. Repository Structure
  7. Getting Started & Installation
  8. API Specification & Endpoints
  9. Running Benchmark Scenarios & Tests
  10. Engineering Tradeoffs & Technical Insights
  11. Author & Acknowledgments

πŸ› System Architecture & Workflow

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]
Loading

✨ Key Capabilities & Engineering Highlights

  • 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.
  • Zero-Friction Hybrid LLM Engine:
    • Native integration with Google Gemini API (google-genai SDK).
    • Fast inference via Groq Cloud API (httpx client).
    • Built-in Smart Deterministic Fallback Engine ensuring 100% offline functionality without API keys.
  • 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.

πŸ”„ The 4-Phase Autonomous Pipeline

Phase 1: Request Analysis & Autonomous Planning

  • Classifies document type (Project Proposal, Standard Operating Procedure (SOP), Technical Specification, or Executive Brief).
  • Analyzes prompt for conflicting business rules and missing thresholds.
  • Generates an initial dynamic 6-step TODO list with granular titles, descriptions, and initial pending statuses.

Phase 2: Sequential Step Execution

  • 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.

Phase 3: Reflection & Self-Check Verification

  • 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.

Phase 4: Corporate Word Document Compilation

  • Transforms structured memory models into a .docx document via python-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.

πŸ” Advanced Engineering: Reflection & Self-Check Loop

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

πŸ’» Interactive Web Studio UI

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 .docx artifacts.

To launch the studio:

python -m uvicorn app.main:app --host 127.0.0.1 --port 8000 --reload

Navigate to http://127.0.0.1:8000 in your web browser.


πŸ“‚ Repository Structure

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

πŸš€ Getting Started & Installation

Prerequisites

  • Python 3.10, 3.11, or 3.12
  • Windows, Linux, or macOS

1. Clone & Setup Environment

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.txt

2. Optional: Configure API Keys

The 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 .env

Edit .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_here

πŸ“‘ API Specification & Endpoints

Start the API server:

python -m uvicorn app.main:app --host 127.0.0.1 --port 8000 --reload

Interactive Swagger documentation is available at: http://127.0.0.1:8000/docs

1. POST /agent

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
  }
}

2. GET /download/{filename}

Streams the generated .docx binary directly to the client.

3. GET /health

Returns server operational health, active LLM provider, and total document count.


πŸ§ͺ Running Benchmark Scenarios & Tests

Scenario 1: Standard Enterprise Business Request

"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."

Scenario 2: Complex, Ambiguous & Conflicting Request

"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."

Run Benchmark Suite

python test_runner.py

Validates document classification, plan generation, reflection scoring, and verifies .docx file integrity (paragraph and table counts).

Run API Integration Tests

python test_api.py

Executes comprehensive end-to-end integration tests using FastAPI TestClient.


πŸ’‘ Engineering Tradeoffs & Technical Insights

1. Autonomous Planning vs. Deterministic Layout Guardrails

  • 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-docx styling rules.

2. Windows Cross-Platform Terminal Encoding

  • Challenge: Standard Python execution on Windows consoles often defaults to Code Page 1252 (cp1252), leading to UnicodeEncodeError when 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.

πŸ‘€ Author & Acknowledgments


πŸ“„ License

This project is licensed under the MIT License.

About

Autonomous Python AI Agent framework that converts natural language business requests into publication-grade Microsoft Word (.docx) documents with dynamic planning, reflection, and corporate styling.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages