MODULE 2.9

⚖️ AI Ethics and Governance

Bias, privacy and LGPD (Brazil’s data protection law), transparency, copyright, and human oversight — treated as engineering requirements, with code and processes, not as a paragraph at the end of the project. Trust is designed: you’ll leave with tests you can run and a governance checklist to copy.

7
Topics
~50
Minutes
Technical
Level
Process
Type
0%
0 of 0 topics read · Section 1 of 7

Detailed content

1

🧭 Why govern AI

AI systems make or influence decisions about people: who gets credit, which résumé gets read, what response a patient receives, which customer gets served first. When they fail, they fail at scale and in ways that are hard to see. AI governance is the set of rules, roles, and controls that ensures these systems are used legally, fairly, safely, and transparently — and that someone is accountable for them.

For people who write code, the key point is that ethics isn’t just talk. Each principle needs to become something you can verify: a bias test that runs in CI, a function that removes personal data before a model call, a log that lets you explain a decision, an approval recorded before deployment. Public references help organize this work, such as the NIST AI Risk Management Framework (Govern, Map, Measure, and Manage functions) and the ISO/IEC 42001, the standard for AI management systems.

📘 New terms

Responsible AI is an umbrella term for developing and using AI in ways that respect rights, safety, and transparency. Accountability means having a person or team responsible for the system and answerable for it. Control, in governance, is a concrete check that reduces a risk and leaves evidence.

What it is

A chain from principles (what the organization promises) to policies (written rules), processes (who does what and when), and technical controls (what the code checks), with each layer leaving evidence for the one above it.

Principles what you promise: fairness, privacy, transparency Policies written rules: what’s allowed, what isn’t, who approves Processes inventory, risk assessment, periodic review Technical controls bias test, anonymization, logs, human approval evidence rises
How to read: From top to bottom, each layer becomes more concrete. The arrow shows the reverse path: an auditor asks, "How do you ensure privacy?" The answer is convincing only when it points to a technical control with a record — not to a paragraph in a policy.

✓ Governance that works

  • ✓Proportional to risk: more control where the impact is greater.
  • ✓Built into the development workflow, not handled by a distant committee.
  • ✓With a named owner for each system.
  • ✓Reviewed when the system, model, or law changes.

✗ Governance in name only

  • ✗A principles document that no one on the team has read.
  • ✗The same bureaucracy for an internal summary and a credit score.
  • ✗Approval granted once and never reviewed again.
  • ✗"The AI decided" as an answer to the customer.

Why learn

Laws, contracts, and clients increasingly demand explanations of how AI is used. If you can code and understand governance, you can turn vague requirements into concrete controls—and avoid costly rework when the questions come after launch.

Key concepts

Governance
rules, roles, controls
Accountability
someone is accountable
Control
evidence-backed check
Proportionality
effort matches risk
2

⚖️ Bias and fairness

Bias, in AI, is a systematic error that harms or favors groups of people. It rarely comes from someone with bad intentions; it comes from the data. If a company’s hiring history favored a certain profile, a model trained on that history learns to repeat the pattern — and does so with an appearance of objectivity. LLMs also carry stereotypes from the texts they were trained on.

The most common sources are historical bias (the past was unequal), selection bias (the data doesn’t represent the entire audience), measurement bias (the label measures something else — "was promoted" instead of "performs well"), and aggregation bias (one model for groups that behave differently). Libraries such as Fairlearn help with measurement; the essentials, however, fit in a few lines of pandas.

📘 New terms

Demographic parity: the positive outcome rate (approval, for example) is similar across groups. Equal opportunity: among people who deserved a positive outcome, the approval rate is similar across groups. Protected attribute: a characteristic that can’t be used as a basis for discrimination, such as race, gender, age, or disability. Metrics can conflict with one another; choosing which one to use is a documented business decision.

What it is

Measure the system’s outcome and error rates by group, compare them against an agreed threshold, and investigate differences before release — then repeat the checks periodically in production.

0% 50% 100% 70% 30% Group A Group B 4/5 of the highest rate = 56% B below the line: investigate before release fictional data, the same data used in the code below
How to read: Compare the height of the bars with the dashed line. The four-fifths rule, used as a reference in hiring assessments in the United States, treats a group’s rate falling below 80% of the most favored group’s rate as a warning sign. It is a trigger to investigate, not proof of discrimination or a guarantee of fairness.

Try this: measure parity and equal opportunity by group (bias.py).

# Installation: pip install pandas
import pandas as pd

# Mock data. Replace with: df = pd.read_csv("<decisoes.csv>")
# columns: group, approved (0/1 = system decision), good_payer (0/1 = what actually happened)
df = pd.DataFrame({
    "grupo":       ["A"] * 10 + ["B"] * 10,
    "aprovado":    [1, 1, 1, 0, 1, 1, 0, 1, 1, 0,   1, 0, 0, 1, 0, 0, 1, 0, 0, 0],
    "bom_pagador": [1, 1, 1, 0, 1, 1, 1, 1, 1, 0,   1, 1, 0, 1, 1, 0, 1, 1, 0, 0],
})

# 1) Demographic parity: approval rate by group
rate = df.groupby("grupo")["aprovado"].mean()
ratio = rate.min() / rate.max()
print("Approval rate:", rate.round(2).to_dict())
print(f"Lower/higher ratio = {ratio:.2f} ->", "ALERT (below 0,8)" if ratio < 0.8 else "ok")

# 2) Equal opportunity: among those who were good payers, how many were approved?
opp = df[df["bom_pagador"] == 1].groupby("grupo")["aprovado"].mean()
print("Approval among good payers:", opp.round(3).to_dict())

# 3) How many good payers did each group lose (false negatives)?
fn = df[(df["bom_pagador"] == 1) & (df["aprovado"] == 0)].groupby("grupo").size()
print("Good payers denied:", fn.to_dict())

How to check: With the mock data, the output should show rate A = 0.7 and B = 0.3, ratio 0.43 with ALERT, approval among good payers A = 0.875 and B = 0.5, and one good payer denied in A versus three in B. In other words, the system denies more good payers in group B. With real data, save this output alongside the release (module 2.8).

💡 Tip

Removing the “gender” or “race” column from the model does not eliminate bias: ZIP code, school, name, and purchase history can act as proxies. To measure it, you need the attribute; to protect it, you need a legal basis and care—data about racial or ethnic origin is sensitive under the LGPD.

Why learn

A model with high overall accuracy can make far more errors for a specific group, and the average hides that. Measuring by group is the only way to find out before the problem harms people, leads to a lawsuit, or makes headlines.

Key concepts

Historical bias
the past was unequal
Parity
similar rates
Opportunity
similar errors
Proxy
ZIP code in place of race
3

🔒 Privacy and LGPD

A LGPD (Law No. 13,709/2018) governs the processing of personal data in Brazil and is overseen by the ANPD (National Data Protection Authority). For AI systems, it matters at three points: the data used to train or evaluate, the data sent to the model with each call (including to providers abroad), and automated decisions about people. All processing needs a legal basis and a defined purpose.

Two articles deserve special attention. Art. 20 guarantees data subjects the right to request a review of decisions made solely on the basis of automated processing that affect their interests, and to receive clear information about the criteria used. And Art. 52 provides for penalties ranging from a warning to a fine of up to 2% of the company’s revenue in Brazil, capped at R$ 50 million per violation, as well as blocking and deletion of data.

📘 New terms

Sensitive personal data includes racial or ethnic origin, religion, political opinion, union membership, health, sex life, and genetic and biometric data—it has stricter rules. Anonymization makes it impossible to identify the person by reasonable means; anonymized data is no longer personal data. Pseudonymization replaces identifiers with codes, but anyone with the lookup table can reverse it—so it remains personal data. Data protection officer is the person appointed to communicate with data subjects and the ANPD.

What it is

Apply the LGPD throughout the AI lifecycle: know which personal data is used, its legal basis and purpose, minimize what goes to the model, protect what remains in logs, and ensure human review and explanations for automated decisions.

your environment external provider (if using an API) original text CPF, email, phone pseudonymizer CPF becomes [CPF_1] LLM only sees placeholders answer with [CPF_1], without the CPF restore if needed table stays here lookup table
How to read: The blue dashed line marks the boundary of your environment; nothing containing a CPF or email crosses it. The table linking [CPF_1] to the real CPF stays on this side. This is pseudonymization—it reduces risk, but the data remains personal under the LGPD. Free-form names and addresses call for NER (module 2.7), not just regular expressions.

Goal: remove CPF, CNPJ, email, phone, and ZIP code before sending text to a model (privacy.py).

# No external dependencies. Order matters: CNPJ before CPF, phone number before ZIP code.
import re

PADROES = {
    "CNPJ":     r"\b\d{2}\.?\d{3}\.?\d{3}/?\d{4}-?\d{2}\b",
    "CPF":      r"\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b",
    "EMAIL":    r"\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b",
    "TELEFONE": r"(?:\+?55\s?)?\(?\b\d{2}\)?\s?9?\d{4}-?\d{4}\b",
    "CEP":      r"\b\d{5}-?\d{3}\b",
}

def pseudonimizar(texto: str) -> tuple[str, dict]:
    tabela = {}
    for tipo, padrao in PADROES.items():
        def troca(m, tipo=tipo):
            chave = f"[{tipo}_{len(tabela) + 1}]"
            tabela[chave] = m.group(0)
            return chave
        texto = re.sub(padrao, troca, texto)
    return texto, tabela          # the table NEVER goes to the model or the log

def repor(texto: str, tabela: dict) -> str:
    for chave, valor in tabela.items():
        texto = texto.replace(chave, valor)
    return texto

original = ("Cliente Maria Souza, CPF 123.456.789-09, e-mail maria@exemplo.com, "
            "tel (11) 98765-4321, CEP 01310-100, pediu revisão da fatura.")
seguro, tabela = pseudonimizar(original)
print(seguro)
# ... here 'seguro' goes to the LLM (classify, summarize) ...
assert repor(seguro, tabela) == original

How to check: the output should be Customer Maria Souza, CPF [CPF_1], email [EMAIL_2], phone [TELEFONE_3], ZIP code [CEP_4], requested a bill review. e o assert should pass. Notice that the name "Maria Souza" got through: regular expressions don't catch names. Combine this with the entity extraction from Module 2.7 and test it with real texts from your system before relying on it.

QuestionWhat to do in the system
What is the legal basis and purpose?Record it in the system inventory with the data protection officer.
Does the model need this data?Minimize: pseudonymize or remove it before the call.
Does the provider use the data for training?Check the contract and settings; prefer plans that neither retain data nor use it for training, or use a local model.
Does the data leave the country?International transfers have specific rules under the LGPD (Brazil's data protection law); document them.
What goes into the logs, and for how long?Keep logs free of personal data whenever possible; define a retention period.
Is the decision automated?A review channel (Article 20) and an explanation of the criteria.

Why learn

Every model call involves data processing. As a programmer, you decide, line by line, what leaves the system and what gets recorded. Understanding the LGPD turns that decision from an invisible legal risk into a simple, testable, documented control.

Key concepts

Legal basis
every processing activity needs one
Minimization
only what’s necessary
Pseudonymization
reversible, still personal
Article 20
review of an automated decision
4

🔍 Transparency and explainability

Transparency has three audiences. The user needs to know they're talking to AI and what to do if the answer isn't helpful. The person affected by a decision needs to understand, in plain language, which factors mattered and how to request a review. And the team and auditors need documentation: what the system does, what data it uses, and its known limitations.

Explaining how an LLM works internally is still a research problem. In practice, explainability comes from how the system is designed: ask the model to provide a rationale along with its answer, cite the source passages that support each claim (RAG with sources), record the release and inputs for each decision, and, with classic tabular models, use techniques such as SHAP to show how much each variable contributed.

📘 New terms

Model card (model card) is a short document that describes a model or system: intended use, data, metrics by group, and limitations. Explainability is the ability to explain, in an understandable way, why the system reached a result. Traceability is the ability to link a decision to the inputs, version, and sources used.

What it is

Make it clear when AI is involved, document the system in a model card, record what is needed to reconstruct each decision, and offer an explanation and review to anyone affected.

✓ Transparent in practice

  • ✓"This response was generated by AI and may contain errors" displayed visibly, not hidden.
  • ✓An easy way to talk to a person.
  • ✓Answers with the source for each claim.
  • ✓Synthetic images and videos identified as such.

✗ Opaque

  • ✗An assistant that presents itself with the name and photo of a real person.
  • ✗Credit denial without a reason or a review channel.
  • ✗No record of which version responded to the customer.
  • ✗Known limitations kept only in the team's heads.

Goal: a system card (FICHA.md) to store in the repository and update with each release.

# System card — <name>   (release <x.y.z>, updated <date>)

## What it’s for
Intended use: <e.g., triaging customer messages into 5 categories>
Out of scope: <e.g., deciding refunds; responding to health or legal questions>
Who is affected: <customers, employees, third parties>    Owner: <name/team>

## How it works
Model: <exact name + version>   Local or API: <which provider, region>
Prompt: <path in repository>   Knowledge base consulted (RAG): <which one, updated when>
Final decision: <automatic | AI suggests and a person decides>

## Personal data (LGPD)
Which data: <...>   Legal basis: <...>   Minimization: <pseudonymization before the call?>
Log retention: <period>   Does the provider train on the data? <no / verified on>

## Quality and fairness
Test set: <path, number of cases>   Current result: <metrics>
Metrics by group: <which groups, results, date>
Known limitations: <e.g., performance worsens with transcribed audio and regional slang>

## Transparency and appeals
Notice to the user: <displayed text>   Human review: <channel and timeframe>

How to check: Give the completed card to someone outside the team (legal, customer support) and ask them to answer, using only the card: “What should this system not do?” and “How can a customer challenge a decision?” If they can’t answer, the card is missing information.

Why learn

Transparency lets users trust the system to the right degree, affected people exercise their rights, and the team investigate problems. Without it, a system error can become a trust crisis that is hard to reverse.

Key concepts

AI Notice
the user knows
Model card
use, data, limits
Explainability
why this result
Traceability
decision linked to version
5

©️ Copyright

Copyright issues come up at three points in AI work. During tokens: what you use to train, fine-tune, or feed a RAG knowledge base may be protected work (in Brazil, under Law No. 9,610/1998). During tool: open models come with different licenses—some permissive, such as Apache 2.0 and MIT, others with restrictions on use or scale. And during tokens: what the model generates may too closely resemble an existing work, and protection for the output itself is uncertain.

For authorship of AI-generated content, the trend in several countries is to require substantial human contribution: in the United States, the Copyright Office has refused to register material produced without sufficient human authorship. Lawsuits over the use of works to train models are ongoing, and the issue is part of the debate over Brazil’s AI legal framework (Bill 2338/2023). This situation changes quickly: the approach is to document sources, respect licenses, and consult legal counsel in cases with significant impact.

📘 New terms

Model license is the agreement that sets out how the weights of an open model may be used—read it before putting the model into a product. Provenance is the record of where each piece of data or content came from. Regurgitation is when a model reproduces long, nearly verbatim passages from its training material.

What it is

Manage the origins and rights of what goes into the system, the licenses for the models and tools used, and the risk that outputs copy third-party works. Keep provenance records and have a person review anything that will be published.

PointRiskPractical control
RAG knowledge base and fine-tuningUsing content without usage rights (websites, books, customer materials)List sources with their origins and permissions; prefer original or licensed content
Open modelLicense with restrictions on use, scale, or attributionRecord the license in the system card; get legal review before product release
Generated text and codePassage copied from a work or code under an incompatible licenseHuman review; similarity-checking tools and license checks for code
Image, voice, and videoStyle or image of a real person, a third-party brand, voice without permissionProhibit requests that name artists and real people; get written permission for voice and image

💡 Tip

Read the terms of the provider you use: some offer clauses protecting against copyright claims about outputs, subject to conditions. Note in the system card what your plan covers and what it doesn’t.

Why learn

A model with the wrong license or a dataset assembled from third-party content can force you to rebuild an entire product. Recording origins and licenses from the start costs little and helps avoid disputes that no technical benefit can justify.

Key concepts

Law 9,610/1998
copyright in Brazil
Model license
read before use
Provenance
where each piece of data came from
Human authorship
basis for protection
6

🛡️ Risk and human oversight

Not every use of AI calls for the same level of care. European regulations (the AI Act, in force since 2024, with obligations taking effect in stages) and Brazil’s bill follow the same approach: classify by risk. Some uses are prohibited, some are high-risk (such as candidate selection, credit, and access to essential services), some require transparency (such as chatbots and synthetic content), and others pose minimal risk. Check the timeline and current status of the rules before each project.

For people building these systems, two questions resolve much of the classification: what is the impact of an error on someone’s life, and how much autonomy does the AI have—it only suggests, makes decisions subject to review, or acts on its own? With agents that use tools, autonomy increases and new risks arise, such as hidden instructions injected into documents and pages the agent reads.

📘 New terms

Human in the loop (human-in-the-loop): a person approves each decision before it takes effect. Human overseeing (on-the-loop): the system acts while a person monitors it and can intervene. Prompt injection: malicious text inside the data (an email, a PDF, a page) that tries to change the model’s instructions. Least privilege: give the agent only the permissions it strictly needs.

What it is

Classify each system by the impact of an error and the AI’s autonomy, then choose a level of human oversight, testing, and approval proportionate to that classification.

AI suggests, a person decides credit, hiring, health, legal human in the loop + explanation bias testing and review (Art. 20) Avoid, or require formal approval agent that makes decisions about people or handles money without review auditing, limits, quick shutdown Free use with review drafts, internal summaries the user reviews the result use and data policy Automate with limits triage, file organization human supervision + logs least privilege, rollback impact on the person AI autonomy: suggests → decides → acts on its own
How to read: locate your system along both axes. The farther up and to the right, the more controls apply. The red quadrant is not automatically prohibited, but it requires justification, formal approval, and auditing. The same product may have functions in different quadrants—classify by function, not by product.

Minimum permissions

An agent that reads emails doesn’t need to send them. One that queries the database doesn’t need to delete anything.

Confirmation for irreversible actions

Payments, deletions, external messages: always require explicit human approval.

Data is data, not an instruction

Content read from documents and pages never changes the agent’s instructions.

Why learn

Risk classification helps avoid two costly mistakes: imposing heavy bureaucracy on trivial uses, which leads the team to work around the rules, and unchecked automation in decisions that affect people’s lives. As agents become more autonomous, designing oversight is part of the code.

Key concepts

Risk class
impact × autonomy
Human in the loop
approve first
Prompt injection
hidden instruction in the data
Least privilege
only what’s necessary
7

📋 Governance process

A governance process doesn’t need a new department to get started. The minimum that works has four parts: an inventory of all AI systems (including tools employees use on their own), a risk assessment before each launch, documented approval by whoever is responsible for the system, and a periodic review — and whenever the model, data, or purpose changes.

The key is to fit this into the workflow the team already uses. The checklist below can become the pull request template, a step in the module 2.8 pipeline, or a page in the repository. What matters is that it’s completed before deployment, with evidence, rather than reconstructed after a problem occurs.

📘 New terms

AI inventory is a list of AI systems and tools in use, with an owner, purpose, and risk class. RIPD (Personal Data Protection Impact Report) is the LGPD (Brazil’s data protection law) document describing data processing that may pose risks to data subjects, along with mitigation measures. Shadow AI is the use of AI tools without the organization’s knowledge.

What it is

A lightweight, repeatable cycle—record, assess, approve, monitor, and review—with a checklist that follows each system from its first prototype to retirement.

1 · Record. Every system enters the inventory when it becomes a prototype, with an owner and purpose.

2 · Assess. Risk class (Topic 6), personal data (Topic 3), bias (Topic 2), rights (Topic 5).

3 · Approve. The owner signs off on the checklist; high risk also requires legal counsel and the data protection officer.

4 · Monitor. Quality, group-specific bias, complaints, and incidents, using the module 2.8 dashboard.

5 · Review. At a fixed interval and whenever the model, data, purpose, or applicable law changes.

Goal: governance checklist to paste into the repository or pull request template.

# AI Governance Checklist — <system> · release <x.y.z> · <date>
Owner: <name/area>   Risk class: <minimal | transparency | high>

## 1. Registration
- [ ] System is in the AI inventory, with its purpose and owner
- [ ] System record (FICHA.md) updated for this release

## 2. Personal data (LGPD)
- [ ] Legal basis and purpose recorded with the data protection officer
- [ ] Minimization: personal data removed or pseudonymized before reaching the model
- [ ] Provider does not train on the data (contract/settings checked on <date>)
- [ ] International transfer assessed, if applicable
- [ ] Logs contain no unnecessary personal data; retention period: <period>
- [ ] RIPD completed or updated if the risk to data subjects is significant

## 3. Quality and fairness
- [ ] Test suite passed the gate (result: <...>)
- [ ] Metrics measured by group; differences explained or corrected
- [ ] Known limitations documented in the system record

## 4. Transparency and rights
- [ ] User is told they are interacting with AI or receiving AI-generated content
- [ ] Human review channel for automated decisions (LGPD art. 20)
- [ ] Data sources and licenses, RAG knowledge base, and model recorded

## 5. Security and oversight
- [ ] Level of human oversight defined according to the risk class
- [ ] Agent has minimum permissions; irreversible actions require confirmation
- [ ] Tested against prompt injection using sample malicious documents
- [ ] Runbook includes rollback and rapid shutdown (module 2.8)

## 6. Approval and review
- [ ] Approved by: <owner>  (+ legal/data protection officer if high risk) on <date>
- [ ] Next review: <date> or when the model, data, or purpose changes

How to check: Apply the checklist to a system you already have — the classifier from modules 2.7 and 2.8 will work. Each checked item must point to evidence (file, test output, contract, approval email). A checked item without evidence counts as not done.

💡 Tip

Start with the inventory. Ask teams which AI tools they use in their day-to-day work and what data they use them with. The first list usually reveals uses no one had assessed — and those are where the simplest risks to fix are.

Why learn

Governance done upfront costs a few hours per system; done after an incident or an audit, it costs weeks and reputation. If you master this process, you can bring AI projects safely into sensitive areas — and that is exactly the perspective Track 3 develops at scale.

Key concepts

Inventory
what exists, and who owns it
RIPD
impact on data subjects
Approval recorded
before deployment
Periodic review
and with every change

✅ Module summary

✓
A principle only matters when backed by a control — a test, function, or approval that leaves evidence.
✓
Measure bias by group and protect personal data — parity, opportunity, minimization, and LGPD.
✓
Be transparent and respect rights — AI notice, system record, human review, licenses, and sources.
✓
Oversight proportional to risk — inventory, checklist, approval, and periodic review.

Next module:

Track 3 — Masterclass 👑