MODULE 2.2

🏗️ Architecture of AI Applications

One API call can handle a script. A product needs more: layers, orchestration, provider switching, memory, caching, queues, observability, and a plan for when the model fails. Here, the model is just one piece — and you’ll learn to build the rest around it, with Python examples that run locally in Ollama.

7
Topics
~60
Minutes
Intermediate
Level
Architecture
Type
0%
0 of 0 topics read · Section 1 of 7

Detailed content

1

🏗️ The layers of an AI application

In Module 2.1, you called a model directly from the script. That works for testing, but it quickly breaks in a product: the provider changes its pricing, the model gets slow on a Friday, a thousand people use it at once, someone asks “what did I say yesterday?” The answer is architecture: separating the application into layers with clear responsibilities, so each problem is handled in one place.

The golden rule is the same as in traditional software: loose coupling. The interface doesn’t know which model is behind it; the business logic doesn’t know whether the response came from the cache or a GPU; switching providers means changing a setting. Coupling is how much one part depends on the details of another—the less coupling, the cheaper it is to make changes.

What it is

AI application architecture is the organization of a system into layers—interface, backend, orchestration, model gateway, and models—with two cross-cutting services: state (data and memory) and observability (logs, metrics, cost).

Interfaceweb, app, WhatsApp, integration Backendlogin, business rules, limits Orchestrationprompts, tools, RAG, validation Model gatewayrouting, fallback, cache, cost ModelsLocal Ollama · cloud APIs State and data sessions, memory, vectors, files Observability logs, traces, tokens, latency, cost
How to read: the request moves down from the interface to the model, and the response comes back along the same path. The highlighted layer, orchestration, is where the “intelligence” of your product lives. The two dashed boxes on the right aren’t steps: they span all the layers—every layer reads and writes state, and every layer generates logs.

✓ Signs of good architecture

  • ✓Switching models means changing a setting, not code.
  • ✓Prompts live in version-controlled files and have tests.
  • ✓Every model call goes through a single point.
  • ✓There’s a defined response for when the model fails.

✗ Warning signs

  • ✗SDK calls are scattered across dozens of files.
  • ✗The model name is hard-coded in several places.
  • ✗No one knows how much each feature costs.
  • ✗If the provider goes down, the customer sees a 500 error.

Why learn

Models change quickly: today’s best is replaced within months, and prices go up and down. If you couple your product to a specific model, you have to rewrite the system every time you switch. If you separate the layers, you can swap one part and keep going—and answer questions about cost, quality, and failures with data.

Key concepts

Layer
one clear responsibility
Coupling
dependence on others’ details
Orchestration
where the AI logic lives
Cross-cutting
state and observability
2

🧭 Orchestration

Orchestration is the code that decides the order of things: what to do before calling the model, how many calls to make, and what to check afterward. There are two styles. In a pipeline (or workflow), you write the steps in a fixed sequence: clean the input, retrieve context, call the model, validate, save. In an agent, the model decides the next step in a loop, choosing tools until it’s done.

Always start with a pipeline. It’s predictable, inexpensive to test, and easy to debug because each step has known inputs and outputs. Use an agent only when the path really varies from case to case (Module 2.5). Libraries like LangGraph help you design both styles as graphs of steps, but a simple pipeline fits into regular Python functions—you don’t need a framework to get started.

What it is

Orchestration is the layer that connects the steps around the model—preprocessing, calling, validation, and postprocessing—with quality gates in between. It can be a fixed pipeline or an agent that chooses the next step.

Inputuser request Preprocessclean, anonymize Modelprompt + context Validateschema and rules Outputresponse + log if it fails: try again or use the fallback each step has known inputs and outputs, and can be tested on its own
How to read: the blue arrow shows the happy path. The red arrow is the quality gate: if the response doesn’t pass the schema or business rules, it never reaches the user. Notice that the model is only one of the five boxes—the other four are regular code.

Preprocess. Normalize the text, trim anything that’s too long, replace personal data with placeholders (LGPD), and detect the language.

Build the context. Combine the system prompt, session memory, and, if available, retrieved document excerpts (RAG, Module 2.3).

Call through the gateway. Never call the SDK directly: the gateway chooses the model and applies caching and fallback.

Validate. Schema, length, banned words, business rules (“discounts must never exceed the allowed amount”).

Postprocess and log. Format the response for the screen, restore the placeholders, and record tokens, latency, and result.

Why learn

Most of the quality in an AI product comes from what happens before and after the call, not from the model. A pipeline with gates turns “sometimes the model gives a wrong answer” into “when the model makes a mistake, the system notices and responds”—which is something a customer can accept.

Key concepts

Pipeline
fixed steps in sequence
Agent
the model chooses the step
Quality gate
validation between stages
LangGraph
stages designed as a graph
3

🔀 Model gateway

O model gateway is a function (or a service) through which every model call passes. The rest of the system asks for a task — “classify,” “summarize,” “respond with quality” — and the gateway decides which model to use, what order to try them in, and what to return if everything fails. It’s the classic software adapter pattern applied to models: a single interface in front of multiple providers.

The most valuable part of the gateway is the fallback: an ordered list of alternatives. If the first model returns an error or times out, try the second; if they all fail, return an honest default response instead of an error screen. Libraries like LiteLLM already do this for dozens of providers; the example below shows the mechanism in a few lines so you can understand what they do.

What it is

A single access point for models that routes each task to the right model, tries alternatives in order when one fails, measures time and tokens, and hides from the rest of the system which provider is being used.

Try this: a gateway with task-based routes and fallback.

# gateway.py  (pip install openai · ollama pull llama3.2 · ollama pull qwen2.5)
import os, time
from openai import OpenAI

PROVEDORES = {
    "local": OpenAI(base_url="http://localhost:11434/v1", api_key="ollama", timeout=60, max_retries=0),
    # Paid API: same interface, different URL and key (read from the environment, never written here)
    # "nuvem": OpenAI(base_url="https://<provedor>/v1", api_key=os.environ["LLM_API_KEY"]),
}

# Each task has an ordered list of (provider, model). The first one to respond wins.
ROTAS = {
    "classificar": [("local", "llama3.2"), ("local", "qwen2.5")],
    "responder":   [("local", "qwen2.5"), ("local", "llama3.2")],
}

RESPOSTA_PADRAO = "I couldn't respond right now. Your message has been recorded, and we'll get back to you soon."

def completar(tarefa, messages, **kw):
    for provedor, modelo in ROTAS[tarefa]:
        inicio = time.perf_counter()
        try:
            r = PROVEDORES[provedor].chat.completions.create(model=modelo, messages=messages, **kw)
            ms = (time.perf_counter() - inicio) * 1000
            print(f"[ok] {tarefa} via {provedor}/{modelo} em {ms:.0f} ms, {r.usage.completion_tokens} tokens")
            return r.choices[0].message.content
        except Exception as e:
            print(f"[falhou] {provedor}/{modelo}: {type(e).__name__}; tentando o próximo")
    return RESPOSTA_PADRAO

if __name__ == "__main__":
    msg = [
        {"role": "system", "content": "You classify customer support tickets. Categories: "
            "VENDAS = wants to buy or ask about pricing; SUPORTE = technical issue or usage question; "
            "FINANCEIRO = invoice, charge, payment, or refund. Respond with the category only."},
        {"role": "user", "content": "Ticket: my invoice was duplicated"},
    ]
    print(completar("classificar", msg, temperature=0, max_tokens=10))

How to check: the output shows a line [ok] classify via local/llama3.2 … and the category (expected: FINANCEIRO). Now change "llama3.2" in the classify route to "nao-existe": you should see [falhou] local/nao-existe: NotFoundError and the response should come from qwen2.5. Turn off Ollama: both attempts fail, and the default response appears without a traceback.

Routing strategyHow it decidesGood for
By taskEach type of request has its own list of models.Start here; it’s the easiest to understand.
CascadeTry the low-cost model; if validation rejects the result, move up to the better one.High volume with rare difficult cases.
By sensitivityPersonal or confidential data goes only to the local model.LGPD and confidentiality agreements.
FallbackIf it fails or takes too long, try the next one on the list.Always, combined with the others.

Why learn

With a gateway, testing a new model means changing one line in the routing table, comparing the results, and reverting if you don’t like them. Provider outages become a log line instead of an incident. And the question “How much does each feature cost?” becomes answerable because every call goes through the same place.

Key concepts

Gateway
single point of access
Task-based route
ask for what, not who
Fallback
ordered list of alternatives
Cascade
low-cost first, higher-cost if needed
4

🧠 State and memory

Since the API is stateless, memory is yours: you decide what goes into each call. Short-term memory consists of the session’s recent messages. Long-term memory consists of facts that carry across sessions — the customer’s name, subscription plan, preferences — stored in a database and injected when relevant. The full history can stay in the database for auditing; only a selection goes to the model.

The most common technique for long conversations is the sliding window with a summary: the last N messages are sent in full; older ones are condensed into a short summary that the model updates from time to time. This keeps the request size stable, along with the cost, without losing what matters. For storage, SQLite is enough for a prototype; in production, use Postgres or Redis.

What it is

Managing state means deciding where the conversation is stored (the database), what gets sent back to the model (the recent window + summary + long-term facts), and how long each item is kept.

older messages (stored in the database) msg 1msg 2msg 3msg 4 the model summarizes system summary5 lines of what matters msg 5msg 6msg 7msg 8 questionnew context window sent with each call: stable size long-term facts (name, plan, preferences) are added to the system message when relevant
How to read: The cyan frame shows what the model receives. The old messages, shown in gray, don’t disappear—they stay in the database—but are included only through the summary. As the conversation continues, the window boxes slide to the left and the summary is rewritten, so the request never grows without limit.

Goal: a chat with persistent memory in SQLite, a sliding window, and a summary.

# memoria.py  (pip install openai · ollama pull llama3.2)
import sqlite3, sys
from openai import OpenAI

client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
MODELO, JANELA, RESUMIR_A_CADA = "llama3.2", 6, 6

db = sqlite3.connect("conversas.db")
db.execute("CREATE TABLE IF NOT EXISTS msgs (id INTEGER PRIMARY KEY, sessao TEXT, papel TEXT, texto TEXT)")
db.execute("CREATE TABLE IF NOT EXISTS resumos (sessao TEXT PRIMARY KEY, texto TEXT)")

def chat(messages, max_tokens=300):
    r = client.chat.completions.create(model=MODELO, messages=messages, max_tokens=max_tokens)
    return r.choices[0].message.content

def salvar(sessao, papel, texto):
    db.execute("INSERT INTO msgs (sessao, papel, texto) VALUES (?, ?, ?)", (sessao, papel, texto))
    db.commit()

def recentes(sessao, n):
    linhas = db.execute("SELECT papel, texto FROM msgs WHERE sessao = ? ORDER BY id DESC LIMIT ?", (sessao, n)).fetchall()
    return [{"role": p, "content": t} for p, t in reversed(linhas)]

def atualizar_resumo(sessao):
    tudo = recentes(sessao, 1000)
    texto = "\n".join(f"{m['role']}: {m['content']}" for m in tudo)
    resumo = chat([{"role": "user", "content": "Summarize the important facts of this conversation in up to 5 lines (names, requests, decisions):\n" + texto}], max_tokens=200)
    db.execute("INSERT OR REPLACE INTO resumos (sessao, texto) VALUES (?, ?)", (sessao, resumo))
    db.commit()

def conversar(sessao, pergunta):
    msgs = [{"role": "system", "content": "You are a support agent. Reply briefly, in Portuguese."}]
    linha = db.execute("SELECT texto FROM resumos WHERE sessao = ?", (sessao,)).fetchone()
    if linha:
        msgs.append({"role": "system", "content": "Conversation summary so far:\n" + linha[0]})
    msgs += recentes(sessao, JANELA) + [{"role": "user", "content": pergunta}]
    resposta = chat(msgs)
    salvar(sessao, "user", pergunta)
    salvar(sessao, "assistant", resposta)
    total = db.execute("SELECT COUNT(*) FROM msgs WHERE sessao = ?", (sessao,)).fetchone()[0]
    if total % RESUMIR_A_CADA == 0:
        atualizar_resumo(sessao)
    return resposta

if __name__ == "__main__":
    sessao = sys.argv[1] if len(sys.argv) > 1 else "demo"
    while True:
        pergunta = input("you: ").strip()
        if pergunta in ("", "quit"):
            break
        print("ai:", conversar(sessao, pergunta))

How to check: run python3 memoria.py ana, say "my name is Ana and my order number is 4521," chat for about four more messages, and type exit. Run it again with ana and ask "what is my order number?"—the answer comes from the database, not the program's memory. Check the summary with sqlite3 conversas.db "select texto from resumos". With python3 memoria.py bia, the session starts empty.

💡 Tip

Memory is personal data. Decide how long to keep each session, allow the data subject to request deletion (LGPD (Brazil's data protection law)), and don’t put anything unnecessary in the summary—card numbers, passwords, and ID documents should never end up there.

Why learn

An assistant that forgets what the customer said three messages ago is frustrating; one that resends the entire conversation with every question gets expensive and slow. Deliberately managing memory is what makes a chatbot seem attentive without the bill growing along with the conversation.

Key concepts

Short-term
recent messages
Long-term
facts across sessions
Sliding window
last N messages
Summary
the old conversation in a few lines
5

⚡ Cache

Cache means storing the result of an expensive operation so it can be reused when the same request comes up again. AI applications have several types: exact cache (same model, same messages, same parameters → same response), semantic cache (different questions with the same meaning, compared using embeddings—Module 2.3), document embedding cache, and prompt caching offered by the providers themselves.

Caching has a tradeoff: the response can become outdated. That’s why every cache needs an expiration rule—the TTL ((time to live), and a way to invalidate it when the source changes. Caching only makes sense for responses that should be the same: use it with temperature=0 and never for personalized content from one user served to another.

What it is

A cache stores previously calculated responses and is checked before calling the model. The key identifies the request (exactly or by similarity), and the TTL defines how long the response remains valid.

TypeKeyCaution
ExactHash of the model + messages + parameters.Only matches identical requests.
SemanticEmbedding of the question, with a similarity threshold.A loose threshold returns an answer to the wrong question.
EmbeddingHash of the document passage.Recalculate everything if you change the embedding model.
Prompt (provider)Identical beginning of the request, handled by the provider.Put the fixed content at the beginning and the variable content at the end.

Try this: exact cache in SQLite with TTL, in front of the model.

# cache.py  (pip install openai · ollama pull llama3.2)
import hashlib, json, sqlite3, time
from openai import OpenAI

client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
TTL = 24 * 3600  # one day

db = sqlite3.connect("cache.db")
db.execute("CREATE TABLE IF NOT EXISTS cache (chave TEXT PRIMARY KEY, resposta TEXT, criado REAL)")

def chave(modelo, messages, params):
    bruto = json.dumps({"m": modelo, "msgs": messages, "p": params}, sort_keys=True, ensure_ascii=False)
    return hashlib.sha256(bruto.encode()).hexdigest()

def completar(messages, modelo="llama3.2", **params):
    params.setdefault("temperature", 0)  # cache only makes sense with stable output
    k = chave(modelo, messages, params)
    linha = db.execute("SELECT resposta, criado FROM cache WHERE chave = ?", (k,)).fetchone()
    if linha and time.time() - linha[1] < TTL:
        return linha[0], "HIT"
    r = client.chat.completions.create(model=modelo, messages=messages, **params)
    texto = r.choices[0].message.content
    db.execute("INSERT OR REPLACE INTO cache VALUES (?, ?, ?)", (k, texto, time.time()))
    db.commit()
    return texto, "MISS"

if __name__ == "__main__":
    pergunta = [{"role": "user", "content": "In one sentence: what is TTL in a cache?"}]
    for _ in range(2):
        t = time.perf_counter()
        texto, status = completar(pergunta, max_tokens=80)
        print(f"{status} in {(time.perf_counter() - t) * 1000:.0f} ms: {texto}")

How to check: the first line appears as MISS, with the model's generation time; the second as HIT, in a few milliseconds and with the same text. Run the script again: now both lines are HIT, because the cache is in the file cache.db. Change one comma in the question and it returns to MISS — that's the limit of an exact cache.

Why learn

Many systems receive the same questions all the time: business hours, return policy, service status. Serving an answer from the cache is faster for the user and uses no tokens. Knowing where caching helps—and where it can serve an outdated answer or someone else's answer—is part of the design, not a final tweak.

Key concepts

HIT / MISS
found or not found in the cache
TTL
how long the response remains valid
Semantic cache
same intent, different wording
Invalidation
clear it when the source changes
6

📬 Queues and asynchronous work

Summarizing a hundred-page contract, transcribing a meeting, or processing a thousand emails doesn't fit in a web request: the browser gives up first. The solution is a queue: the API receives the request, adds a “job” to a queue, and immediately responds with an ID. Separate processes, called workers, pick up jobs one at a time, call the model, and save the result. The user checks the status or gets notified when it’s done.

Established tools for this include Celery and RQ in Python, BullMQ in Node, usually with Redis behind them; in automations, n8n and Make play a similar role. Two concepts help avoid headaches. Idempotency: running the same job twice must not produce duplicate effects (two emails, two charges). Dead-letter queue (DLQ, dead-letter queue): jobs that fail several times go into a separate place for someone to review, instead of blocking the queue.

What it is

Asynchronous processing separates “receiving the request” from “doing the work”: a queue holds jobs, and independent workers run them at a pace the model and budget can handle.

APIresponds: job ID queue worker 1worker 2worker 3 resultDB or alert dead lettersfailed N times: review the user doesn't wait for the model: the API responds in milliseconds
How to read: From left to right is the path of a job. The API only adds it to the queue and responds. The number of workers is your throughput control: with more workers, the queue moves faster, but you hit the provider or GPU limit sooner. The red arrow shows that repeated failures leave the queue instead of blocking it.

✓ Use a queue when

  • ✓The task takes more than a few seconds.
  • ✓Many requests arrive at once (import, campaign).
  • ✓You need to respect a rate limit or GPU limit.
  • ✓The result can be delivered by email, notification, or webhook.

✗ A queue doesn't solve

  • ✗A chat where the person is waiting for a response (use streaming).
  • ✗Jobs without idempotency: reprocessing duplicates effects.
  • ✗A queue without monitoring: it grows silently until someone complains.
  • ✗A model that's too slow for the volume: in that case, you need another model.

Why learn

The queue is what lets you process documents in batches, run a local model overnight, and absorb spikes without taking down the system. It also lets you use providers’ batch APIs, which cost less because the result doesn’t need to be ready right away.

Key concepts

Queue
jobs waiting their turn
Worker
process that executes the job
Idempotency
repeat without duplicating effects
DLQ
where repeated failures go
7

🔭 Observability and graceful degradation

Observability is being able to answer any question about the system by looking at the records: why that response came out wrong, which feature used the most tokens yesterday, when latency got worse. For AI, the essential signals for each call are: model used, input and output tokens, latency, validation result, error (if any), and an identifier that links every step of the same request—the trace. The open OpenTelemetry standard and tools like Langfuse organize this.

Graceful degradation is when a system gradually loses quality instead of breaking all at once. A circuit breaker helps: after several consecutive failures from a provider, the gateway stops calling it for a while and goes straight to plan B, instead of making each user wait for a timeout. Write down the fallback steps before you need them.

What it is

Observability means recording what the system did and how much it cost, for each call and request. Graceful degradation means having increasingly simple—and honest—response steps for when components fail.

StepSituationWhat the user sees
1 · NormalPrimary model responding.Complete response.
2 · AlternatePrimary failed; fallback to another model.Response, perhaps simpler.
3 · Cache / FAQNo model available.Prepared answer to frequently asked questions.
4 · QueueNo answer possible right now.“We’ve recorded your request; we’ll respond soon.”
5 · HumanSensitive topic or prolonged failure.Handoff to a person.

💡 Tip

Start simple: in the topic 3 gateway, write one JSON line per call to a file ({"trace": …, "tarefa": …, "modelo": …, "ms": …, "tokens_in": …, "tokens_out": …, "ok": …}). With that alone, you can build a cost and latency dashboard. Don’t record the full text of conversations containing personal data; keep only what you need to debug, for a defined period.

🧩 New terms

Trace: the path a request takes through every step, linked by the same identifier. Span: each step within the trace (retrieve context, call the model, validate). Eval: a fixed set of questions with expected answers, run whenever you change a prompt or model to see whether quality has dropped.

Why learn

Models fail silently: the answer comes out well-written but wrong, with no exception in the log. Without observability, you only find out from the customer. And without degradation steps, an external provider going down can take your entire product down.

Key concepts

Trace
the path of a request
Circuit breaker
stops calling a provider that’s down
Step
simpler, honest response
Eval
repeatable quality test

✅ Module summary

✓
Loosely coupled layers — switching models is a configuration change.
✓
Pipeline before agent — with validation gates between steps.
✓
Gateway with fallback — route every call through one point, with a plan B.
✓
Memory, cache, and queues — window + summary, TTL, and heavy work outside the request.
✓
Observe and degrade gracefully — record tokens and latency, and define fallback steps.

Next module:

2.3 — RAG and Knowledge Bases 📚