MODULE 3.7

🏢 AI in Production — Enterprise Scale

When ten teams use AI, each with its own key, prompt, and account, the company doesn’t have AI: it has ten risks. This module shows you how to turn scattered projects into an internal platform — gateway, identity, auditing, SLAs, FinOps, and adoption — with configurations and checklists you can take to your next architecture meeting.

7
Topics
~55
Minutes
Advanced
Level
Architecture
Type
0%
0 of 0 topics read · Section 1 of 7

Detailed content

1

🏗️ Internal AI Platform

A company’s first year with AI is usually a collection of pilots: customer support tests an assistant, legal summarizes contracts, and engineering uses a coding agent. Each pilot solves its own problem and creates the same five problems all over again: scattered keys, no central record, invisible costs, uncontrolled personal data, and no way to switch models without rewriting the app. The solution is to treat AI as a platform: a set of shared services that every project uses, instead of each project reinventing them.

Internal platform here means the same thing it does in software engineering: a product maintained by one team for other teams. It provides a “paved road” (paved road) — the easy way to do things right. If the right path is harder than the shortcut, teams take the shortcut, and the platform becomes just another ignored rule.

What it is

An internal AI platform is the shared layer between applications and models: a gateway that handles all calls, shared services (context, evaluation, tools), and three cross-cutting controls — identity, auditing, and cost.

Customer support Legal Sales Engineering Model gateway routing · limits · cache · fallback · logging Context and RAG permissioned documents Continuous evaluation before-and-after tests Tools (MCP) access to internal systems External models under contract and data terms Local models / private cloud sensitive data stays inside Identity SSO · roles Auditing logs · traces FinOps cost by team
How to read: read from top to bottom. Department apps never talk directly to a model: everything goes through the gateway (blue). The dashed boxes on the right aren’t a layer — they span all of them. If a project bypasses the gateway, it slips out from under all three controls at once.

✓ Signs of a platform

  • ✓A new app goes into production in days, reusing the gateway, logs, and evaluation.
  • ✓Switching models means changing a route in the gateway, not rewriting code.
  • ✓A team owns the platform, with a roadmap and support channel.
  • ✓Any manager can see their own department’s costs and usage without asking anyone.

✗ Signs of scattered projects

  • ✗API keys in each team’s environment variables, with no rotation.
  • ✗No one can say which models the company uses today.
  • ✗The bill arrives, and the question is, “Who spent this?”
  • ✗Each team has its own rule for masking personal data — or none at all.

Why learn

A platform’s cost is paid once; the cost of not having one is paid with every new project, in rework, incidents, and audits. For an architect, the question is no longer “which model should we use?” but “how can every team use any model safely without asking me for permission every time?”

Key concepts

Internal platform
a product for which the teams are the customers
Paved road
the right way is the easiest way
Shared service
built once, used by everyone
Cross-cutting control
identity, auditing, cost
2

🚪 Model gateway

O model gateway is a proxy: apps call an internal address using a platform key, and the gateway decides which model gets the call. Since almost all providers and local servers accept an OpenAI-compatible “chat completions” API format, the app’s code is written once and the gateway translates it. Open-source tools like LiteLLM play this role; cloud providers and API management vendors have their own versions.

Each call goes through five steps: authenticate the key, apply the limit for the team, check the cache, choose the route (and the fallback, if the primary model fails) and log everything. A route is the logical name ("internal-fast," "external-powerful") the app requests; the actual model behind it can change without the app knowing.

What it is

A single entry point for all the company’s models. It separates the logical name the app requests from the physical model that responds, and applies authentication, limits, caching, fallback, and logging to every call.

App request team key Gateway 1 · authenticate 2 · apply limit 3 · check cache 4 · choose route 5 · log Local model simple task, sensitive data External model complex task Fallback if the primary fails
How to read: the app only knows the box on the left and the route name. All the intelligence about "where it goes" lives in the gateway. Notice that the fallback (dashed line) is an architecture decision: deciding in advance which model takes over when the primary goes down avoids improvising during an incident.

New term

Proxy is an intermediary server that receives a call in place of its destination and forwards it. Fallback is the automatic alternative when the first option fails. Semantic cache returns an already calculated answer to similar questions—useful for FAQs, risky when the answer depends on the user.

Try this: a local gateway with two routes and a fallback (LiteLLM proxy).

# config.yaml — install with: pip install 'litellm[proxy]'
# run with:  litellm --config config.yaml --port 4000
model_list:
  - model_name: interno-rapido          # logical name the app requests
    litellm_params:
      model: ollama/llama3.2            # local, free model
      api_base: http://localhost:11434
      rpm: 120                          # call limit per minute on this route
  - model_name: externo-forte
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_key: os.environ/ANTHROPIC_API_KEY
      rpm: 30

router_settings:
  fallbacks:
    - externo-forte: ["interno-rapido"] # if the external model fails, fall back to the local one
  num_retries: 2

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY  # the key apps use

# Test (the app only knows the route, never the actual model):
# curl http://localhost:4000/v1/chat/completions \
#   -H "Authorization: Bearer $LITELLM_MASTER_KEY" -H "Content-Type: application/json" \
#   -d '{"model":"interno-rapido","messages":[{"role":"user","content":"say ok"}]}'

How to check: with Ollama running, the test curl should return a response through the route interno-rapido. Then, without the variable ANTHROPIC_API_KEY, call externo-forte: the response should come from the local model (fallback), and the proxy log should show the failure and the switch. Configuration key names change between versions; check the documentation for the version you installed.

💡 Tip

Give routes names based on capability ("fast," "powerful," "vision," "sensitive"), never the provider. When you replace the model behind "powerful," no app needs to know—and you can negotiate with providers on more equal terms.

Why learn

Models change every few months, and so do prices. Without a gateway, every switch becomes a migration project across ten apps. With a gateway, it’s one configuration line tested in one place—and that same point becomes the foundation for auditing, limits, and cost tracking, which come next.

Key concepts

Logical route
capability name, not provider name
Fallback
automatic plan B
Limit per team
calls and tokens per minute
Compatible API
one format, many models
3

🔐 Identity and access

At scale, the security question isn’t "is the model secure?" It’s "on whose behalf is this call being made, and what can that person see?". An HR assistant that searches documents must not return another employee’s pay stub just because it was in the index. AI inherits the permissions of whoever makes the request—or it should.

With agents, a second kind of identity comes into play: the agent’s own. An agent that reads the CRM, opens tickets, and sends emails needs its own service identity with minimum permissions, credentials that expire, and a human responsible for it. Never use the personal key of whoever created it.

What it is

It’s the set of rules that ties each AI call to an identified person or agent, applies that identity’s role to the data and tools accessed, and maintains the minimum privileges needed for the task.

New term

SSO (single sign-on) means signing in once with your corporate account to access multiple systems. RBAC is role-based access control: an "HR analyst" can see X, a "manager" can see Y. Least privilege means giving only the access needed for the task, and nothing more.

IdentityHow it authenticatesGolden rule
Person in internal chatCorporate SSODocument searches respect the user’s permissions, which are applied before results reach the model.
Team appGateway key per appOne key per app and environment; scheduled rotation; revocation within minutes.
Autonomous agentService account with short-lived credentialsMinimum scope for each tool; irreversible actions require human approval.
Model providerContract and key stored in the gatewayData usage terms reviewed by legal; the key never leaves the vault.

✓ Do

  • ✓Filter documents by the user’s permissions before retrieval, not after the response.
  • ✓Mask personal data at the gateway when the purpose doesn’t require it (the LGPD (Brazil’s data protection law) necessity principle).
  • ✓Assign a human owner to every agent and every key.

✗ Avoid

  • ✗Relying on the prompt (“don’t show salaries”) as an access control.
  • ✗A single index with all company documents and no permission metadata.
  • ✗Agents running with administrator credentials “to avoid errors.”

Why learn

The most likely leaks in corporate AI don’t come from sophisticated attacks on the model: they come from poorly inherited permissions. A prompt can be bypassed; a permission filter applied before retrieval can’t. Getting identity design right from the start prevents you from rebuilding the entire index after the first incident.

Key concepts

SSO
a corporate account
RBAC
role-based access
Service identity
the agent has its own account
Least privilege
only what’s necessary
4

📜 Auditing and traceability

A customer complains that the assistant promised a discount that doesn’t exist. The audit question is simple: which prompt version, with which model, documents, and tools, produced that response? If the platform can’t answer within minutes, it isn’t ready for production.

The central piece is the trace: a unique identifier that follows the request through every stage — gateway, retrieval, model, tools, output filter. Each stage becomes a span with a start time, end time, and attributes. The open standard OpenTelemetry already has conventions for generative AI calls, and tools like Langfuse and Arize Phoenix build this view for you.

What it is

Traceability is the ability to reconstruct any response: who requested it, with which configuration, what data went in, what the model and tools did, and how much it cost — while keeping only what’s necessary for only as long as necessary.

request (trace_id) gateway document retrieval model call tool: CRM output filter the model called a tool
How to read: The horizontal axis represents time. The top bar is the entire request; the bars below are the stages, each one a span. The tool (cyan) runs within the model call — that’s where an agent acts in the world, and it’s the span auditors look for most. When a response is slow, the longest bar shows where the bottleneck is.

Goal: a minimal audit log format for each call (one JSONL line).

{
  "ts": "2026-10-16T14:03:22Z",
  "trace_id": "<ID generated by the gateway>",
  "equipe": "customer support",
  "caso_de_uso": "support-response",
  "usuario_hash": "<hash of the employee ID, never the name>",
  "rota": "strong-external",
  "modelo_real": "<model that responded, including if it was a fallback>",
  "versao_prompt": "sac-v14",
  "documentos": ["<IDs of the passages used in the context>"],
  "ferramentas": ["crm.consultar_pedido"],
  "tokens_entrada": 1830,
  "tokens_saida": 412,
  "latencia_ms": 2240,
  "cache_hit": false,
  "dados_pessoais": "masked",
  "resultado": "accepted",
  "retencao_dias": <period defined with the DPO>
}

How to check: Choose a real response from yesterday and try to reconstruct it using only this log: can you find the prompt version, the documents, and the tool used? If you’re missing a field needed to answer, add it to the format. If a field stores free-form user text, ask the data protection officer (DPO) whether the purpose justifies it and for how long.

💡 Tip

Auditing and the LGPD pull in opposite directions: one calls for keeping everything, the other for keeping as little as possible. Resolve this by separating two levels — metadata (who, when, which version, cost) with longer retention, and content (the prompt and response text) with short retention, restricted access, and masking.

Why learn

Without traceability, every incident becomes one person’s word against another’s, and the only safe response is to shut the system down. With it, you can find the cause, fix the prompt version or the incorrect document, and show legal and the customer exactly what happened.

Key concepts

Trace
the end-to-end request
Span
a stage with timing and attributes
Prompt version
a prompt is version-controlled code
Retention
how long to keep it and why
5

📈 SLAs and reliability

An AI system can be “up” and still be broken: it responds quickly, with no HTTP errors, but its responses have gotten worse since yesterday’s model switch. That’s why AI reliability has three dimensions, not two: availability, latency, and quality. You can measure the third only if you continuously run an evaluation set — real questions with reference answers, rerun after every change.

New term

SLI is the measured indicator (e.g., latency at the 95th percentile). SLO is the internal target for it. SLA is the contractual commitment to the customer, with consequences if it’s missed — so the SLA should allow more room than the SLO. 95th percentile (p95) is the time within which 95% of responses are completed.

What it is

It means setting measurable targets for availability, latency, and quality for each use case, measuring continuously, and changing versions (model, prompt, index) only in stages with gates that check those targets.

DimensionTypical SLIHow to protect
AvailabilityProportion of calls without errorsFallback between providers; queues with retries; degraded mode.
Latencyp95 time to the first token and to the complete responseStreaming, a lighter route for simple tasks, cache.
QualityEvaluation set score; rate of accepted responsesEvaluation before each change; daily sampling in production.
SecurityResponses blocked by the filter; injection attempts detectedInput and output filters; alert when the rate shifts to a new level.
1 · Shadow runs in parallel 2 · Canary small slice 3 · Expansion larger slice 4 · Everyone new default version SLO? SLO? SLO? gate fails at any stage → return to the previous version (rollback)
How to read: A new version (model, prompt, or index) moves from left to right only if it passes the gate (diamond). In the shadow stage, it responds in parallel without the user seeing it, which lets you compare quality without risk. You decide the slice sizes; what matters is testing the way back (red) before you start.

💡 Tip

Pin the model version in the gateway whenever the provider allows it. A route pointing to an alias such as “latest” means the provider can swap out the model behind your back—and your quality SLO can change without any deployment on your part.

Why learn

Promising an SLA without measuring quality means promising something you don’t control. Teams that set SLOs across all three areas and make changes through gates can update models often without fear—and teams that don’t end up freezing the version out of concern and falling behind.

Key concepts

SLI · SLO · SLA
measurement, target, contract
p95
tail latency, not the average
Canary
new version on a slice
Rollback
rollback tested beforehand
6

💰 AI FinOps

FinOps is the practice of making technology costs visible to decision makers and ensuring those who consume it are accountable for them. In AI, costs are variable by nature: each call consumes tokens, and an agent stuck in a loop can spend a month’s budget in one afternoon. Cost per token is the provider’s metric; the business metric is cost per task resolved.

The levers are well known: route simple tasks to smaller or local models, use caching (including prompt caching, which several providers offer for repeated context), cut unnecessary context, batch work that isn’t urgent, and set step and spending limits for each agent. Before optimizing, though, you need to attribute: know which team and use case generated each dollar.

What it is

AI FinOps means measuring the cost of each call, attributing it to a team and use case, showing it to decision makers (showback) or charging it internally (chargeback), and optimizing for cost per outcome—not cost per token.

Try this: cost per team and per accepted task, based on the audit log from Topic 4.

#!/usr/bin/env python3
"""finops_ia.py — showback by team and use case.
Usage: python3 finops_ia.py auditoria.jsonl"""
import json, sys
from collections import defaultdict

# Price per 1 million tokens, in your contract currency.
# Replace the 0.0 values with the current pricing table; local models have infrastructure costs, not token costs.
PRECO = {
    "interno-rapido": {"entrada": 0.0, "saida": 0.0},
    "externo-forte":  {"entrada": 0.0, "saida": 0.0},  # <contract price>
}

agg = defaultdict(lambda: {"chamadas": 0, "custo": 0.0, "aceitas": 0, "cache": 0})
with open(sys.argv[1], encoding="utf-8") as f:
    for linha in f:
        r = json.loads(linha)
        p = PRECO.get(r["rota"], {"entrada": 0.0, "saida": 0.0})
        custo = (r["tokens_entrada"] * p["entrada"] + r["tokens_saida"] * p["saida"]) / 1e6
        a = agg[(r["equipe"], r["caso_de_uso"])]
        a["chamadas"] += 1
        a["custo"] += custo
        a["aceitas"] += r.get("resultado") == "aceito"
        a["cache"] += bool(r.get("cache_hit"))

print(f"{'equipe':14} {'caso de uso':18} {'chamadas':>8} {'custo':>10} {'custo/aceita':>12} {'cache':>6}")
for (equipe, caso), a in sorted(agg.items(), key=lambda kv: -kv[1]["custo"]):
    por_aceita = a["custo"] / a["aceitas"] if a["aceitas"] else float("nan")
    taxa_cache = a["cache"] / a["chamadas"]
    print(f"{equipe:14} {caso:18} {a['chamadas']:8} {a['custo']:10.2f} {por_aceita:12.4f} {taxa_cache:6.0%}")

How to check: Create a file with three lines in the format from Topic 4 (two from the same team, one accepted and one not), enter any price, and calculate it by hand. Cost per accepted task should be the line’s total cost divided by 1. A use case with a cost per accepted task far above the others is the first candidate for reviewing the route, context, or prompt.

✓ Levers that usually work

  • ✓Route by complexity: use the stronger model only when the task calls for it.
  • ✓Prompt caching for instructions and documents that repeat.
  • ✓Batch processing for work that can wait a few hours.
  • ✓Step and spending limits per agent run, with an alert.

✗ Pitfalls

  • ✗Cut costs by switching models without running the quality evaluation.
  • ✗Look only at the provider’s bill and forget idle GPUs, engineering, and human review.
  • ✗A fixed annual budget for usage that varies with adoption.

Why learn

The first AI budget cut almost never comes from a use case that failed; it comes from a bill nobody could explain. When you assign costs and measure them by outcome, you can defend the use cases that pay for themselves and end the ones that don’t, with the numbers in hand.

Key concepts

Showback
show costs to those who consume the service
Chargeback
charge internally
Cost per outcome
the metric that matters
Per-agent limit
step and spending limit
7

🌱 Company-wide adoption

A technically flawless platform that nobody uses is a cost with no return. And when the official platform is slow to grant access, people use whatever is at hand—personal accounts, browser extensions, free tools with unknown terms of use. This has a name: shadow AI, AI used outside the company’s control. Banning it doesn’t solve the problem; offering a better path does.

Adoption has three fronts: access (a secure assistant available to everyone, with clear rules about what can be pasted into it), training (short tracks by role and “champions” in each area who help their colleagues) and catalog (approved use cases, each with an owner, metric, and status, so no one reinvents what another team has already done).

What it is

It’s the work of bringing the platform into real-world use: providing secure access, training people by role, maintaining a catalog of use cases, and measuring usage, results, and satisfaction—reducing shadow AI by offering a better alternative, not through prohibition.

Weeks 1–2 · Baseline. Find out which AI tools are already being used (an anonymous survey works better than an audit) and measure the current metrics for candidate processes.

Weeks 3–4 · Secure access. Make the corporate assistant available through the gateway, with a one-page usage policy (what can and cannot be pasted).

Weeks 5–8 · Champions and tracks. One or two champions per area, a short track by role, and a regular time for questions.

Weeks 9–12 · Catalog and first review. Publish the use cases that worked, with an owner and a metric; compare them with the baseline; decide what to scale and what to stop.

Goal: platform readiness assessment and 90-day adoption plan.

Act as an AI platform architect and critical reviewer.
Company: <industry, size, approximate number of departments>
What’s already in place: <gateway? SSO? logs? evaluation? cost by team?>
AI tools currently in use (official and unofficial): <list>
Pilot use cases: <name · area · status · current metric>
Constraints: <LGPD, regulated industry, data that cannot leave the country, budget>

Deliver, in this order:
1. A readiness table with the rows Gateway, Identity, Auditing,
   SLOs, FinOps, Adoption—and the columns: current state | gap | risk if left as is | next action.
2. The 3 biggest shadow AI risks in my situation and the official alternative for each.
3. A 90-day plan in 4 phases, with a deliverable and a “done” criterion for each phase.
4. The adoption metrics I should measure. Don’t invent benchmark numbers:
   wherever a value is needed, write “measure baseline.”
5. What you assumed due to missing information, in a separate list.

How to check: Each table row must have a next action with a possible owner and deadline; if “implement governance” appears without saying what that means, ask for details. Check the list of assumptions: anything incorrect there invalidates the parts of the plan that depend on it. Don’t paste client names or personal data into the prompt.

Why learn

The value of AI in a company comes from many people using it well for small tasks, more than from one heroic project. The platform provides security; adoption delivers returns. Leaders who bring both together avoid the risks of shadow AI and the waste of an empty infrastructure.

Key concepts

Shadow AI
Uncontrolled AI
Champions
a point person in each area
Use case catalog
owner, metric, status
Baseline
measure before comparing

✅ Module summary

✓
A platform, not a project — shared services and a paved path for every team.
✓
Everything goes through the gateway — logical routes, limits, fallback, and logging in one place.
✓
Identity before search, a trace for every response — inherited permissions and the ability to reconstruct any response, with retention aligned with the LGPD.
✓
SLOs across three dimensions and cost per result — availability, latency, and quality; FinOps costs attributed by team.
✓
Adoption is part of the architecture — secure access, champions, and a catalog beat shadow AI.

Next module:

3.8 — AI Leadership and Strategy 🧭