AWS Builder Center
Weekend Creative Agent Challenge: Madurai Malar🌸: From Local Stories to a Global Audience 🌍

Weekend Creative Agent Challenge: Madurai Malar🌸: From Local Stories to a Global Audience 🌍

Madurai Malar is an always-on AI storytelling agent that brings Madurai’s Tamil culture, stories, traditions, and local identity to life.Every day, it autonomously creates a fresh experience inspired by Madurai and makes it ready for users to discover. From Madurai’s roots to a modern global audience - one story at a time. 🌸🌍

Community Builder and Browserstack Champion
What if an AI agent could wake up every day, explore the stories, traditions, and cultural richness of Madurai, and transform them into engaging experiences for a modern audience?
That question inspired me to build Madurai Malar - From Madurai to the World.
I wanted this project to be more than another AI chatbot or a content-generation application. I wanted to bring together Madurai, Tamil culture, local stories, traditions, food, language, and modern AI in a way that feels fresh and relevant.
The result is an always-on autonomous storytelling agent that creates something new every day without anyone opening the application, entering a prompt, or pressing a Generate button.
The idea is simple:
Madurai's culture → AI storytelling → New perspectives for the world



Vision & What It Does

Madurai is more than a city. It is a place where Tamil language, literature, food, traditions, temples, markets, festivals, and everyday stories have lived alongside generations of people.
Yet much of that richness remains local—shared through conversations, memories, expressions, and stories that may never reach someone outside the region.
Madurai Malar is an autonomous AI storytelling agent that brings these stories to a wider audience. Every day, without anyone opening the application, writing a prompt, or pressing a Generate button, the agent wakes up, chooses something interesting from Madurai's cultural world, and creates a fresh experience in Tamil and English.
The core idea:
Madurai's culture → AI storytelling → A new perspective for the world

What it produces daily (autonomously):

  • 🌸 A fresh Madurai story inspired by its culture, places, traditions, food, language, or everyday life
  • 🗣️ A natural Tamil version that feels written for Tamil readers rather than simply translated from English
  • 🌍 A global perspective explaining why this local story or tradition can be interesting to someone anywhere in the world
  • 🔗 A modern connection linking a traditional idea to today's technology, lifestyle, community, sustainability, or human values
  • 💡 Three things to take away from the story
  • 📖 Context cards that distinguish cultural facts from creative storytelling
  • 🎨 A visual concept that can be used to bring the day's story to life

What makes it different from a chatbot:

This is NOT a Tamil Q&A bot.
Nobody needs to ask it:
"Tell me something about Madurai today."
The agent decides.
Every morning, it checks the available context, selects a theme it hasn't recently covered, creates the day's Malar, validates the content, and publishes it.
The next day, it does it again.
Over time, it remembers what has already been created and what users enjoy, allowing the experience to become more varied and personalized.
The goal isn't just to tell stories about Madurai. It's to make Madurai's stories discoverable, relatable, and alive for a new generation. 🌸🌍









Architecture Philosophy

Smallest reliable architecture that produces autonomous Tamil cultural content daily. No over-engineering - every AWS resource directly serves the autonomous pipeline. SAM + DynamoDB single-table + Bedrock + EventBridge. One scheduled Lambda, one API Lambda, one React SPA.
The Build Process
Step 1: Agent Pipeline (the brain) Built a TypeScript Lambda orchestrator (runDailyAgent.ts) that runs the full pipeline daily at 06:00 IST:
  • Idempotency check (already published today?)
  • Context collection (recent content, Tamil calendar, global preferences with decay)
  • Weighted theme selection across 10 Tamil cultural categories (கதை, கவிதை, சொல், உணவு, etc.) with 3-day cooldown gates and preference-weighted randomization
  • Amazon Bedrock generation with structured prompts - no user PII ever reaches the model
  • 12-gate content validation (Tamil density, length, fiction labeling, duplicate detection) Retry loop with corrective instructions (up to 3 attempts, temperature reduction on attempt 3)
  • Curated fallback library if all attempts fail
  • Atomic publish via DynamoDB TransactWriteItems
  • Structured JSON logging per stage + CloudWatch metrics
Step 2: Content Validation (the responsibility) Pure function validator ensures Tamil content quality - checks script density (≥70% Tamil chars), title length, content type consistency, duplicate detection against recent 14 days, fiction/fact labeling. Failed validation produces corrective instructions fed back to Bedrock on retry.
Step 3: Personalization Engine (the variety) Rule-based preference scoring (not ML). Every like/save/share/not-interested adjusts per-type scores clamped to [0,1]. Global aggregate with running mean + mild temporal decay toward neutral. Theme selector uses: 0.45×preference + 0.30×recencyFreshness + 0.15×weekdayBonus + 0.10×weatherAffinity.
Step 4: React UI (the experience) Dark-mode SPA with Tamil typography (Noto Sans Tamil, line-height 1.9). Dawn gradient hero card ("Paati's Petti"), archive with type filter chips, explore page ordered by preference scores, profile with visual score bars. Mobile-first responsive (390/768/1024 breakpoints). Cognito auth with PKCE flow.
Step 5: Infrastructure as Code (the deployment) Single SAM template creates: DynamoDB table (single-table design with GSI1, PITR, PAY_PER_REQUEST), two Lambda functions (Agent with reserved concurrency 1, API with JWT authorizer), EventBridge Scheduler (cron with Asia/Kolkata timezone), Cognito User Pool, API Gateway HTTP API, CloudWatch alarm for missed publications.
Stack: React + Vite + TypeScript | AWS SAM | Node 20 Lambdas | DynamoDB | Amazon Bedrock | EventBridge | Cognito | API Gateway HTTP API



AWS Architecture


AWS Services
Service
Role
Amazon EventBridge
Autonomous daily trigger - cron(0 6 * * ? *) at 06:00 IST
AWS Lambda (x3)
Agent orchestration + API serving + Admin trigger
Amazon Bedrock
AI Tamil content generation (Nova Premier) - story + validation loop
Amazon DynamoDB
Single-table design - content, users, interactions, preferences, agent runs, engagement (GSI for date/type queries)
Amazon Cognito
User authentication (PKCE flow), admin group authorization
Amazon API Gateway
HTTP API with JWT authorizer - routes all client requests
Amazon CloudFront
CDN for React SPA, HTTPS, caching
Amazon S3
Static website hosting (React + Vite build)
Amazon CloudWatch
Structured JSON logs, custom metrics (AgentRunSuccess, ValidationFailure, etc.), missed-publication alarm
AWS IAM
Least-privilege roles per Lambda function
AWS SAM
Infrastructure as Code - single sam deploy for entire stack



Key Design Decisions

  1. API Gateway HTTP API with JWT authorizer instead of Lambda Function URLs: Supports Cognito-based authentication natively, route-level authorization (admin vs. user), and structured request validation - needed for a multi-user app with protected routes and interaction recording.
  1. Single DynamoDB table with composite keys (pk/sk pattern): Content, users, interactions, preferences, agent runs, engagement counters, and saved items all in one table. GSI1 enables reverse-chronological archive queries and type-filtered content browsing without scan operations.
  1. Static React + Vite build instead of SSR: Faster, cheaper, simpler deployment to S3 + CloudFront. Content is fetched client-side via API - no server rendering needed since the data changes only once daily.
  1. Reserved concurrency 1 on the agent Lambda: Eliminates race conditions in the daily publish pipeline. Combined with 3-layer idempotency (existence check → conditional write → ConditionalCheckFailedException as success), guarantees exactly one Malar per day.
  1. Retry loop with corrective instructions instead of a separate validation call: The same Bedrock model generates and receives corrective feedback in a tight loop (up to 3 attempts, temperature reduction on attempt 3). More efficient than two separate model invocations - validator is a pure TypeScript function, not a second LLM call.
  1. Curated fallback library as safety net: If Bedrock fails all 3 attempts, one of 10 hand-written pre-validated Tamil content items is published. The system never misses a daily publication.
  1. Nova Premier model: Capable of high-quality bilingual Tamil/English creative output with structured JSON responses. Temperature 0.85 for creativity, reduced to 0.6 on final retry for reliability.
  1. Rule-based preference scoring instead of ML: Simple interaction deltas (LIKE +0.06, SAVE +0.10, NOT_INTERESTED -0.12) clamped to [0,1]. Transparent, explainable, and declared openly to users - "Based on simple interaction counting - not machine learning."
  1. AWS SAM over CDK: Template-level simplicity for a serverless-only stack. Single sam deploy creates the entire infrastructure - no compilation step, faster iteration during the 48-hour MVP build.



Challenges and Solutions

Challenge 1: Cultural Accuracy Without Fabrication
Problem: How do you prevent an AI from inventing Tamil cultural facts, fabricating temple histories, or attributing false quotes to historical figures?
Solution: A 12-gate content validator (contentValidator.ts) that runs as a pure TypeScript function -no second LLM call needed. It checks:
  • Fiction/fact labeling consistency (isFictional must match sourceType)
  • Factual claims require a reference field — unverifiable facts are blocked
  • Content type must match the selected theme
  • Duplicate detection against the last 14 days of content (title and subject similarity)
The system prompt also enforces clear fiction labeling: "✨ கற்பனைக் கதை / Creative fiction" vs "🌿 பண்பாட்டுக் குறிப்பு / Cultural note" — users always know what they're reading.
Challenge 2: Natural Tamil Output (≥70% Tamil Script Density)
Problem: Bedrock might produce mixed-language output or transliterated Tamil that reads poorly.
Solution: The validator enforces a hard Tamil density gate - tamilDensity(text) measures the ratio of Tamil script characters (U+0B80–U+0BFF) to meaningful characters. Below 70% density → content is rejected with corrective instructions: "Your previous response was largely not in Tamil script. Rewrite tamilContent entirely in Tamil." The retry loop feeds this feedback back to Bedrock with progressively lower temperature (0.85 → 0.6) for more deterministic output.
Challenge 3: Topic Repetition Across 10 Content Types
Problem: An autonomous daily agent could repeat the same popular types (STORY every day, ignoring POEM or LOCAL_WORD).
Solution: 3-day cooldown hard gate with progressive relaxation. Before selecting a theme, the agent queries DynamoDB for the last 14 content items. Any type used in the last 3 days is excluded entirely. The weighted-random sampling formula balances: 0.45×userPreference + 0.30×recencyFreshness + 0.15×weekdayBonus + 0.10×weatherAffinity. Types unused for 7+ days get maximum freshness weight.
Challenge 4: Bedrock Response Parsing
Problem: LLM output isn't always valid JSON - sometimes wrapped in markdown code fences, sometimes with trailing commentary.
Solution: The bedrockGenerator.ts strips markdown fences (` json ... ```) before parsing, attempts JSON.parse, and returns a typed { parseError: string }  on failure instead of throwing. The orchestrator then feeds "Your previous response was not parseable JSON. Return one JSON object only, no fences." as a corrective instruction for the next attempt.
Challenge 5: Idempotency -Running the Agent Twice Must Not Produce Two Malars
Problem: EventBridge might retry, admin might trigger while schedule is running, or race conditions between concurrent invocations.
Solution: 3-layer idempotency:
  1. Reserved concurrency 1 on the Lambda - at most one instance executes
  1. Early exit check: GetItem for today's content before starting the pipeline
  1. Conditional write: attribute_not_exists(pk) AND attribute_not_exists(sk) on publish - ConditionalCheckFailedException treated as success-by-race, not an error
Challenge 6: Graceful Degradation When External Services Fail
Problem: Weather API timeout, DynamoDB read failure for preferences, or Bedrock outage shouldn't prevent daily publication.
Solution: The context collector (contextCollector.ts) uses Promise.allSettled - each optional source (weather, preferences, recent content) can fail independently without stopping the pipeline. Failures push to a degraded[] array in the context. If all Bedrock attempts fail, a curated fallback library of 10 hand-written Tamil items (one per content type) publishes through the same path. The system never misses a day.


What Was Learned
  1. Autonomous agents need memory - and memory needs structure
Without the 14-day content history in DynamoDB, the agent would repeat "Meenakshi Temple story" every third day. The single-table design with GSI queries makes memory retrieval fast and cheap. Memory transforms a generator into a curator - each day's content is informed by everything that came before it.
  1. Validation as code beats validation as a second LLM call
We initially considered a separate Bedrock validation call, but a pure TypeScript validator with 12 deterministic gates proved more reliable. The validator never hallucinates, never approves its own output, and runs in <1ms. It produces machine-readable corrective instructions that feed directly back into the retry loop. Deterministic validation + generative creation is the right separation.
  1. The system prompt is the real product engineering
The most impactful work wasn't the Lambda orchestrator or the SAM template. It was crafting the Bedrock prompt: balancing "creative Tamil storytelling" with "structured JSON output" with "culturally responsible content." Getting Tamil density above 70% consistently, enforcing fiction/fact labeling, and preventing content type drift - all prompt engineering. The code just enforces what the prompt creates.
  1. Static SPAs are perfect for daily-content apps
A Vite + React static build served via CloudFront is fast, cheap ($0.01/day), and globally cached. Content changes once daily - there's no reason for SSR. The dynamic parts (user state, interactions, preferences) come from authenticated API calls. The static shell loads instantly; data fills in progressively.
  1. Idempotency must be designed in layers, not bolted on
A single if (exists) return check isn't enough when EventBridge retries, admins trigger manually, and Lambda cold starts race. Three layers solved it: reserved concurrency 1, early existence check, and conditional DynamoDB writes. Each layer catches a different failure mode. The result: run the agent 10 times in a row, get exactly one Malar.
  1. Cultural AI carries responsibility beyond technical correctness
Building an AI system about Tamil culture - real festivals, real traditions, real food, real places - means the fiction/fact distinction isn't a nice-to-have, it's an ethical requirement. Every piece of content is visibly labeled. Users always know: "Is this a creative story inspired by Madurai, or a cultural note based on documented tradition?" Transparency is the minimum bar.
  1. Graceful degradation > graceful failure
The agent must publish every single day. Weather API down? Publish without weather context. Preferences unreadable? Use neutral 0.5 defaults. Bedrock failing? Use curated fallback. Each failure degrades quality slightly but never breaks the daily promise. The degraded[] array in context tracks what was lost - useful for monitoring without blocking output.
  1. SAM + single-table DynamoDB = fast serverless iteration
One sam deploy creates 9 AWS resources with correct IAM, all wired together. The single DynamoDB table with composite keys (pk/sk) eliminated the need for multiple tables, multiple IAM policies, and cross-table consistency concerns. Everything in one table, everything in one template, deployed in under 60 seconds.



Evidence of Autonomous Execution

  1. Admin Activity Dashboard
The web application includes a dedicated Admin panel (/admin) showing:
Agent status and last run outcome (PUBLISHED / FAILED / SKIPPED)
Next scheduled run time (06:00 IST daily)
"Run Agent Now" button with rate limit indicator (5/hr)
Stage-by-stage activity panel with real timings
Recent runs table with agentRunId, status, duration, and content type
2. Structured Stage-by-Stage Logs
Each run produces structured JSON logs per pipeline stage:
06:00:01 DailyMalarAgent START trigger=SCHEDULE
06:00:01 runDailyAgent CONTEXT ok=true durationMs=340
06:00:01 runDailyAgent WEATHER ok=false (degraded)
06:00:02 runDailyAgent THEME ok=true selectedTheme=POEM durationMs=2
06:00:04 runDailyAgent GENERATION ok=true attempt=1
06:00:04 runDailyAgent VALIDATION ok=true
06:00:05 runDailyAgent PUBLISH ok=true contentId=malar_2026-08-22_POEM
06:00:05 DailyMalarAgent COMPLETE status=PUBLISHED durationMs=4200
3. CloudWatch Metrics & Alarms
Every Lambda execution emits custom CloudWatch metrics under MaduraiMalar/Agent:
AgentRunSuccess — incremented on successful publish
AgentRunFailure — incremented on pipeline failure
AgentFallbackUsed — tracks curated fallback usage
GenerationAttempts — how many Bedrock calls were needed
AgentRunDuration — end-to-end milliseconds
AgentIdempotentSkip — duplicate run detection
Alarm: triggers when AgentRunSuccess < 1 in the 07:00–08:00 IST window
4. EventBridge Scheduler Rule
The rule madurai-malar-daily-0600-ist is configured in the SAM template:
ScheduleExpression: "cron(0 6 * * ? *)"
ScheduleExpressionTimezone: "Asia/Kolkata"
FlexibleTimeWindow: OFF
Input: '{"trigger":"SCHEDULE","scheduleName":"madurai-malar-daily-0600-ist"}'
5. DynamoDB Agent Run Records
Each run creates a full AgentRun record with timestamps and stage history:
{
"pk": "AGENTRUN#2026-08-22",
"sk": "RUN#a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"gsi1pk": "AGENTRUN#ALL",
"gsi1sk": "2026-08-22T00:30:05.123Z",
"runDate": "2026-08-22",
"trigger": "SCHEDULE",
"status": "PUBLISHED",
"selectedTheme": "POEM",
"generationAttempts": 1,
"validationStatus": "PASSED",
"usedFallback": false,
"contentId": "malar_2026-08-22_POEM",
"durationMs": 4200,
"stages": [
{"stage": "CONTEXT", "ok": true, "durationMs": 340},
{"stage": "WEATHER", "ok": false},
{"stage": "THEME", "ok": true, "detail": "POEM", "durationMs": 2},
{"stage": "GENERATION", "ok": true},
{"stage": "VALIDATION", "ok": true},
{"stage": "PUBLISH", "ok": true}
]
}
6. Multiple Malars Already Generated
The agent produces diverse Tamil cultural content daily across 10 categories, demonstrating that the scheduling, theme diversity, and cooldown systems work:
  • "வைகை நதியின் கதை" (STORY - Vaigai River tale)
  • "மதுரை மல்லிகை மணம்" (POEM - Madurai jasmine fragrance)
  • "கொத்துப் பரோட்டா" (FOOD - Kothu parotta cultural note)
  • "திருமலை நாயக்கர் மஹால்" (HERITAGE - Thirumalai Nayakkar Palace)
  • "கூடல் நகர்" (LOCAL_WORD - "Koodal" meaning confluence city)


Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article