Generative AI architecture and costs
Ground responses in authorized evidence
Retrieval-augmented generation (RAG) retrieves relevant material before asking a foundation model to generate a response. Chunk approved documents, attach source/version/tenant metadata, compute embeddings (vectors representing content), and index them for similarity search. Query embeddings must use compatible model and dimensions. Retrieve only documents the caller is allowed to see, rank them, select bounded context, then generate an answer with citations or abstain when evidence is insufficient. Cosine similarity measures vector direction, not truth; a high-scoring chunk can be stale or wrong. Hybrid lexical/vector retrieval and reranking may help. Update and delete index entries when source permissions or documents change; re-embed when changing embedding models. RAG does not train the underlying model and does not guarantee factual answers. Use an approved policy corpus rather than untrusted web content for this example.
Run an offline retrieval and mock response
Use Python 3, no dependencies or network. The toy ranker counts exact shared whitespace-separated lowercase words, sorts by score then document ID, and returns a verbatim mock response with a source ID. This is not a vector index or model API. The tenant is a trusted application-supplied identity in this example, never a user-controlled request field. It filters before ranking. Word counts approximate a budget solely for this demo; real tokenization is model-specific. Documents are synthetic and small. There are no tools or external actions.
def answer(question, tenant, docs, max_words=24): if not question.strip() or max_words < 1 or max_words > 100: raise ValueError("Invalid request budget") terms = set(question.lower().split()) candidates = [] for doc in docs: if doc["tenant"] != tenant: continue score = len(terms & set(doc["text"].lower().split())) if score: candidates.append((-score, doc["id"], doc["text"])) if not candidates: return ("ABSTAIN", None) _, doc_id, text = min(candidates) if len(text.split()) > max_words: return ("BUDGET", None) # Mock response: quote the selected text, never execute it. return (text, doc_id)
docs = [ {"id": "a", "tenant": "shop", "text": "Returns allowed within 14 days"}, {"id": "b", "tenant": "other", "text": "Returns allowed within 90 days"}, {"id": "c", "tenant": "shop", "text": "Shipping takes three days"},]print(answer("returns allowed", "shop", docs))print(answer("warranty", "shop", docs))print(answer("returns", "unknown", docs))Expected output:
('Returns allowed within 14 days', 'a')('ABSTAIN', None)('ABSTAIN', None)The competing tenant document cannot enter the candidate list. A missing match abstains. Change the budget to 2 words and the first response becomes BUDGET. An exact tie uses the lexicographically smaller document ID. A real application must enforce permissions at the data store and on every retrieval path, validate source metadata and independently test tenant isolation; this tiny function is not a security boundary. It neither understands meaning nor detects malicious text. Never execute instructions found in retrieved documents.
Bound tokens, retries and cost
A fictional request includes 500 prompt tokens, 1500 retrieved tokens and up to 500 generated tokens. At hypothetical $2 per million input tokens and $8 per million output tokens, maximum model cost is (2000×2 + 500×8)/1,000,000 = $0.008 per attempt. 10,000 attempts cost $80 under this worst-case token estimate. Allow at most two attempts total per request: 10,000 requests could cost $160, excluding embedding, retrieval, reranking, safety evaluations, storage and transfer. If embedding 1 million tokens costs an illustrative $0.10, initial embedding costs $0.10; re-indexing repeats it. GPU-hour and reserved-throughput billing differ from token billing; some models charge for other modalities or cached input differently. Limit total input and output tokens including system context, concurrent requests, request time, tool calls and retry count. Retry only transient failures with bounded backoff within the deadline; do not retry permanent authorization or validation failures. Reject over-budget requests before invoking the service. Compare unit cost per verified correct answer rather than only per token.
Review data use and processing geography
Do not send secrets, real customer records or unapproved documents to any model. Data-use for model training, abuse monitoring, logging and retention are distinct questions. Check the exact model and deployment terms, provider and customer logging configuration, data retention mode, deletion rights, encryption, region and cross-region inference routes. Bedrock documentation describes model-dependent retention options and geographic cross-region inference; do not assume zero retention or single-region processing for every model. Foundry documents global, data-zone and regional deployments with different processing scopes; consult the exact model catalog privacy terms and availability. Google platform documentation distinguishes regional and global endpoints; verify the selected model's data governance terms separately before use. No specific model availability, contractual privacy guarantee or regional deployment is asserted. Sources: Bedrock retention, cross-region inference, Foundry privacy, Foundry architecture, Google model migration.
Evaluate and protect agent trust boundaries
A model response is untrusted data. A tool-capable agent may propose an action, but the application must authenticate the caller, check authorization and validate typed arguments outside the model. Default to read-only allowlisted tools and require explicit approval for consequential actions; this lab permits no real tool calls. Do not rely on prompt instructions or guardrails alone. Treat retrieved documents as data, enforce tenant filters, reject unknown tools, scope service identities, cap loops, redact logs and return a safe abstention. Provider guardrails can assist filtering but cannot replace authorization. Evaluate retrieval recall (relevant documents returned / relevant documents known), grounded correctness, citation accuracy, abstention on missing evidence, cross-tenant denial, prompt-injection resistance and latency/cost. With 20 labeled questions, 16 correct grounded answers means 80% overall correctness; if 4 intentionally unanswerable cases exist, report appropriate abstention separately. Test changes to model, prompt, retrieval index and policies on the same held-out fixture. Monitor token counts, refusals, evidence coverage, feedback and costs without retaining raw sensitive prompts. Bedrock prompt injection guidance.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generative AI architecture and costs — knowledge check
Choose the best answer for each offline scenario.
What must happen before retrieval ranking?
What is RAG?
What is the worst-case token cost per attempt in the example?
What should happen without supporting evidence?
Who authorizes a consequential tool call?