{"id":9136,"date":"2026-11-10T04:52:51","date_gmt":"2026-11-10T04:52:51","guid":{"rendered":"https:\/\/www.skyalleys.com\/?p=9136"},"modified":"2026-11-10T04:52:56","modified_gmt":"2026-11-10T04:52:56","slug":"cognitive-work-architecture-open-source-ai-agent","status":"publish","type":"post","link":"https:\/\/www.skyalleys.com\/index.php\/cognitive-work-architecture\/cognitive-work-architecture-open-source-ai-agent\/","title":{"rendered":"Building an AI Agent That Knows Its Own Cost: Open-Sourcing the Cognitive Work Architecture"},"content":{"rendered":"\n<figure class=\"wp-block-image size-large\"><img loading=\"lazy\" decoding=\"async\" width=\"2048\" height=\"1143\" src=\"https:\/\/www.skyalleys.com\/wp-content\/uploads\/2026\/11\/Temp_Image_1lub1c1lub1c1lub-1-2048x1143.jpg\" alt=\"Abstract blueprint visualization of a 5-layer AI agent output guardrail pipeline with amber governance gate and data stream flowing through translucent filter layers on dark background\" class=\"wp-image-9138\" srcset=\"https:\/\/www.skyalleys.com\/wp-content\/uploads\/2026\/11\/Temp_Image_1lub1c1lub1c1lub-1-2048x1143.jpg 2048w, https:\/\/www.skyalleys.com\/wp-content\/uploads\/2026\/11\/Temp_Image_1lub1c1lub1c1lub-1-500x279.jpg 500w, https:\/\/www.skyalleys.com\/wp-content\/uploads\/2026\/11\/Temp_Image_1lub1c1lub1c1lub-1-768x429.jpg 768w, https:\/\/www.skyalleys.com\/wp-content\/uploads\/2026\/11\/Temp_Image_1lub1c1lub1c1lub-1-1536x857.jpg 1536w, https:\/\/www.skyalleys.com\/wp-content\/uploads\/2026\/11\/Temp_Image_1lub1c1lub1c1lub-1-1000x558.jpg 1000w, https:\/\/www.skyalleys.com\/wp-content\/uploads\/2026\/11\/Temp_Image_1lub1c1lub1c1lub-1-230x128.jpg 230w, https:\/\/www.skyalleys.com\/wp-content\/uploads\/2026\/11\/Temp_Image_1lub1c1lub1c1lub-1-350x195.jpg 350w, https:\/\/www.skyalleys.com\/wp-content\/uploads\/2026\/11\/Temp_Image_1lub1c1lub1c1lub-1-480x268.jpg 480w\" sizes=\"auto, (max-width: 2048px) 100vw, 2048px\" \/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">Most AI agents are built to be impressive. This one was built to be accountable.<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">There&#8217;s a gap in the AI agent ecosystem that nobody talks about at conferences.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Every tutorial shows you how to build an agent that works. Few show you how to build one that works <strong>within a budget<\/strong>, <strong>enforces its own behavioral rules in code<\/strong>, and <strong>degrades gracefully when something goes wrong<\/strong> instead of showing your visitors an error page.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We&#8217;ve spent the past year building and deploying AI agents for enterprise clients. Along the way, we developed an internal framework we call the <strong>Cognitive Work Architecture (CWA)<\/strong>, a set of patterns for building agents that operate with the same governance, cost discipline, and accountability you&#8217;d expect from any production enterprise system.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Today, we&#8217;re open-sourcing the first agent built on this architecture: the <strong>Site Sales Agent<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Not a demo. Not a proof of concept. The actual production code running on our website, handling real conversations, tracking its own cost to six decimal places on every single request.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>GitHub:<\/strong> <a href=\"https:\/\/github.com\/Cuciu\/cognitive-work-architecture\/tree\/main\/site-sales-agent\" data-type=\"link\" data-id=\"https:\/\/github.com\/Cuciu\/cognitive-work-architecture\/tree\/main\/site-sales-agent\" target=\"_blank\" rel=\"noreferrer noopener\">Cognitive-work-architecture\/sales-agent<\/a><\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What the Site Sales Agent Actually Does<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The agent sits on our website as a chat widget. When a visitor asks about our services, it responds with the depth and nuance of a senior sales advisor \u2014 not the enthusiasm of a chatbot desperately trying to book a meeting.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s what happens on every request:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>The visitor&#8217;s message arrives with their conversation history<\/li>\n\n\n\n<li>Cloudflare Turnstile verifies the request isn&#8217;t from a bot<\/li>\n\n\n\n<li>The monthly budget is checked, if exhausted, a graceful fallback is served<\/li>\n\n\n\n<li>The session prompt count is checked, if exceeded, a human handoff is offered<\/li>\n\n\n\n<li>The model generates a response using cached site content<\/li>\n\n\n\n<li>Five layers of output processing enforce behavioral rules<\/li>\n\n\n\n<li>The actual token cost is calculated and accumulated against the monthly budget<\/li>\n\n\n\n<li>The clean response is returned with optional booking CTA<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Every step in that flow has a failure mode, and every failure mode has a handler. The visitor never sees an error.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The Three Pillars<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The architecture rests on three pillars that we believe every production AI agent needs:<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">1. Budget Governance<\/h3>\n\n\n\n<h3 class=\"wp-block-heading\">2. Behavioral Guardrails<\/h3>\n\n\n\n<h3 class=\"wp-block-heading\">3. Graceful Degradation<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s look at each one.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Pillar 1: Budget Governance<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">This is the pillar most agent builders skip entirely.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here&#8217;s the typical AI agent cost management strategy: deploy the agent, hope the token costs stay reasonable, and find out what you actually spent when the invoice arrives 30 days later.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">That&#8217;s not engineering. That&#8217;s gambling.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Per-Request Cost Tracking<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Our agent calculates the exact cost of every single request using the token counts from the model&#8217;s response metadata:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>RATE_INPUT_CACHED = 0.15 \/ 1_000_000\nRATE_INPUT_STD    = 1.50 \/ 1_000_000\nRATE_OUTPUT       = 7.50 \/ 1_000_000\n\num         = resp.usage_metadata\ncached     = getattr(um, \"cached_content_token_count\", 0) or 0\nprompt_tok = getattr(um, \"prompt_token_count\", 0) or 0\nout_tok    = getattr(um, \"candidates_token_count\", 0) or 0\nnon_cached = max(prompt_tok - cached, 0)\ncost       = (cached * RATE_INPUT_CACHED + non_cached * RATE_INPUT_STD + out_tok * RATE_OUTPUT)\n\nbudget_ref.update({\"CurrentSpendUSD\": firestore.Increment(cost)})\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Notice the distinction between <strong>cached and non-cached input tokens<\/strong>. When the context cache is active, site content tokens are billed at 1\/10th the standard rate. When the cache is missing or expired, those same tokens are billed at the full rate. The agent tracks both separately because they represent fundamentally different cost profiles.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The cost is accumulated in Firestore using <code>firestore.Increment()<\/code> \u2014 an atomic operation that prevents race conditions even under concurrent requests.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Monthly Budget Lifecycle<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The budget isn&#8217;t just tracked, it&#8217;s governed through a four-stage lifecycle:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Track<\/strong> \u2192 Every request calculates and accumulates its cost.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Monitor<\/strong> \u2192 A scheduled job runs every four hours, checking spend against two thresholds:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>80% (DegradeThreshold):<\/strong> A warning alert fires via webhook \u2014 Slack, Teams, PagerDuty, whatever you&#8217;ve configured. The alert fires exactly once, not every four hours. Alert deduplication is built in through a boolean flag.<\/li>\n\n\n\n<li><strong>100% (MonthlyLimit):<\/strong> A critical alert fires, and the service tier is set to &#8220;Degraded.&#8221; The agent stops calling the model and serves a fallback CTA instead.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Enforce<\/strong> \u2192 The agent reads the current tier on every request. When degraded, visitors see a professional message with a direct booking link \u2014 not an error.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Reset<\/strong> \u2192 On the 1st of each month, a scheduled job zeros the spend counters and clears the alert flags. Importantly, it preserves any custom budget limits. If someone manually raised the MonthlyLimitUSD mid-month, the reset doesn&#8217;t stomp that configuration \u2014 it only clears the counters.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Auto-Recovery<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">One detail we&#8217;re particularly proud of: the system self-heals. If the budget monitor finds that spend has dropped below the monthly limit \u2014 because someone manually increased the budget, or because a new billing period started \u2014 it automatically restores the service tier to &#8220;Full&#8221; without any human intervention.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Most budget systems require a manual reset to un-degrade. This one doesn&#8217;t.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What It Costs in Practice<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">At current Gemini 2.5 Flash Lite pricing, with context caching:<\/p>\n\n\n\n<figure class=\"wp-block-table is-style-stripes\"><table class=\"has-fixed-layout\"><thead><tr><th>Scenario<\/th><th class=\"has-text-align-center\" data-align=\"center\">Monthly Cost<\/th><\/tr><\/thead><tbody><tr><td>1,000 conversations, 4 turns average, <strong>with cache<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\">~$2.50<\/td><\/tr><tr><td>1,000 conversations, 4 turns average, <strong>without cache<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\">~$18.00<\/td><\/tr><tr><td><strong>Savings from caching<\/strong><\/td><td class=\"has-text-align-center\" data-align=\"center\"><strong>~85%<\/strong><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The default budget is set to $10\/month \u2014 more than enough for a site-level sales agent. The degrade threshold sits at $8, giving you a $2 warning buffer before the agent stops calling the model.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Pillar 2: Behavioral Guardrails<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">&#8220;Prompt = Suggestion. Code = Law.&#8221;<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This is the thesis of the entire architecture.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Every AI agent has a system prompt that tells the model how to behave. Our system prompt is detailed \u2014 it defines a 4-state conversation machine, handles low-energy replies, prevents premature booking suggestions, and forbids URL generation.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">But here&#8217;s what we learned in production: <strong>models don&#8217;t always follow prompts.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Not because they&#8217;re broken. Because they&#8217;re probabilistic. A large language model will follow your instructions most of the time. But &#8220;most of the time&#8221; isn&#8217;t good enough when a model that ignores your &#8220;don&#8217;t push for a meeting on the first message&#8221; instruction ends up feeling like a desperate chatbot instead of a senior advisor.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So we built a second layer of enforcement, in code.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The 5-Layer Output Pipeline<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Every model response passes through five processing layers before reaching the visitor:<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Layer 1: Smart Truncation<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def smart_truncate(text, limit=MAX_ANSWER_CHARS):\n    text = (text or \"\").strip()\n    if len(text) &lt;= limit:\n        return text\n    cut = text&#91;:limit]\n    for sep in &#91;\". \", \"! \", \"? \"]:\n        idx = cut.rfind(sep)\n        if idx &gt; limit * 0.6:\n            return cut&#91;:idx + 1].strip()\n    return cut.rsplit(\" \", 1)&#91;0].strip() + \"\u2026\"\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The model is told to keep responses concise. But sometimes it generates a 1,200-character wall of text for a small chat window. This function caps the output at 700 characters, but it doesn&#8217;t cut mid-sentence. It finds the last sentence-ending punctuation mark in the safe zone (after 60% of the content has been preserved) and cuts there.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If no sentence boundary is found, it falls back to the last word boundary and adds an ellipsis.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Layer 2: Premature CTA Language Removal<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def strip_premature_cta_language(text, turn_count, min_turns=MIN_TURNS_BEFORE_CTA):\n    if turn_count &gt;= min_turns:\n        return text\n    patterns = &#91;\n        r\"Would you like to (schedule|book|set up).*?\\?\",\n        r\"Ready to (schedule|book|set up).*?\\?\",\n        r\"Let'?s (schedule|book|set up).*?\\.\",\n        r\"Shall we (schedule|book|set up).*?\\?\",\n    ]\n    for p in patterns:\n        text = re.sub(p, \"\", text, flags=re.IGNORECASE)\n    return text.strip()\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The system prompt says: &#8220;Don&#8217;t suggest a meeting before the visitor has had at least two substantive exchanges.&#8221; The model usually complies. When it doesn&#8217;t, this function catches phrases like &#8220;Would you like to schedule a call?&#8221; and silently removes them if we haven&#8217;t passed the turn gate (<code>MIN_TURNS_BEFORE_CTA = 3<\/code>).<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Once the turn count is at or above the minimum, this function does nothing \u2014 it&#8217;s a gate, not a permanent filter.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Layer 3: Booking Marker Extraction<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The system prompt tells the model to emit <code>[BOOK_CTA]<\/code> as a marker when it detects buying intent. The code extracts this marker (retaining it as a signal for whether to render the booking button) and removes it from the display text so the visitor never sees the raw marker.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Layer 4: URL Stripping<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def strip_urls(text):\n    t = text or \"\"\n    had_url = bool(re.search(r'https?:\/\/\\S+', t))\n    t = re.sub(r'https?:\/\/\\S+', '', t)\n    t = re.sub(r'\\s*(here|below|at)\\s*:?\\s*$', '', t, flags=re.IGNORECASE)\n    t = re.sub(r'\\s{2,}', ' ', t).strip()\n    return t, had_url\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The model is explicitly told: &#8220;Never write a URL or booking link.&#8221; But occasionally, it generates one anyway \u2014 usually a hallucinated URL that doesn&#8217;t even exist.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This function strips all URLs from the output and also cleans up dangling text like &#8220;&#8230;click here:&#8221; or &#8220;&#8230;visit the link below:&#8221; that would read awkwardly after the URL is removed.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The function returns a boolean indicating whether a URL was found. If the model tried to output a URL, that&#8217;s treated as an additional signal for booking intent \u2014 the model was probably trying to share a booking link.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Layer 5: CTA Gate Check<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>show_cta = (\n    (has_marker or had_url or visitor_wants_booking or new_count &gt;= MAX_PROMPTS_PER_SESSION)\n    and new_count &gt;= MIN_TURNS_BEFORE_CTA\n)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The final gate. Even if every other signal says &#8220;show the booking button,&#8221; it will not render unless <code>new_count &gt;= MIN_TURNS_BEFORE_CTA<\/code>. This is the hard override.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The prompt says &#8220;don&#8217;t push meetings early.&#8221; The code makes it impossible.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The Conversation State Machine<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Beneath the output pipeline, the agent&#8217;s behavior is governed by a 4-state conversation machine defined in the system prompt:<\/p>\n\n\n\n<figure class=\"wp-block-table is-style-stripes\"><table class=\"has-fixed-layout\"><thead><tr><th class=\"has-text-align-center\" data-align=\"center\">State<\/th><th>Name<\/th><th>Behavior<\/th><th>Transition Rule<\/th><\/tr><\/thead><tbody><tr><td class=\"has-text-align-center\" data-align=\"center\">1<\/td><td><strong>Discovery<\/strong><\/td><td>Ask one question about their challenge<\/td><td>Enter once, never return. Skip if visitor opens with a specific question<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">2<\/td><td><strong>Acknowledge<\/strong><\/td><td>Validate why their challenge is hard \u2014 one sentence<\/td><td>Move to Solution after one clarifier (if needed)<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">3<\/td><td><strong>Solution<\/strong><\/td><td>Match problem to capability. Cite proof points<\/td><td>Primary operating state. Go deeper, not wider. Never repeat.<\/td><\/tr><tr><td class=\"has-text-align-center\" data-align=\"center\">4<\/td><td><strong>Intent<\/strong><\/td><td>Booking CTA<\/td><td>Only on explicit buying signals. <code>[BOOK_CTA]<\/code> emitted once maximum<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The critical design decision is the <strong>low-energy reply handler<\/strong>. When a visitor responds with &#8220;ok,&#8221; &#8220;sure,&#8221; &#8220;cool,&#8221; or &#8220;thanks&#8221; after receiving a solution, most chatbots interpret that as engagement and push for a meeting.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It&#8217;s not engagement. It&#8217;s politeness.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The system prompt explicitly tells the model: this is NOT buying intent. Instead of moving to State 4 (booking), the model should offer one additional insight \u2014 a related proof point, a different angle, or a qualifying question. If the visitor gives two consecutive low-energy replies, the model offers a graceful exit.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is the difference between an agent that feels like a senior advisor and one that feels like a used car salesman.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Pillar 3: Graceful Degradation<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The agent has a clear hierarchy of degradation, and every level serves the visitor professionally:<\/p>\n\n\n\n<figure class=\"wp-block-table is-style-stripes\"><table class=\"has-fixed-layout\"><thead><tr><th>Condition<\/th><th>What the Visitor Sees<\/th><\/tr><\/thead><tbody><tr><td>Everything works<\/td><td>Full agent response with optional booking CTA<\/td><\/tr><tr><td>Cache missing<\/td><td>Full agent response (costs more, but visitor doesn&#8217;t notice)<\/td><\/tr><tr><td>Model call fails<\/td><td>&#8220;I&#8217;m having a brief issue. Let&#8217;s connect you with our team directly.&#8221; + booking CTA<\/td><\/tr><tr><td>Session prompt cap reached<\/td><td>Lead capture form + booking CTA<\/td><\/tr><tr><td>Monthly budget exhausted<\/td><td>Professional message + direct booking link<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">The visitor <strong>never<\/strong> sees a stack trace, an error code, or a blank response. Every failure mode routes to a human handoff.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Error Handling Is Not an Afterthought<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The error handling in this agent is deliberately designed to communicate cost impact to the engineering team while protecting the visitor experience:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>except Exception as e:\n    return ({\n        \"reply\": \"I'm having a brief issue. Let's connect you with our team directly.\",\n        \"cta_html\": consultation_cta(),\n        \"tier\": \"Error\",\n        \"model_called\": False,\n        \"error_detail\": str(e)&#91;:200],\n    }, 200, headers)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The response returns HTTP 200 \u2014 not 500. The visitor gets a professional message. The <code>error_detail<\/code> field is truncated to 200 characters so it&#8217;s useful for debugging without ever leaking project IDs, paths, or credentials.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">In the cache refresh module, the error log message literally says: <em>&#8220;agent falls back to inline (full-price) context.&#8221;<\/em> That one sentence tells the on-call engineer exactly what&#8217;s at stake \u2014 not just &#8220;something failed,&#8221; but &#8220;something failed and it&#8217;s costing you 10x more per request until you fix it.&#8221;<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Cost Optimization: Context Caching<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The agent&#8217;s knowledge base is a ~8,000-token document containing service descriptions, proof points, competitive positioning, and objection handling scripts. Without caching, this document is sent with every single request at full input token pricing.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Context caching changes the economics entirely.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">How It Works<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">A scheduled Cloud Function runs daily and creates a Gemini context cache with a 25-hour TTL (providing a 1-hour buffer beyond the daily refresh cycle). The cache includes both the system prompt and the site content. The cache name is stored in Firestore.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">At runtime, the agent reads the cache name from Firestore and passes it to the model config. The site content tokens are now billed at the cached rate 1\/10th of the standard price.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The Fallback<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">If the cache is missing (expired, creation failed, first deployment), the agent falls back to inline context. It constructs the system instruction with the site content embedded directly:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>cache_name = get_cache_name()\nif cache_name:\n    cfg = types.GenerateContentConfig(\n        max_output_tokens=MAX_OUTPUT_TOKENS,\n        temperature=0.3,\n        cached_content=cache_name,\n    )\nelse:\n    cfg = types.GenerateContentConfig(\n        max_output_tokens=MAX_OUTPUT_TOKENS,\n        temperature=0.3,\n        system_instruction=f\"{SYSTEM_PROMPT}\\n\\nSITE CONTENT:\\n{SITE_CONTEXT}\",\n    )\nresp = client.models.generate_content(model=MODEL, contents=contents, config=cfg)\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The agent works in both modes. It just costs more without the cache. And because the budget governance tracks cached vs. non-cached tokens separately, the cost difference is visible in the per-request telemetry.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Cache Name in Firestore, Not in Code<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The cache name is stored in Firestore, not hardcoded in the agent&#8217;s configuration. This enables zero-downtime cache rotation:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>New cache created with updated site content<\/li>\n\n\n\n<li>Firestore config updated atomically<\/li>\n\n\n\n<li>Next agent request picks up the new cache<\/li>\n\n\n\n<li>Old cache expires naturally<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">No redeployment required.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Security<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">Bot Protection<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Every request includes a Cloudflare Turnstile token. The server verifies it before processing:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def verify_turnstile(token, remoteip=None):\n    if not TURNSTILE_SECRET:\n        return True  # skip in dev\n    try:\n        r = _rq.post(\n            \"https:\/\/challenges.cloudflare.com\/turnstile\/v0\/siteverify\",\n            data={\"secret\": TURNSTILE_SECRET, \"response\": token, \"remoteip\": remoteip},\n            timeout=10,\n        )\n        return bool(r.json().get(\"success\", False))\n    except Exception:\n        return False  # Fail closed\n<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Note: the function <strong>fails closed<\/strong>. If Turnstile verification fails for any reason (network error, timeout, malformed response), the request is rejected. This is a deliberate security decision \u2014 we&#8217;d rather occasionally block a legitimate visitor than allow bots to drain our budget.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">No Conversation Storage on the Server<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">The server is stateless regarding conversation content. History is managed on the client side and sent with each request. The server stores only metadata \u2014 prompt count, budget spend, lead captures. Never conversation text.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This means there&#8217;s no server-side PII to protect, breach, or comply with \u2014 the client controls its own context.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">The Widget<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The frontend is a single HTML file. No React. No npm. No build step. No CDN dependency. Paste it before <code>&lt;\/body&gt;<\/code> on any page.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is a deliberate architectural choice. A React-based chat widget would add 40-150KB of framework code to every page load. Our widget is ~3KB. At scale, that&#8217;s bandwidth cost you&#8217;re paying on every page load for every visitor \u2014 not just the ones who open the chat.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Rotating Teasers<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Instead of a static &#8220;Chat with us&#8221; button, the widget shows a random teaser bubble after 4 seconds \u2014 once per browser session. Each teaser surfaces a specific proof point or pain point:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p class=\"wp-block-paragraph\">\ud83e\udd16 <strong>Hi!<\/strong> Most AI agents run without cost controls. Ours don&#8217;t. Ask me why.<\/p>\n<\/blockquote>\n\n\n\n<p class=\"wp-block-paragraph\">Clicking the teaser opens the chat AND sends the associated question automatically. The visitor gets value immediately \u2014 no &#8220;How can I help you today?&#8221; preamble.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Deep Linking<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Any <code>&lt;a href=\"#chat\"&gt;<\/code> link on the page opens the widget. This means you can put &#8220;Talk to our AI advisor&#8221; links in your navigation, inline content, CTAs \u2014 anywhere. They all open the same chat panel.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Prompt Duplication: An Architectural Trade-off<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">The system prompt appears in three files: the core agent, the CLI cache setup script, and the scheduled cache refresh function.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This is intentional, and it&#8217;s worth explaining why we chose duplication over abstraction.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Each module deploys independently as a separate Cloud Function. If we extracted the prompt into a shared import, updating the prompt would require redeploying all three functions simultaneously. A version mismatch between the cache (created with prompt version A) and the agent (running prompt version B) would produce inconsistent behavior.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The alternative \u2014 storing the prompt in Firestore and loading it at runtime \u2014 adds a network dependency to cold start and introduces a new failure mode.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We chose the trade-off we can manage: manual synchronization of three files, with a comment in each one that says <code>\"MUST be identical.\"<\/code> It&#8217;s not elegant. It&#8217;s correct.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s in the Repo<\/h2>\n\n\n\n<figure class=\"wp-block-table is-style-stripes\"><table class=\"has-fixed-layout\"><thead><tr><th>Module<\/th><th>Purpose<\/th><\/tr><\/thead><tbody><tr><td><code>sales-agent\/main.py<\/code><\/td><td>Core conversational agent with 5-layer guardrail pipeline<\/td><\/tr><tr><td><code>sales-agent\/cache_setup.py<\/code><\/td><td>CLI tool for manual cache creation<\/td><\/tr><tr><td><code>capture-lead\/main.py<\/code><\/td><td>Lead capture with email validation and CRM webhook<\/td><\/tr><tr><td><code>refresh-cache\/main.py<\/code><\/td><td>Scheduled context cache refresh<\/td><\/tr><tr><td><code>monitor-budget\/main.py<\/code><\/td><td>Budget threshold monitor (runs every 4h)<\/td><\/tr><tr><td><code>reset-budget\/main.py<\/code><\/td><td>Monthly budget reset<\/td><\/tr><tr><td><code>widget\/widget.html<\/code><\/td><td>Self-contained chat widget<\/td><\/tr><tr><td><code>scripts\/<\/code><\/td><td>GCP API enablement and Firestore setup<\/td><\/tr><tr><td><code>site_content_template.txt<\/code><\/td><td>Agent knowledge base template with working example<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">Every file is annotated with inline comments explaining the architectural decision behind each section \u2014 including the failure mode it prevents.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What This Architecture Is Not<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">This is not a general-purpose agent framework. It&#8217;s not LangChain. It&#8217;s not trying to be.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">It&#8217;s a set of patterns for building <strong>specific, bounded, production-grade AI agents<\/strong> that operate within defined constraints. The patterns are:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Budget governance with per-request cost tracking and multi-tier enforcement<\/strong><\/li>\n\n\n\n<li><strong>Behavioral guardrails enforced in code, not just in prompts<\/strong><\/li>\n\n\n\n<li><strong>Graceful degradation that never shows a visitor an error<\/strong><\/li>\n\n\n\n<li><strong>Cost optimization through context caching with automatic fallback<\/strong><\/li>\n\n\n\n<li><strong>Security through Turnstile verification, input validation, and output scrubbing<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">If you&#8217;re building a research prototype or a hackathon demo, you don&#8217;t need any of this.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you&#8217;re building an agent that will run in production, handle real conversations, and show up on a real invoice \u2014 you need all of it.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">What&#8217;s Next<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">This is the first agent in the Cognitive Work Architecture repo. The architecture patterns \u2014 budget governance, behavioral guardrails, graceful degradation \u2014 are designed to be applied to any agent, not just sales.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The inline comments in the code document every decision with the failure mode it prevents. We encourage you to read them, disagree with them, and build on them.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>The architecture is the moat. The code is open.<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>GitHub:<\/strong> <a href=\"https:\/\/github.com\/Cuciu\/cognitive-work-architecture\/tree\/main\/site-sales-agent\" data-type=\"link\" data-id=\"https:\/\/github.com\/Cuciu\/cognitive-work-architecture\/tree\/main\/site-sales-agent\" target=\"_blank\" rel=\"noreferrer noopener\">Cognitive-work-architecture\/sales-agent<\/a><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p class=\"wp-block-paragraph\"><em>This post is part of the Cognitive Work Architecture series \u2014 exploring how to build AI agents that operate with the same governance, accountability, and cost discipline you&#8217;d expect from any production enterprise system.<\/em><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><em>Alex Cuciurean is the founder of Sky Alleys, where the Cognitive Work Architecture powers enterprise AI deployments across cloud, manufacturing, and advisory practices.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Most AI agents are built to be impressive. This one was built to be accountable. There&#8217;s a gap in the AI agent [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":9137,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[201,5,781,71,66],"tags":[811,803,515,802,809,808,500,801,386,804,805,806,810,807,717],"class_list":["post-9136","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ai","category-cloud","category-cognitive-work-architecture","category-google-cloud-functions","category-google-cloud-platform","tag-5-layer-behavioral-guardrails-enforced-in-code","tag-ai-agent-framework","tag-ai-governance","tag-ai-guardrails","tag-and-graceful-degradation-production-code-running-live-not-a-demo-tags-ai-agents","tag-budget-governance","tag-cognitive-work-architecture","tag-conversational-ai","tag-finops","tag-focus-keyphrase-ai-agent-guardrails-and-budget-governance-slug-cognitive-work-architecture-open-source-ai-agent-meta-description-open-source-ai-agent-with-per-request-budget-governance","tag-gemini","tag-google-cloud-2","tag-llm-cost-optimization","tag-open-source","tag-production-ai"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Building an AI Agent That Knows Its Own Cost: Open-Sourcing the Cognitive Work Architecture - Sky Alleys<\/title>\n<meta name=\"description\" content=\"Open-source AI agent with per-request budget governance, 5-layer behavioral guardrails enforced in code, and graceful degradation. Production code running live \u2014 not a demo.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.skyalleys.com\/index.php\/cognitive-work-architecture\/cognitive-work-architecture-open-source-ai-agent\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Building an AI Agent That Knows Its Own Cost: Open-Sourcing the Cognitive Work Architecture - Sky Alleys\" \/>\n<meta property=\"og:description\" content=\"Open-source AI agent with per-request budget governance, 5-layer behavioral guardrails enforced in code, and graceful degradation. Production code running live \u2014 not a demo.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.skyalleys.com\/index.php\/cognitive-work-architecture\/cognitive-work-architecture-open-source-ai-agent\/\" \/>\n<meta property=\"og:site_name\" content=\"Sky Alleys\" \/>\n<meta property=\"article:published_time\" content=\"2026-11-10T04:52:51+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-11-10T04:52:56+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.skyalleys.com\/wp-content\/uploads\/2026\/11\/image-2.png\" \/>\n\t<meta property=\"og:image:width\" content=\"929\" \/>\n\t<meta property=\"og:image:height\" content=\"873\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Alex\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Alex\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"13 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.skyalleys.com\\\/index.php\\\/cognitive-work-architecture\\\/cognitive-work-architecture-open-source-ai-agent\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.skyalleys.com\\\/index.php\\\/cognitive-work-architecture\\\/cognitive-work-architecture-open-source-ai-agent\\\/\"},\"author\":{\"name\":\"Alex\",\"@id\":\"https:\\\/\\\/www.skyalleys.com\\\/#\\\/schema\\\/person\\\/af17d91196c915ffb289c194827c4616\"},\"headline\":\"Building an AI Agent That Knows Its Own Cost: Open-Sourcing the Cognitive Work Architecture\",\"datePublished\":\"2026-11-10T04:52:51+00:00\",\"dateModified\":\"2026-11-10T04:52:56+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.skyalleys.com\\\/index.php\\\/cognitive-work-architecture\\\/cognitive-work-architecture-open-source-ai-agent\\\/\"},\"wordCount\":2743,\"commentCount\":0,\"image\":{\"@id\":\"https:\\\/\\\/www.skyalleys.com\\\/index.php\\\/cognitive-work-architecture\\\/cognitive-work-architecture-open-source-ai-agent\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.skyalleys.com\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/image-2.png\",\"keywords\":[\"5-layer behavioral guardrails enforced in code\",\"AI Agent Framework\",\"AI Governance\",\"AI Guardrails\",\"and graceful degradation. Production code running live \u2014 not a demo. Tags: AI Agents\",\"Budget Governance\",\"Cognitive Work Architecture\",\"Conversational AI\",\"FinOps\",\"Focus keyphrase: AI agent guardrails and budget governance Slug: cognitive-work-architecture-open-source-ai-agent Meta description: Open-source AI agent with per-request budget governance\",\"Gemini\",\"Google Cloud\",\"LLM Cost Optimization\",\"Open Source\",\"Production AI\"],\"articleSection\":[\"AI\",\"Cloud\",\"Cognitive Work Architecture\",\"Google Cloud Functions\",\"Google Cloud Platform\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.skyalleys.com\\\/index.php\\\/cognitive-work-architecture\\\/cognitive-work-architecture-open-source-ai-agent\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.skyalleys.com\\\/index.php\\\/cognitive-work-architecture\\\/cognitive-work-architecture-open-source-ai-agent\\\/\",\"url\":\"https:\\\/\\\/www.skyalleys.com\\\/index.php\\\/cognitive-work-architecture\\\/cognitive-work-architecture-open-source-ai-agent\\\/\",\"name\":\"Building an AI Agent That Knows Its Own Cost: Open-Sourcing the Cognitive Work Architecture - Sky Alleys\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.skyalleys.com\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.skyalleys.com\\\/index.php\\\/cognitive-work-architecture\\\/cognitive-work-architecture-open-source-ai-agent\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.skyalleys.com\\\/index.php\\\/cognitive-work-architecture\\\/cognitive-work-architecture-open-source-ai-agent\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.skyalleys.com\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/image-2.png\",\"datePublished\":\"2026-11-10T04:52:51+00:00\",\"dateModified\":\"2026-11-10T04:52:56+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/www.skyalleys.com\\\/#\\\/schema\\\/person\\\/af17d91196c915ffb289c194827c4616\"},\"description\":\"Open-source AI agent with per-request budget governance, 5-layer behavioral guardrails enforced in code, and graceful degradation. Production code running live \u2014 not a demo.\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.skyalleys.com\\\/index.php\\\/cognitive-work-architecture\\\/cognitive-work-architecture-open-source-ai-agent\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.skyalleys.com\\\/index.php\\\/cognitive-work-architecture\\\/cognitive-work-architecture-open-source-ai-agent\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.skyalleys.com\\\/index.php\\\/cognitive-work-architecture\\\/cognitive-work-architecture-open-source-ai-agent\\\/#primaryimage\",\"url\":\"https:\\\/\\\/www.skyalleys.com\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/image-2.png\",\"contentUrl\":\"https:\\\/\\\/www.skyalleys.com\\\/wp-content\\\/uploads\\\/2026\\\/11\\\/image-2.png\",\"width\":929,\"height\":873,\"caption\":\"The core agent pipeline: cache-first model call \u2192 5-layer output processing \u2192 per-request cost tracking. Every behavioral rule is enforced in code, not just prompted.\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.skyalleys.com\\\/index.php\\\/cognitive-work-architecture\\\/cognitive-work-architecture-open-source-ai-agent\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.skyalleys.com\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Building an AI Agent That Knows Its Own Cost: Open-Sourcing the Cognitive Work Architecture\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.skyalleys.com\\\/#website\",\"url\":\"https:\\\/\\\/www.skyalleys.com\\\/\",\"name\":\"Sky Alleys\",\"description\":\"Business Development as a Service and Expert Led Delivery\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.skyalleys.com\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.skyalleys.com\\\/#\\\/schema\\\/person\\\/af17d91196c915ffb289c194827c4616\",\"name\":\"Alex\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/c191643bf88ff2825b0a73c636b3db69adc1e24bfbb2c72a22aab9917f4eb94e?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/c191643bf88ff2825b0a73c636b3db69adc1e24bfbb2c72a22aab9917f4eb94e?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/c191643bf88ff2825b0a73c636b3db69adc1e24bfbb2c72a22aab9917f4eb94e?s=96&d=mm&r=g\",\"caption\":\"Alex\"}}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Building an AI Agent That Knows Its Own Cost: Open-Sourcing the Cognitive Work Architecture - Sky Alleys","description":"Open-source AI agent with per-request budget governance, 5-layer behavioral guardrails enforced in code, and graceful degradation. Production code running live \u2014 not a demo.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.skyalleys.com\/index.php\/cognitive-work-architecture\/cognitive-work-architecture-open-source-ai-agent\/","og_locale":"en_US","og_type":"article","og_title":"Building an AI Agent That Knows Its Own Cost: Open-Sourcing the Cognitive Work Architecture - Sky Alleys","og_description":"Open-source AI agent with per-request budget governance, 5-layer behavioral guardrails enforced in code, and graceful degradation. Production code running live \u2014 not a demo.","og_url":"https:\/\/www.skyalleys.com\/index.php\/cognitive-work-architecture\/cognitive-work-architecture-open-source-ai-agent\/","og_site_name":"Sky Alleys","article_published_time":"2026-11-10T04:52:51+00:00","article_modified_time":"2026-11-10T04:52:56+00:00","og_image":[{"width":929,"height":873,"url":"https:\/\/www.skyalleys.com\/wp-content\/uploads\/2026\/11\/image-2.png","type":"image\/png"}],"author":"Alex","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Alex","Est. reading time":"13 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.skyalleys.com\/index.php\/cognitive-work-architecture\/cognitive-work-architecture-open-source-ai-agent\/#article","isPartOf":{"@id":"https:\/\/www.skyalleys.com\/index.php\/cognitive-work-architecture\/cognitive-work-architecture-open-source-ai-agent\/"},"author":{"name":"Alex","@id":"https:\/\/www.skyalleys.com\/#\/schema\/person\/af17d91196c915ffb289c194827c4616"},"headline":"Building an AI Agent That Knows Its Own Cost: Open-Sourcing the Cognitive Work Architecture","datePublished":"2026-11-10T04:52:51+00:00","dateModified":"2026-11-10T04:52:56+00:00","mainEntityOfPage":{"@id":"https:\/\/www.skyalleys.com\/index.php\/cognitive-work-architecture\/cognitive-work-architecture-open-source-ai-agent\/"},"wordCount":2743,"commentCount":0,"image":{"@id":"https:\/\/www.skyalleys.com\/index.php\/cognitive-work-architecture\/cognitive-work-architecture-open-source-ai-agent\/#primaryimage"},"thumbnailUrl":"https:\/\/www.skyalleys.com\/wp-content\/uploads\/2026\/11\/image-2.png","keywords":["5-layer behavioral guardrails enforced in code","AI Agent Framework","AI Governance","AI Guardrails","and graceful degradation. Production code running live \u2014 not a demo. Tags: AI Agents","Budget Governance","Cognitive Work Architecture","Conversational AI","FinOps","Focus keyphrase: AI agent guardrails and budget governance Slug: cognitive-work-architecture-open-source-ai-agent Meta description: Open-source AI agent with per-request budget governance","Gemini","Google Cloud","LLM Cost Optimization","Open Source","Production AI"],"articleSection":["AI","Cloud","Cognitive Work Architecture","Google Cloud Functions","Google Cloud Platform"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.skyalleys.com\/index.php\/cognitive-work-architecture\/cognitive-work-architecture-open-source-ai-agent\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.skyalleys.com\/index.php\/cognitive-work-architecture\/cognitive-work-architecture-open-source-ai-agent\/","url":"https:\/\/www.skyalleys.com\/index.php\/cognitive-work-architecture\/cognitive-work-architecture-open-source-ai-agent\/","name":"Building an AI Agent That Knows Its Own Cost: Open-Sourcing the Cognitive Work Architecture - Sky Alleys","isPartOf":{"@id":"https:\/\/www.skyalleys.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.skyalleys.com\/index.php\/cognitive-work-architecture\/cognitive-work-architecture-open-source-ai-agent\/#primaryimage"},"image":{"@id":"https:\/\/www.skyalleys.com\/index.php\/cognitive-work-architecture\/cognitive-work-architecture-open-source-ai-agent\/#primaryimage"},"thumbnailUrl":"https:\/\/www.skyalleys.com\/wp-content\/uploads\/2026\/11\/image-2.png","datePublished":"2026-11-10T04:52:51+00:00","dateModified":"2026-11-10T04:52:56+00:00","author":{"@id":"https:\/\/www.skyalleys.com\/#\/schema\/person\/af17d91196c915ffb289c194827c4616"},"description":"Open-source AI agent with per-request budget governance, 5-layer behavioral guardrails enforced in code, and graceful degradation. Production code running live \u2014 not a demo.","breadcrumb":{"@id":"https:\/\/www.skyalleys.com\/index.php\/cognitive-work-architecture\/cognitive-work-architecture-open-source-ai-agent\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.skyalleys.com\/index.php\/cognitive-work-architecture\/cognitive-work-architecture-open-source-ai-agent\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.skyalleys.com\/index.php\/cognitive-work-architecture\/cognitive-work-architecture-open-source-ai-agent\/#primaryimage","url":"https:\/\/www.skyalleys.com\/wp-content\/uploads\/2026\/11\/image-2.png","contentUrl":"https:\/\/www.skyalleys.com\/wp-content\/uploads\/2026\/11\/image-2.png","width":929,"height":873,"caption":"The core agent pipeline: cache-first model call \u2192 5-layer output processing \u2192 per-request cost tracking. Every behavioral rule is enforced in code, not just prompted."},{"@type":"BreadcrumbList","@id":"https:\/\/www.skyalleys.com\/index.php\/cognitive-work-architecture\/cognitive-work-architecture-open-source-ai-agent\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.skyalleys.com\/"},{"@type":"ListItem","position":2,"name":"Building an AI Agent That Knows Its Own Cost: Open-Sourcing the Cognitive Work Architecture"}]},{"@type":"WebSite","@id":"https:\/\/www.skyalleys.com\/#website","url":"https:\/\/www.skyalleys.com\/","name":"Sky Alleys","description":"Business Development as a Service and Expert Led Delivery","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.skyalleys.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/www.skyalleys.com\/#\/schema\/person\/af17d91196c915ffb289c194827c4616","name":"Alex","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/c191643bf88ff2825b0a73c636b3db69adc1e24bfbb2c72a22aab9917f4eb94e?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/c191643bf88ff2825b0a73c636b3db69adc1e24bfbb2c72a22aab9917f4eb94e?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/c191643bf88ff2825b0a73c636b3db69adc1e24bfbb2c72a22aab9917f4eb94e?s=96&d=mm&r=g","caption":"Alex"}}]}},"wps_subtitle":"","post_mailing_queue_ids":[],"_links":{"self":[{"href":"https:\/\/www.skyalleys.com\/index.php\/wp-json\/wp\/v2\/posts\/9136","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.skyalleys.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.skyalleys.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.skyalleys.com\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.skyalleys.com\/index.php\/wp-json\/wp\/v2\/comments?post=9136"}],"version-history":[{"count":1,"href":"https:\/\/www.skyalleys.com\/index.php\/wp-json\/wp\/v2\/posts\/9136\/revisions"}],"predecessor-version":[{"id":9139,"href":"https:\/\/www.skyalleys.com\/index.php\/wp-json\/wp\/v2\/posts\/9136\/revisions\/9139"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.skyalleys.com\/index.php\/wp-json\/wp\/v2\/media\/9137"}],"wp:attachment":[{"href":"https:\/\/www.skyalleys.com\/index.php\/wp-json\/wp\/v2\/media?parent=9136"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.skyalleys.com\/index.php\/wp-json\/wp\/v2\/categories?post=9136"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.skyalleys.com\/index.php\/wp-json\/wp\/v2\/tags?post=9136"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}