IA corporativa sem mandar dados para fora: a arquitetura que estou usando para transformar Excel em evidência
Português ↔ English
O projeto começou com uma restrição que eliminou metade das soluções da moda
Em um projeto recente de Qualidade industrial, a regra veio antes da arquitetura:
os dados não podem sair do ambiente da empresa.
Isso muda bastante a conversa sobre IA.
Não adianta escolher o modelo mais impressionante se, para usá-lo, preciso enviar planilhas, reclamações, lotes, processos internos e observações operacionais para um serviço que a política da empresa não permite.
A segunda restrição era quase tão importante: a fonte não era um data warehouse bonito.
Era um Excel grande, atualizado continuamente, com muitas abas, células mescladas, fórmulas, cores com significado e layout variável.
Ou seja: antes de "fazer IA", eu precisava transformar um artefato feito para pessoas em uma base que software consegue interpretar de forma repetível.
O erro seria começar pelo chatbot
A primeira demo tentadora seria:
Excel → LLM → "quais são os principais problemas?"
Eu considero essa arquitetura fraca para o caso.
Ela mistura quatro responsabilidades:
- extrair informação;
- interpretar estrutura;
- classificar reclamação;
- produzir conclusão executiva.
Quando a resposta estiver errada, fica difícil descobrir onde errou.
Eu prefiro uma pipeline:
Excel bruto
↓
extração fiel
↓
modelo canônico
↓
normalização e regras
↓
classificação assistida por IA
↓
revisão/correção humana
↓
base analítica
↓
Power BI
Agora cada etapa deixa evidência.
Antes de IA existe engenharia de ingestão
Planilha corporativa costuma carregar semântica que não está no valor da célula.
Exemplos:
- fundo vermelho significa confirmado;
- célula mesclada vale para várias linhas abaixo;
- fórmula define categoria;
- aba representa período ou unidade;
- linha vazia separa blocos;
- gráfico resume um intervalo escondido.
Se eu fizer apenas:
pandas.read_excel(file)
e assumir que acabou, posso perder justamente a informação que faz a planilha ter sentido para quem a usa.
Por isso a primeira carga precisa preservar mais metadados do que a tabela final provavelmente terá.
Eu gosto de criar uma camada "raw" quase intocável
Uma estratégia é manter três zonas lógicas:
RAW
o que veio do arquivo
NORMALIZED
o que o sistema entendeu de forma determinística
CURATED
o que passou por regra/IA/revisão
A camada raw ajuda a responder:
"essa conclusão saiu de onde?"
Se o parser mudou, eu posso reprocessar sem pedir novamente o histórico inteiro.
Isso é especialmente importante quando acurácia vale mais que velocidade.
O modelo canônico é a parte menos glamourosa e mais valiosa
Uma reclamação confirmada precisa virar uma entidade estável independentemente da aba original.
Exemplo simplificado:
class Complaint(BaseModel):
source_sheet: str
source_row: int
received_at: date | None
product: str | None
lot: str | None
description_raw: str
confirmed: bool
equipment: str | None
production_line: str | None
Depois posso ter uma camada enriquecida:
class ComplaintEnrichment(BaseModel):
complaint_id: UUID
category: str
subcategory: str | None
suspected_cause: str | None
evidence: list[str]
confidence: float | None
needs_review: bool
Separar original de enriquecimento é crucial.
A IA nunca deve sobrescrever o que a fonte dizia.
Cor é dado quando o negócio decidiu que cor é dado
Engenheiro gosta de dizer que usar cor para semântica é ruim.
Pode ser. Mas se a operação funciona assim há anos, ignorar a cor não torna o dado mais limpo — torna a ingestão errada.
Então eu trataria estilos como parte do parser inicial.
cell.fill.fgColor.rgb
cell.font.bold
cell.number_format
cell.data_type
Depois, a normalização pode converter isso para algo explícito:
{
"status": "confirmed",
"status_source": "cell_fill"
}
O objetivo não é perpetuar a cor para sempre. É não perder significado durante a migração.
A IA entra melhor depois que a estrutura está estável
Uma vez que cada reclamação tem texto e contexto conhecidos, IA pode ajudar em tarefas em que linguagem é realmente difícil:
- agrupar descrições semanticamente parecidas;
- sugerir categoria;
- extrair possível componente citado;
- relacionar reclamação com mudança operacional conhecida;
- resumir um cluster para análise humana.
Uma chamada não precisa receber a planilha inteira.
Reclamação: "...
Produto: X
Linha: 3
Período: agosto
Eventos operacionais próximos: [...]"
Quanto mais focado o contexto, mais fácil testar o comportamento.
Hipótese e fato precisam ter tipos diferentes
Esse projeto me fez insistir em uma separação importante.
type Evidence = {
source: string
value: string
}
type Hypothesis = {
text: string
evidenceIds: string[]
status: 'suggested' | 'reviewed' | 'rejected' | 'confirmed'
}
Se depois de uma troca de seladora crescem reclamações de vedação, o sistema pode apontar correlação temporal e sugerir investigação.
Ele não deve magicamente transformar isso em causalidade.
"houve aumento após o evento"
≠
"o evento causou o aumento"
Essa distinção precisa aparecer no dado, não só num disclaimer no dashboard.
Correção humana não é remendo; é parte do produto
A especialista pode saber algo que não existe no Excel.
Exemplo:
"essa linha não usa aquela seladora".
Se o sistema não oferece forma de registrar isso, ele vai repetir o mesmo erro para sempre.
Então correção precisa ser persistida:
type HumanCorrection = {
entityId: string
field: string
previousValue: unknown
correctedValue: unknown
note?: string
createdAt: Date
authorId: string
}
E a próxima execução deve considerar a correção como fonte de maior autoridade do que uma inferência anterior.
Isso cria memória operacional auditável.
Eu não faria fine-tuning como primeira resposta
Com correções acumuladas, é tentador dizer "vamos treinar o modelo".
Talvez um dia.
Antes, eu usaria esse histórico para:
- few-shot examples;
- regras determinísticas;
- dicionário de exceções;
- evals;
- classificação supervisionada mais simples, se fizer sentido.
Fine-tuning é ferramenta. Não é prêmio por ter dataset.
Muitas correções podem revelar que o problema nem deveria estar no LLM.
Modelo local também precisa de avaliação
Rodar local elimina uma classe de risco de saída de dados. Não elimina erro de modelo.
Eu montaria uma bateria com casos já revisados:
100 reclamações conhecidas
20 categorias difíceis
20 descrições quase idênticas com causas diferentes
20 casos que devem ir para revisão
Ao trocar modelo, quantização ou prompt, rodo novamente.
Métricas possíveis:
- acerto de categoria;
- taxa de
needs_reviewcorreta; - falsos vínculos causais;
- campos inventados;
- divergência em relação à especialista.
Local-first não significa eval-free.
"Dados não saem" precisa valer para logs também
Uma arquitetura privada pode vazar por observabilidade se ninguém pensar nisso.
Não adianta inferência local se:
prompt completo → SaaS de log externo
Por isso o boundary precisa incluir:
- modelo;
- embeddings;
- banco vetorial, se houver;
- logs;
- traces;
- backups;
- crash reports;
- arquivos temporários.
Segurança é propriedade do fluxo inteiro.
Power BI entra no fim, não como banco de verdade
O objetivo executivo é entregar filtros, tendência e capacidade de investigação para gerência e diretoria.
Power BI é excelente para essa camada de consumo.
Mas eu não quero regras de classificação espalhadas em dezenas de medidas DAX se essas regras pertencem ao pipeline.
Prefiro:
pipeline produz tabelas confiáveis
↓
Power BI modela e apresenta
O dashboard deve receber fatos e dimensões já suficientemente claros para análise.
Gateway precisa ser uma decisão consciente de boundary
A Microsoft oferece o on-premises data gateway como ponte entre fontes locais e serviços de nuvem como Power BI.
Isso é útil, mas existe uma nuance importante: usar gateway significa que dados consultados/atualizados participam de um fluxo com serviço de nuvem.
Se a política da empresa for literalmente "nenhum dado pode sair da rede", eu não presumiria que gateway atende ao requisito só porque a fonte continua on-premises.
A decisão precisa ser validada pela TI e pela política de segurança.
Se o requisito permitir Power BI Service com gateway, ótimo. Se não permitir, a arquitetura de visualização precisa permanecer inteiramente local ou usar a alternativa corporativa aprovada.
Requisito de soberania vem antes da conveniência da ferramenta.
Uma tabela de evidência muda a qualidade do dashboard
Para cada insight, eu gosto da ideia de preservar ligação com os registros que o suportam.
Cluster: falha de vedação
Período: 12/08–30/08
Quantidade: 37
Produtos: A, B
Lotes: ...
Evento próximo: troca de equipamento
Hipótese: investigar relação
Evidências: [#102, #118, #121...]
A diretoria pode começar no resumo.
A especialista consegue descer até a reclamação original.
Esse caminho de volta é o que transforma "insight de IA" em algo verificável.
O produto final não é a IA; é um sistema de investigação
Esse talvez seja o maior insight desse trabalho.
O usuário não precisa de um chatbot que pareça inteligente.
Precisa conseguir responder melhor:
- o que aumentou?
- desde quando?
- em quais produtos?
- quais lotes?
- quais linhas?
- houve evento operacional próximo?
- qual hipótese existe?
- quais dados sustentam a hipótese?
- o que a especialista corrigiu?
IA é uma peça importante porque texto livre é difícil de agrupar e interpretar.
Mas o valor nasce quando essa capacidade entra em uma cadeia de dados, regras, revisão e evidência.
É assim que eu estou começando a enxergar "Enterprise AI": menos chatbot no centro e mais camada de inteligência verificável entre dados operacionais e decisão humana.
Referências
The project started with one constraint that eliminated half the fashionable solutions
The business requirement was simple to state and difficult to satisfy:
corporate data must not leave the controlled environment.
That immediately changes the architecture.
A workflow that casually uploads spreadsheets to an external model endpoint, sends traces to a public observability SaaS or stores prompts in a third-party analytics service is no longer acceptable just because the model itself is "private".
The boundary has to include data, inference, logs, temporary files, embeddings, backups and support tooling.
This is the kind of requirement that turns AI from a feature into infrastructure.
Starting with a chatbot would have been the wrong move
The source data was a continuously maintained Excel workbook with many worksheets, merged cells, formulas, color conventions and inconsistent layouts.
The useful business questions were analytical:
- what problem increased?
- since when?
- on which products, lots or lines?
- what operational event happened around the same period?
- what hypothesis exists?
- what evidence supports it?
A chat interface cannot compensate for a weak data foundation.
So the first version of the architecture was not "Excel → LLM → answer". It was closer to:
Excel
↓
raw extraction
↓
normalized records
↓
canonical business model
↓
AI enrichment / grouping
↓
human correction
↓
curated analytical tables
↓
Power BI
Before AI comes ingestion engineering
Messy spreadsheets are semi-structured interfaces built for humans.
Merged cells may carry hierarchy. Blank rows may separate sections. Colors may encode status. Formulas may be more valuable than their current displayed value.
A robust extractor therefore needs to understand more than pandas.read_excel() followed by dropna().
I want to capture, when relevant:
- worksheet name;
- row and column coordinates;
- raw cell value;
- formula;
- formatted value;
- fill/style signals used by the business;
- merged-range membership;
- source file version or hash.
That metadata gives me a way to trace a normalized record back to its origin.
I like creating an almost untouched raw layer
The raw layer is not pretty. That is the point.
Its job is to preserve enough of the source to let me reprocess later when extraction rules improve.
raw_file
raw_sheet
raw_cell / raw_row
↓
normalization version N
↓
canonical record
Without that layer, every parser improvement requires trusting the already-transformed data or asking someone to upload old workbooks again.
Reproducibility starts before the model.
The canonical model is the least glamorous and most valuable part
The spreadsheet may express the same idea differently across tabs or years.
The analytical layer should not inherit every layout quirk.
I prefer mapping source variations into stable concepts such as:
type ComplaintRecord = {
id: string
occurredAt: Date | null
productCode?: string
lot?: string
productionLine?: string
category?: string
description: string
confirmed: boolean
source: SourceReference
}
Once this layer exists, Power BI, rules and AI all consume the same vocabulary.
That is what makes future changes cheaper.
Color is data when the business decided color is data
Engineers often treat formatting as cosmetic noise.
In operational spreadsheets, that assumption can destroy meaning.
If red fill means "confirmed", yellow means "under investigation" and green means "closed", fill color is effectively an undocumented enum.
The long-term goal should be to migrate meaning into explicit fields. But during ingestion, I still have to preserve what the source actually uses.
A good data pipeline respects reality before improving it.
AI works better after the structure is stable
Free-text complaints are a good fit for AI because people describe similar problems with different words.
The model can help with:
- semantic grouping;
- category suggestions;
- entity extraction;
- summarizing recurring descriptions;
- linking similar cases for review.
But I do not let the model decide whether a complaint was confirmed if confirmation already exists as a business field.
The AI enriches the canonical record. It does not overwrite authoritative facts.
Hypothesis and fact need different types
One of the most important decisions is to stop putting everything in a single text answer.
I want a result to distinguish:
type InvestigationFinding = {
observation: string
evidenceIds: string[]
hypothesis?: string
confidence?: number
humanStatus: 'unreviewed' | 'accepted' | 'rejected' | 'edited'
}
"Complaints increased after the sealer change" is a much stronger statement than "complaints increased in the same period as the sealer change".
The first implies causality. The second describes temporal evidence.
A useful system should preserve that distinction instead of letting fluent text erase it.
Human correction is not a patch; it is part of the product
The domain specialist needs to be able to say things such as:
- this category is wrong;
- line 3 does not use this machine;
- these two descriptions are equivalent;
- this hypothesis is not operationally possible;
- this source row was interpreted incorrectly.
Those corrections should not disappear into a chat history.
I store them as structured feedback tied to the record, rule or model output they modify.
Then the next processing run can reuse known corrections instead of making the specialist teach the system the same fact again.
I would not fine-tune as the first response
When an AI classification is wrong, fine-tuning is only one possible solution and usually not the first one I want.
First I ask:
- is the source ambiguous?
- is the canonical schema missing a field?
- does a deterministic rule solve this better?
- is retrieval missing relevant context?
- is the prompt unclear?
- is this actually a stable pattern worth learning?
Many enterprise AI errors are data and workflow errors wearing an AI costume.
A local model still needs evaluation
Running inference on-premises reduces one class of data-exposure risk. It does not make the output correct.
I still need a benchmark built from reviewed real cases.
For each task—classification, grouping, extraction, hypothesis suggestion—I can compare model output with a specialist-approved reference set and track precision, recall or task-specific acceptance metrics.
That makes model replacement a measurable engineering decision instead of a demo contest.
"Data does not leave" has to include logs
This is one of the easiest boundaries to accidentally break.
An application can run the model locally and still send:
- stack traces containing row values;
- prompts to an external tracing platform;
- screenshots to remote support tooling;
- backups to an uncontrolled bucket;
- analytics events containing identifiers.
So I treat observability and support as part of the security model.
Redaction, local log retention and strict egress policies matter as much as the inference server.
Power BI belongs at the end, not as the source of truth
Power BI is excellent for exploration, filtering and executive communication.
I do not want the semantic corrections and AI state to live only inside a report.
The pipeline should publish curated tables that Power BI consumes.
That keeps transformations testable and makes another visualization layer possible later without recreating the domain logic.
The on-premises gateway is a boundary decision, not a checkbox
Microsoft's on-premises data gateway can bridge local data sources with Power BI services.
That is useful, but it matters to understand the boundary: using the gateway still involves communication with Microsoft's cloud services.
If an organization's policy literally means no corporate data may leave the local environment, the architecture must validate whether that usage is allowed instead of assuming "gateway" means "fully local".
Security requirements have to be translated into network and data-flow diagrams, not product names.
An evidence table changes the quality of the dashboard
Instead of a chart ending in a number, I like being able to drill down to the records that produced it.
metric
↓
cluster/category
↓
individual cases
↓
source workbook / sheet / row
That traceability makes executive analytics more credible and gives the specialist a way to challenge a conclusion.
The dashboard becomes a view over evidence rather than a collection of untraceable AI summaries.
The final product is not the AI; it is an investigation system
The real questions are not "what did the model say?".
They are:
- what increased?
- since when?
- on which products?
- which lots or lines?
- was there a nearby operational event?
- what hypothesis exists?
- which evidence supports it?
- what did the specialist correct?
AI matters because free text is difficult to group and interpret at scale.
But the value appears when that ability is placed inside a chain of data engineering, rules, review and evidence.
That is increasingly how I see Enterprise AI: less chatbot at the center and more verifiable intelligence layer between operational data and human decisions.