Pular para o conteúdo

Preparando o caminho para a produção: agentes de IA corporativos com governança — Harish Gaggar, Credit Karma

Ver no idioma original →

Autoria: AI Engineer · Assistir no YouTube

Vídeo de autoria do canal indicado, não da IANIA; todos os direitos pertencem ao criador. Transcrição, resumo e tradução gerados automaticamente; o conteúdo no idioma original é preservado na versão em idioma original.

Idioma original: inglês

Vídeo original: Paving the Road to Production: Governed Enterprise AI Agents — Harish Gaggar, Credit Karma · Canal: AI Engineer · 28:59 · Assistir no YouTube

Tópicos: Agentes de IA, Avaliação e benchmarks de IA, Engenharia de prompts e contexto, Governança e regulação de IA

Harish Gaggar apresenta uma arquitetura e um conjunto de frameworks para levar agentes de IA de experimentos à produção em ambientes corporativos. A proposta inclui um MCP gateway centralizado para autenticação e roteamento, MCP servers com ferramentas revisadas por segurança e monitoramento de operações. Também aborda memória, tracking e evals, proteção de dados sensíveis e otimização de contexto. O objetivo é implantar agentes com controles, observabilidade e supervisão humana desde o início.

  • Agentes corporativos precisam de controles de produção desde o início, não apenas de um framework para executar tarefas.
  • Um MCP gateway centraliza a autenticação e o roteamento entre clientes, agentes e MCP servers.
  • As ferramentas dos MCP servers devem passar por revisão de segurança e limitar os dados acessíveis aos agentes.
  • Monitoramento de logs, traces e métricas ajuda a acompanhar falhas, latência e uso das ferramentas.
  • Memória baseada em threads e checkpoints permite recuperar o estado de execuções e dar continuidade a conversas.
  • Tracking e evals registram consultas, respostas, custos, uso de tokens e métricas de qualidade.
  • Dados sensíveis devem ser detectados e bloqueados antes de chegar ao LLM, à memória ou aos sistemas de observabilidade.
  • O otimizador de contexto seleciona, reordena, deduplica e comprime informações para reduzir o uso de tokens.
  • Operações sensíveis devem passar por aprovação humana, com auditoria das ações realizadas ou rejeitadas.
Início Capítulo Resumo
00:03 Desafios para levar agentes à produção O palestrante apresenta a necessidade de controles, autenticação, tracking, memória, proteção de dados e otimização de contexto.
02:40 Framework e infraestrutura de desenvolvimento A proposta combina LangGraph, MCP gateway e MCP servers próprios, integrados a um portal interno, repositórios e um pipeline de CI/CD.
08:21 MCP servers e autenticação pelo gateway A apresentação explica a criação de ferramentas revisadas por segurança e o fluxo de autenticação, roteamento e retorno das chamadas.
11:59 Monitoramento e fluxo de execução dos agentes Logs, traces e métricas dão visibilidade às operações, enquanto o fluxo do agente classifica ações e encaminha operações sensíveis para aprovação humana.
17:06 Memória, tracking e evals O palestrante demonstra como threads e checkpoints preservam o estado e como tabelas registram execuções, qualidade, custos e chamadas de ferramentas.
23:20 Proteção de dados e otimização de contexto Um framework bloqueia dados sensíveis antes do envio ao LLM, e outro reduz tokens selecionando, reordenando, deduplicando e comprimindo o contexto.
27:28 Recomendações para agentes corporativos O encerramento recomenda implantar o conjunto de controles em conjunto, centralizar autenticação, auditar ferramentas e manter supervisão humana.

Não deve haver acesso direto aos endpoints; as chamadas precisam passar pelo MCP gateway com a autenticação adequada. — 11:29

O objetivo é bloquear esses dados sensíveis assim que são inseridos. — 23:51

Para a mesma consulta, desta vez foram usados apenas 2.400 tokens. — 25:54

Construa um framework corporativo, não apenas um agent. — 27:28

Mantenha sempre o processo human-in-the-loop para ações e itens de alto risco. — 28:29

  • Harish Gaggar (pessoa): Palestrante apresentado no título como engenheiro da Credit Karma, que descreve práticas para levar agentes corporativos à produção.
  • Credit Karma (empresa): Empresa associada ao palestrante no título da apresentação.
  • Intuit (empresa): Empresa mencionada pelo palestrante ao descrever sua função na Intuit Credit Karma.
  • LangGraph (ferramenta): Framework de arquitetura baseada em grafos usado para organizar estados, ramificações e fluxos de trabalho de agentes.
  • LangChain (empresa): Comunidade à qual o palestrante atribui a disponibilização do LangGraph.
  • MCP gateway (conceito): Ponto central de autenticação e roteamento entre clientes ou agentes e os MCP servers.
  • MCP server (conceito): Servidor que expõe ferramentas para agentes e aplica controles sobre as operações e os dados disponibilizados.
  • FastMCP (ferramenta): Pacote ou wrapper citado como opção para construir MCP servers próprios.
  • OpenTelemetry (ferramenta): Solução open source mencionada para coletar e encaminhar traces e métricas.
  • Tempo (ferramenta): Sistema citado para armazenar traces das chamadas e investigar o comportamento das ferramentas.
  • Prometheus (ferramenta): Sistema citado para armazenar métricas como latência e rejeições de autenticação.
  • Redis (ferramenta): Banco usado no exemplo para armazenar o estado da sessão do MCP gateway.
  • Cloud Spanner (ferramenta): Opção mencionada para armazenar memória de agentes em produção no GCP.
  • Kubernetes (ferramenta): Plataforma na qual a arquitetura apresentada implanta agentes em namespaces.
  • ELK (ferramenta): Uma das opções citadas para armazenar logs operacionais.
  • Loki (ferramenta): Uma das opções citadas para armazenar logs operacionais.
  • CloudWatch (ferramenta): Uma das opções citadas para armazenar logs operacionais.
  • BigQuery (ferramenta): Banco citado como opção para armazenar dados de tracking e evals durante o desenvolvimento local.
  • SQLite (ferramenta): Banco citado para armazenar dados de memória durante o desenvolvimento local.
  • Artifactory (ferramenta): Serviço usado nos exemplos de consultas a artefatos e imagens Docker.
  • Slack (ferramenta): Plataforma usada em uma demonstração de consultas a imagens Docker por meio de um bot.

00:03 Olá, pessoal. Gostaria de mostrar como podemos levar os agentes de IA da fase de experimentação para um ambiente corporativo real. Antes de começar, uma breve apresentação. Meu nome é Sharish Gokar. Sou engenheiro de software sênior na Intuit Credit Karma, onde criei e sou responsável pela infraestrutura e pelos serviços de análise de IA. Além disso, sou consultor, autor, pesquisador e também membro de comitês de programa de várias organizações, onde também oriento jovens

00:33 pesquisadores. Certo. Vamos ver a agenda. Primeiro, queremos falar sobre os desafios que enfrentamos ao criar agentes de IA e implantá-los em sistemas de produção, e sobre como podemos criar uma estrutura diferente para lidar com esses desafios. Depois, veremos como é a arquitetura. Em seguida, como criar seus próprios servidores MCP e um gateway MCP.

01:04 E também um sistema de monitoramento nesse gateway. Depois, vamos falar sobre os diferentes tipos de estruturas de agent que você pode usar e sobre algumas estruturas adicionais para gerenciar memórias, rastreamento e evals, como bloquear dados de PII antes que cheguem aos LLMs e como otimizar o contexto para economizar tokens, certo? Então, sem demora, vou explicar os desafios. É claro que muitos agentes costumam falhar em produção

01:36 porque não têm os controles fundamentais. O principal motivo é que, na maioria das vezes, falta um gateway para garantir que o agent consiga se comunicar com ele e se autenticar primeiro com os provedores de autenticação corretos, para então ser encaminhado aos servidores MCP adequados, certo? Segundo, faltam aos servidores MCP as ferramentas certas para executar suas consultas. Terceiro, temos sistemas suficientes de rastreamento e avaliação para garantir que cada consulta enviada aos

02:07 agents seja rastreada e que a qualidade das respostas seja avaliada? Temos um sistema de gerenciamento de memória ou não? Por exemplo, se você interage com um agent por muito tempo ou durante vários dias, ele consegue se lembrar do que você perguntou antes? E há outras estruturas: vocês têm um mecanismo de medição do contexto para economizar tokens? Ou têm proteções em produção para garantir que nenhum segredo chegue aos LLMs, ao rastreamento, aos registros de rastreamento ou a qualquer banco de dados de memória? Há muitas

02:40 questões em aberto. Para resolvê-las, não vamos criar um agent mágico nesta demonstração. Vamos falar sobre diferentes estruturas que você pode criar para lidar com esses desafios. A primeira é a estrutura de agent. Aqui, escolhemos usar a estrutura LangGraph, fornecida pela comunidade LangChain. Ela nos ajuda a criar nós específicos para cada tarefa com base nas perguntas, e é fácil integrar

03:11 plugins de qualquer marketplace, skills e prompts para garantir que os agents respondam com eficiência às suas consultas. Além disso, estamos criando o gateway MCP para garantir que, sempre que um agent ou uma conta de serviço desse agent fizer uma chamada, a autenticação no gateway MCP seja segura e o encaminhamento seja feito aos servidores MCP adequados. A terceira parte são os servidores MCP personalizados, ou seja, você cria seus próprios servidores MCP com as ferramentas certas para

03:43 executar suas consultas. Por fim, há auditoria das operações que você realiza, certo? Também vamos falar de estruturas adicionais, como bloquear segredos que sejam PII, armazenar os dados de rastreamento e evals na nuvem, processar memórias — especialmente threads e checkpoints de cada contexto — e otimizar o contexto como um todo para garantir que você não consuma tokens demais

04:14 ao executar suas consultas. Certo? Agora vamos falar da infraestrutura de agents. Primeiro, veremos o desenvolvimento local. A abordagem deve ser a seguinte: sempre que você criar um agent, primeiro precisa registrá-lo em algum sistema. Em geral, você informa qual é o caso de uso e para qual área ou sistema ele será usado, insere essas informações e gera um ID para o agent, certo?

04:46 Depois disso, você pode usar um portal de desenvolvimento interno para inserir todos os detalhes: qual é o caso de uso do agent, qual é o ID dele, qual estrutura você vai usar — LangGraph, LangChain ou outra — e qual linguagem vai usar, Python ou TypeScript. Depois, você pode escolher suas skills ou prompts e enviar as informações, certo? Ao fazer isso, o portal de desenvolvimento cria um repo que vai conter

05:16 não apenas a estrutura do agent, como a estrutura de agent do LangGraph, mas também a estrutura de memória, a estrutura de rastreamento e evals, certo? E ainda a estrutura de otimização de contexto e a estrutura de bloqueio de PII. O motivo é que nem todos os desenvolvedores cuidam de todas essas estruturas, certo? Às vezes, eles simplesmente criam estruturas que, em geral, as ferramentas de assistente de IA costumam oferecer, certo? Ou se limitam a uma ou duas

05:47 estruturas, certo? Queremos garantir que, quando essas estruturas forem implementadas, sejam consistentes em toda a empresa, centralizadas em um só lugar e capazes de cuidar dessas tarefas, para que também seja possível visualizar os resultados, certo? Depois de ter esse repo, os desenvolvedores o clonam, criam o agent como uma imagem Docker e contêineres, e testam as entradas e saídas do agent usando consultas. Também podem rastrear a memória local, talvez com o Cloud Span Evaluator. E podem

06:19 armazenar esses dados de rastreamento e evals em um banco de dados, como SQLite ou BigQuery, para verificar se os agents estão funcionando plenamente no ambiente local, certo? Quando os agents estiverem rodando localmente, você estará pronto para abrir um PR. Depois que ele receber duas aprovações, seguirá para o pipeline de CI/CD, certo? Primeiro, o PR vai registrar seu agent em um sistema centralizado de registro de agents, que fornece um URL para que você possa ver todos os rastreamentos.

06:49 Então, o pipeline de CI/CD pega o contêiner Docker que você criou localmente e o constrói para o sistema de produção. Ele verifica a imagem para garantir que não haja vulnerabilidades. Se tudo estiver certo e a segurança aprovar, você pode mover a imagem de volta para o registro, certo? Além disso, há sua própria plataforma de implantação ou de orquestração, que implantará o agent no cluster do Kubernetes, em um namespace específico, certo? O bom aqui é que esse portal de desenvolvimento não cria apenas o

07:20 repo, certo? Ele também cria vários outros recursos de produção, como a identidade da carga de trabalho, certo? E também o banco de dados de memória, as tabelas de rastreamento e evals e o gerenciamento de segredos do agent, certo? Com base no nome que você fornecer, ele cria não apenas o repo, mas todos esses recursos diferentes. Assim, quando esse orquestrador interno implanta os agents, o agent já sabe com qual identidade de carga de trabalho deve operar, certo? A vinculação já deve estar configurada.

07:51 Quando essa vinculação de K a GSA acontece, o agent começa a se comunicar com todos esses recursos. Com tudo pronto, o agent também se comunicará com os demais serviços de endpoint, como, por exemplo, o gateway de IA, os servidores MCP, o Langfuse para rastreamento ou outros endpoints de API. Certo? Agora, primeiro, também vamos falar dos servidores MCP. Já falamos da arquitetura. Agora, vamos

08:21 indo para os diferentes componentes. Então, o servidor MCP é algo que você definitivamente pode usar quando algo externo estiver disponível, mas, se estiver trabalhando em um ambiente isolado, é altamente recomendável criar seus próprios servidores MCP. Então, sim, e você pode usar o… não vou entrar na definição. Todo mundo sabe o que é. O framework foi criado de modo que você possa aproveitar o pacote fast MCP server ou um wrapper para, sabe, criar esses servidores MCP e criar um conjunto diferente de ferramentas

08:52 dentro desse wrapper fast MCP para construir, sabe, os servidores como um todo. E então você garante que toda ferramenta definida no servidor MCP seja totalmente revisada pela sua equipe interna de segurança, para garantir que somente ferramentas autorizadas possam ir para produção. É assim que você pode, sabe, aplicar filtros e limites e bloquear os campos que realmente não precisam ser enviados ao LLM para obter as informações

09:23 que você não deveria obter, certo? E, em terceiro lugar, é claro que você precisa garantir que seu servidor MCP seja construído de modo que, sempre que o tráfego vier do cliente MCP para o gateway MCP e, depois, para os servidores MCP, seja de uma conta de usuário ou de serviço, ele precise ser autenticado primeiro pelo gateway MCP, para que possa acessar sua ferramenta MCP e obter as informações corretas. Certo. Agora, a parte do gateway. Como o gateway funciona? Mais uma vez, você pode criar seu próprio

09:54 gateway MCP interno se estiver trabalhando em um ambiente isolado. O funcionamento é o seguinte: você está usando uma ferramenta local de assistência de código na nuvem ou talvez seu agent, certo? No momento em que você envia sua primeira consulta ao agent, ele envia uma solicitação de autenticação única ao gateway MCP, certo? O gateway MCP reconhece e recebe sua solicitação. Primeiro, ele salva o estado da sua sessão no Redis, certo? Depois, retorna o token de acesso JWT ao seu cliente, certo? Depois que

10:26 o cliente recebe esse token JWT, ele sabe qual servidor MCP precisa chamar, certo? Então, envia uma solicitação de chamada de ferramenta em um namespace específico, por exemplo, /MCP, ou seja, Artifactory ou GitHub /MCP, incluindo o token JWT de autorização do tipo bearer. Quando o gateway MCP recebe isso, entende qual namespace — ou seja, qual servidor MCP — precisa consultar. Em seguida, ele desembrulha esse token JWT e anexa o token do usuário à

10:57 solicitação e a envia aos servidores MCP correspondentes. Quando o servidor MCP a recebe, faz as chamadas de API correspondentes ao endpoint do serviço e, em seguida, troca esse token de ID e retorna a resposta com base no escopo que o usuário está autorizado a ver, certo? Quando o usuário recebe o token, o servidor MCP basicamente desembrulha todos os dados e monta o payload compatível para o gateway MCP receber. Por fim, o

11:29 payload final é enviado de volta ao cliente para que ele veja os pontos de dados. Isso mostra que criamos esse gateway MCP para termos um hub centralizado de autenticação e roteamento que conecte com segurança qualquer ferramenta de assistente de programação ou agent ao endpoint por meio desse gateway MCP e do servidor MCP. Não deve haver acesso direto a nenhum endpoint. O acesso precisa passar pelo gateway MCP, com as autenticações apropriadas, antes de chegar ao servidor MCP

11:59 e aos endpoints. Certo? Agora, vamos à parte de monitoramento do gateway. Já falamos sobre a arquitetura, o servidor MCP e o gateway MCP. Agora, vamos falar do monitoramento. Um agent de IA não pode ser confiável sem monitoramento, avaliação e feedback contínuos, certo? Por isso estamos criando o monitoramento do gateway MCP. Normalmente, o monitoramento funciona assim: no momento em que você envia qualquer chamada ao seu agent, ele envia todos os logs operacionais para o armazenamento de logs. Você

12:30 pode usar ELK, Loki ou CloudWatch também, certo? Em geral, isso contém informações como: mostre-me todos os erros 401 ocorridos nas chamadas dos últimos 10 minutos, certo? E o que o OAuth fez quando a atualização do token falhou, certo? Esse tipo de solicitação pode ir para o armazenamento de logs. Agora, há também dados de rastreamento e métricas — dados em tempo real — que vão para o OpenTelemetry. O OpenTelemetry também é uma solução open source que coleta todos os seus rastreamentos e métricas e

13:00 processa os dados e os encaminha para o sistema de backend, certo? Neste caso, os rastreamentos vão para o Tempo. Essa também é uma solução open source que armazena todos os seus rastreamentos, isto é, informações sobre qual ferramenta ficou lenta nessa solicitação, se a chamada veio do agent ou do IDE, qual foi o erro exato nessa chamada que falhou e assim por diante, certo? Esse tipo de dado é armazenado no Tempo. Foi mal. Certo. E as métricas ficam no…

13:31 Prometheus. Ele contém informações como a latência P95 de uma determinada ferramenta, certo? E se as rejeições de autenticação estão aumentando em um determinado momento, certo? Esse tipo de métrica é armazenado no Prometheus. Depois que você reúne todos esses pontos de dados, como rastreamentos e métricas, todos esses dados agregados são salvos no Grafana para visualização.

14:01 Certo. Cobrimos o gateway do servidor MCP e o monitoramento. Agora, vamos falar do framework. Então, o framework de agents: usamos LangGraph na maioria dos casos. O LangGraph, mais uma vez, é fornecido pela comunidade LangChain. Ele oferece uma arquitetura baseada em grafos que dá suporte a loops, ramificações e gerenciamento de estado para workflows complexos de IA com vários agents, certo? O funcionamento é assim: no momento em que

14:31 você envia sua primeira consulta, interpretamos primeiro sua pergunta, ou seja, que tipo de pergunta é e que resposta você está procurando. Com base nisso, criamos um plano, certo? Depois, ela vai para a etapa de classificação, que determina se é apenas uma operação de leitura, se são alterações de modificação ou se você realmente quer excluir algo, certo? Ou se são operações sensíveis. Com base nisso,

15:04 ela ajusta a estrutura geral e faz o planejamento de acordo. A próxima etapa, o planejamento, é um subgrafo em si, onde você realiza a maior parte das operações. Ou seja, no plano, depois de identificar qual operação está sendo executada, ele vai, por exemplo, para a seção de coleta de evidências, onde faz a chamada com base na pergunta que você fez. Depois de interpretar e classificar tudo, ele faz a chamada ao gateway MCP, garante que haja autenticação e

15:34 faz a chamada ao servidor MCP usando a ferramenta correta, obtém os dados e, em seguida, gera as evidências, certo? Depois de validar todas as descobertas, ele verifica as políticas. Se for somente leitura, prossegue com a execução e salva todos os registros nos nossos logs de auditoria. Mas, se forem operações de escrita e sensíveis, elas definitivamente passam pelo processo HITL, em que se aguarda uma aprovação. Se for aprovada, prossegue com a execução. Se for rejeitada, em qualquer um dos casos, ela será

16:05 salva no log de auditoria. Certo? Então, se juntarmos tudo isso — o gateway MCP, o servidor MCP e o agent —, é assim que as coisas ficam. No fim das contas, qualquer agent que você criar e qualquer chamada que enviar passarão pelo gateway MCP para autenticação. Depois, serão encaminhados aos servidores MCP corretos para executar sua consulta usando uma ferramenta específica, de modo que ela faça a chamada de API para esse

16:35 endpoint e obter a resposta. Certo? Tudo bem. Se pensarmos pela perspectiva da infraestrutura, é assim que ela se parece. O agent se comunica com o gateway MCP, que vai para o servidor MCP e para o endpoint. Certo? Então, falamos bastante sobre o gateway MCP, os servidores MCP, o monitoramento e o framework do agent. Agora vamos falar de três ou quatro frameworks adicionais que devemos ter para cuidar da construção do ecossistema completo de ponta a ponta,

17:06 certo? Um deles é o gerenciamento da memória do agent. De novo, é um processo em que você pode salvar e restaurar o estado do seu workflow ao longo do tempo, certo? Isso garante durabilidade e recuperação contínua em cada execução de consulta. O funcionamento é assim: sempre que você envia uma consulta ao seu agent, ele gera uma thread, certo? Nessa thread, quando você faz a

17:37 primeira pergunta, ele cria um ID de execução para ela. Então, quando você faz perguntas mais aprofundadas, ele vai para um nó específico nesse LangGraph e executa a consulta. Nesse nó, ele salva o checkpoint correspondente aqui, certo? Agora, se você fizer uma pergunta complementar na mesma thread, ele cria outro ID de execução. E, novamente, dependendo da sua pergunta complementar, vai para um nó específico e salva o checkpoint ali, certo? Para todo esse armazenamento de dados no desenvolvimento local, você pode usar o banco de dados SQLite,

18:09 mas, em produção, por exemplo, no GCP, você pode usar o Cloud Spanner. E também pode usar os bancos de dados correspondentes no Azure e na AWS, certo? Vou mostrar uma demonstração rápida da memória. Por exemplo, construí este agent localmente e estou tentando executar esta consulta no banco de dados SQLite para ver se há algum dado. Inicialmente, não tenho nenhum dado. Agora, envio minha

18:40 consulta. Vocês verão que recebi um registro, que diz: “Este é o meu ID de thread. Esta é a pergunta que foi feita.” E o horário exato em que essa consulta foi executada. Agora, se eu executar a próxima consulta para ver quantas mensagens foram produzidas em uma determinada thread, posso obter essa informação executando outras consultas, certo? Agora, se eu quiser ver todas as informações no nível dos metadados da minha consulta, posso executá-la novamente e ver a descrição detalhada

19:11 de quantas ferramentas foram invocadas, qual é o meu ID de thread, qual é o meu ID de execução e todas essas informações. Agora, se eu também quiser ver quais ferramentas foram executadas quando rodei esta consulta, posso ver o nome exato da ferramenta nesses servidores MCP. Além disso, também quero ver como foi o progresso no meu framework LangGraph. Posso ver isso executando esse tipo de consulta no banco de dados de memória. Vocês podem ver aqui os diferentes nós

19:43 que foram chamados quando a consulta foi executada. Certo? Agora, o rastreamento e as evals. Só para não haver confusão: o monitoramento do gateway MCP, que mencionamos antes, é diferente; este é o rastreamento no nível do agent. Fazemos isso porque queremos rastrear qual consulta você enviou ao agent, qual foi a resposta, qual modelo LLM você usou, qual foi o custo em tokens, quantos

20:13 tokens foram consumidos e quais são os critérios das suas evals. Qual é a qualidade da sua resposta? Certo? Você precisa armazenar esses dados desde o primeiro dia. Imagine que você tenha mais de mil agents: cada um terá seu próprio projeto e suas próprias tabelas de rastreamento e evals. Se juntarmos tudo, digamos que você tenha 100 agents, terá 100 projetos diferentes, e cada projeto terá suas respectivas tabelas de rastreamento e evals.

20:45 Daqui a seis meses, se alguém perguntar como o seu agent se saiu, qual foi a resposta, qual foi a qualidade e quantos tokens foram consumidos, você poderá agregar todos esses dados e criar dashboards executivos para ver qual é o ROI de construir tantos agents, certo? Vou mostrar a demonstração de rastreamento e evals. Então, aqui, se eu olhar para este item, primeiro, como vocês podem ver,

21:15 há seis tabelas listadas aqui. Uma é a tabela de rastreamento de jobs, que contém a maior parte dessas informações, como qual é a sua consulta, qual é a resposta e tudo mais. Também há várias outras tabelas, como as relacionadas à qualidade, às invocações de ferramentas, às execuções no nível dos nós e assim por diante. Neste caso, vou enviar minha primeira consulta ao agent, e vocês verão que, de início, não haverá nenhum dado

21:45 porque leva algum tempo. Vou atualizar novamente. Desta vez, ao atualizar, vejo que, para uma determinada consulta, recebo meu ID de solicitação, meu ID de sessão, o nome do meu agent, a pergunta que foi feita e a saída dessa pergunta, se foi concluída ou não, quanto tempo levou, qual modelo foi usado e algumas informações intermediárias, certo? Além disso, se eu verificar a qualidade,

22:17 novamente, há oito verificações de qualidade por execução, certo? Vocês podem ver uma linha para cada item, como sucesso, latência, custo, precisão das ferramentas, segurança etc. Tudo isso foi armazenado aqui, certo? Agora, as pontuações das evals. Mais uma vez, isso será uma linha. Será um placar para a execução em questão, com valores que variam de zero a um e que pontuam todas as dimensões de qualidade em uma única linha,

22:48 certo? Agora, as métricas de qualidade. Mais uma vez, é um detalhamento daquela execução específica. Basicamente, um campo aninhado para a qualidade da resposta, segurança, latência, custo e estatísticas das ferramentas em uma única linha larga, certo? Agora, as invocações de ferramentas: cada chamada de ferramenta, qual ferramenta MCP foi executada, quanto tempo levou e se teve sucesso ou não. Certo? E agora, a trajetória do agent com ferramentas, que descreve passo a passo a execução, cada chamada de LLM e o estado do grafo em ordem, como planejar, resumir etc.

23:20 Tudo bem. Agora, o próximo tópico é o tratamento de PII do agent. Isso é muito, muito importante porque, muitas vezes, quando se trabalha com agents ou com essa tecnologia, pode acontecer de alguns segredos serem incluídos na consulta, certo? Digamos que você esteja enviando um documento com informações confidenciais e, às vezes, ao digitar, pode incluir chaves de API ou algo assim. Então, temos um framework

23:51 que define diferentes tipos de dados e seus níveis de gravidade. Se a gravidade estiver acima de 90% ou algo assim, vamos bloquear e ocultar esses segredos imediatamente. Isso garante que eles nunca cheguem aos modelos LLM, certo? Também não irão para o banco de dados de memória, nem para as tabelas de rastreamento e evals, nem para os sistemas de tracing. O objetivo é simplesmente bloquear esses dados confidenciais assim que

24:22 forem ingeridos, certo? No momento em que você digita. Tudo bem. O último framework é o otimizador de contexto. Esta é uma das minhas áreas favoritas. Sempre que você envia muitas consultas, às vezes carrega muitos pontos de dados e vários sistemas de arquivos ou algo assim, certo? Nesse momento, é muito importante garantir que você

24:52 economizar tokens em cada consulta. Então, criamos um framework de otimização de contexto em que você ajusta a consulta e depois a poda antes de ela chegar ao LLM. No sistema de poda, selecionamos o payload com base no limite de tokens. Em seguida, reordenamos: “Qual é a informação mais relevante que devemos priorizar quando você envia esse contexto enorme?” Depois, eliminamos as duplicatas e criamos um conjunto de dados muito exclusivo e bem selecionado, ou seja, os dados principais para o

25:24 LLM. Por fim, comprimimos esse payload grande antes de ele chegar ao LLM. Vamos ver esta demonstração. Vai ser rápida. Por exemplo, digamos que eu envie minha primeira consulta: “Encontre todos os artefatos no meu JFrog Artifactory.” Veja que, antes mesmo de eu enviar qualquer consulta, não há dados aqui. No momento em que envio essa primeira consulta e atualizo esta página,

25:54 você pode ver que o registro foi adicionado. Foram usados 24.000 tokens. Vou voltar um pouco só para mostrar. Como você pode ver, foram usados 24.000 tokens para as perguntas fornecidas. Agora, vou ativar o otimizador de contexto nos bastidores e executar novamente exatamente a mesma consulta. Desta vez, para a mesma consulta, se eu atualizar esta execução, você verá que foram usados apenas 2.400 tokens.

26:26 Certo? Para exatamente a mesma consulta. Isso representa uma economia de quase 90%. Também posso repetir a mesma demonstração no bot do Slack, perguntando: “Diga-me quais são todas as minhas imagens Docker em todos os repositórios no Artifactory.” Quando executo essa consulta, não há dados. Agora, vou enviar minha consulta. Depois que ela for executada, se eu executar a consulta novamente aqui, você verá que o registro foi criado. Para esta consulta específica, foram usados novamente cerca de 24.000 tokens.

26:57 Agora, vou ativar o otimizador nos bastidores e executar novamente a mesma consulta no bot do Slack. Se eu executar essa consulta novamente, ele mostrará que foram usados exatamente cerca de 1.500 tokens, o que representa novamente uma economia de quase 90%. Na maioria dos casos, economizamos de 70% a 78% dos tokens. Imagine que você tenha milhares de agents executando

27:28 muitas consultas por dia. Imagine quantos tokens você pode economizar com esse framework. Certo. Então, a principal conclusão para nós é garantir que criemos um framework empresarial, não apenas um agent, certo? Isso garante que você tenha todo o framework por baixo. Não tente se apressar para criar algum agent rapidamente e colocá-lo em produção. Certifique-se de que ele passe por todo o framework. Assim, você não vai perceber, mais tarde, que deveria ter esse framework implementado

27:59 desde o início. Em segundo lugar, certifique-se de ter um sistema de gateway adequado. Garanta que toda solicitação de tool call, seja feita localmente ou por meio de um agent, passe por algum tipo de gateway MCP centralizado. Certifique-se de que ela seja autenticada antes de chegar aos servidores MCP. E garanta que seus servidores MCP controlem qual ferramenta deve ser usada para executar uma determinada consulta, certo? E certifique-se

28:29 de que haja monitoramento e auditoria completa das execuções dessas ferramentas. E, claro, mantenha sempre uma pessoa no processo para cada item de ação e para cada item de alto risco. Certifique-se de que haja observabilidade e auditoria. Por último, mas não menos importante, garanta que o otimizador de contexto esteja sempre presente para justificar o custo dos seus agents, certo? Só queria compartilhar que

28:59 publiquei recentemente meu livro sobre MCP na Amazon. Fiquem à vontade para baixá-lo. Ele é gratuito no Kindle. Também há uma versão impressa. Certo. Muito obrigado por assistir a este vídeo. Se tiverem alguma dúvida, podem entrar em contato comigo pelo LinkedIn ou pelo Twitter. Terei prazer em responder. Obrigado novamente.

Transcrição original

[00:03] Hello everyone. Um, I would like to walk you through that how we can transition in AI agents from an experiments to the real enterprise environment. So, before I begin, a quick introduction about me. My name is Sharish Gokar. I’m a senior staff software engineer at Intuit Credit Karma where I built and own the AI analytics infrastructure and services. Um, and beside that, um, I’m advisor, uh, author, researchers, um, and also a program committee members for various organizations where I mentor the young

[00:33] researchers as well. All right. So, let’s, uh, walk through the, um, agenda here. So, first we would like to talk about what are the challenges we have when we build an AI agents and deploy into the production systems and how we, uh, can build a different framework to address that, uh, different challenges here. Um, then how the architecture looks like for it. Um, then, um, how you can build your own MCP servers, um, and MCP gateway.

[01:04] And then some monitoring on top of that gateway as well. Um, then further we’re going to talk about what are the different type of agent framework you can have, um, and then, um, some additional framework around managing the memories, tracking and eval, um, how you can block the PII data, uh, going before the LLMs, and then context optimizer to save your token, right? So, without delay, let’s, um, let me walk you through the challenge. Um, of course, like there are many agents, uh, uh, generally get failed in productions

[01:36] because their foundation controls are missing. Um, and the key reason behind is that, um, you know, like, oh, most of the people are missing the gateway to make sure that agent can, you know, communicate to the gateway to get authenticated first with the right auth providers so that they can redirect to the right MCP servers, right? Second, that, um, MCP servers are missing the right tool to execute your query. Third, do we have like enough tracking and evaluation system to make sure that every query when you are sending to the

[02:07] agents, whether they’ve been tracked or not, and are you evaluating the quality response or not, right? Do we have any in memory management system or not in terms of let’s say you are doing the interaction with agent for long or for many days, is it able to recall that what you have been asked in the past, right? And then there are other framework, of course, like do you have a context of the measures to save the token, or do you have inner production in place to make sure that your any secrets should not go into LLM or tracking or tracing or any memory DB or so, right? So, a lot of lot

[02:40] of open questions. So, in order to resolve this, we are not going to, you know, like build a magical agent here in this demo. We’re going to talk about like different framework that you can build to address this. So, first is the agent framework. This is where like we use the like we choose to use the LangGraph framework, which is provided by LangChain community. This is help us in building the task-specific node based on your questions, and which is easy to plug in

[03:11] any like marketplace plugins or skills and prompts to make sure that agents respond efficiently based on your query. Further, the second part is we are also building the MCP gateway to make sure that whenever agent make the call or any service account from that agent make the call, make sure that they are securely get authenticated to that MCP gateway, and then get redirected to the right MCP servers. Third is the customized MCP, which means that you are building your own MCP servers with the right tool in place to

[03:43] execute your query. And then finally some audit on top of what actually operation you’re performing, right? And then we talk about some additional framework around you know like how you can block the PII secrets, how you going to store the tracking eval into the cloud, and how you going to process the memories, especially any threads and checkpoints on every context, and then also how you can optimize overall your context to make sure that you don’t don’t burn too many tokens

[04:14] when you run your query. All right? So, we talk about now the agent infrastructure. So, the Firstly, we’ll go through the local development. The way the approach should be is that you know like whenever you build an agent, right? First you have to register your agent into some system. You usually tell that hey look, this is my the use case and these are the use case going to use for this particular vertical or system, and you feed all those information and generate a ID for your agent, right?

[04:46] Once you have that, then you can have a dev portal, internal portal where you can ingest all the details saying that hey look, this is my agent use case, this is my agent ID, this is the framework I’m going to use either LangGraph, LangChain or so. These are my language I’m going to use either Python or TypeScript, and then you can choose you know like your skills or prompts, and then you submit your information, right? To this. Once you submit this, the dev portal is going to create a repository, which is going to contains

[05:16] not just the agent framework like your LangGraph agent framework, but is also going to contains your memory framework, your tracking eval framework, right? and then your context optimizer framework, and your PII blocking framework as well. So, the reason for that is because not necessarily all your developers are taking care of all this framework, right? They just sometimes you know create the framework what generally like AI assistant tools are generally the right? Or they stick to one or two

[05:47] framework, right? So, we just want to make sure that when you roll out such framework, make sure they are consistent across the company um and they can take care of uh and they can be centralized in one place so you can visualize their results as well, right? So, once you have that repository, so developers basically, you know, clone that repository, they can build their agent as a Docker image and containers and test their agent input and output through the query. And they can also traces on their local memory, maybe cloud span evaluator here. And you can

[06:19] also store this tracking and eval in some of your DB, maybe SQLite or maybe BigQuery um to see to make sure that agents are fully working on your local, right? So, once your agents are running in local, um then you’re ready to go ahead and generate a PR and then you can once you get your two PR approval, then it’s go to the CICD pipeline, right? So, the PR is basically going to firstly is going to uh register your agent into some centralized agent registry system, which provide a length with URL to it to make sure that you see all the traces.

[06:49] And then the CICD pipeline is basically, you know, whatever the local Docker container you built here is going to build that container into production system. Uh it will scan that image, make sure that there’s no vulnerability. Um if everything looks great, security approved, you can move that image back into the registry, right? Further, you have your own deployment platform or orchestrator platform which going to deploy that agent into the Kubernetes cluster in a given namespace, right? So, the good part here is that this dev portal is not just creating the

[07:20] repository, um right? It also do create um bunch of other production resources, for example, the workload identity, um right? And then memory DB or tracking and eval tables and then agent secret management, right? Um so, it based on whatever the name you provide, it not just again it like not just repository, it all these different resources as well. So, what happened is when this internal orchestrator when it deploy the agents, the agent already know that hey, what

[07:51] workload identity I supposed to work with, right? That binding should already happen. So, once this K to GSA binding happens, the agent will start communicating to all these resources. Once everything in place, um agent is further going to communicate to the rest of your endpoint services like for example, AI gateway or MCP servers or length fuse for tracing or some other API endpoints. Right? So, now firstly, we talk about the MCP server as well. So, we talk about architecture. Now, we’re

[08:21] going to the different component. So, MCP server is something that you can definitely use something which is outside available, but if you’re working on air gap environment, it’s highly recommended that you build your own MCP servers. So, um yeah, uh and you can use the uh I will not go with the definition. Everyone knows about it. So, the way the framework has been built here is that uh you you can leverage the fast MCP server package um or wrapper to um you know, build that MCP servers and you can create a different set of tools

[08:52] inside that a fast MCP wrapper to construct your um you know, the overall servers. And then you make sure that, you know, like every tool when you define in MCP server, they had to be fully reviewed by your own internal security team to make sure that only authorized tool can be go in production. And that’s how you can you know, enforce some filters, limits, and block the fields which is really not required to go to LLM and get you the information

[09:23] which is you’re not supposed to get, right? Um and third part is like a of course, you need to make sure that you build your MCP server in a way that whenever the traffic is coming from your MCP client to MCP gateway to MCP servers, either it’s coming from user service account, they has to be authenticated to the MCP gateway first and so that they can be access your MCP tool to get the right information. All right. Now, the gateway part. So, the how the gateway works. So, this is again, you can build it your own

[09:54] internal MCP gateway if you are again working on your air gap environment. So, the way it work is you are working on cloud assist like local, you know, code assistance tool or maybe your agent, right? So, the moment you submit your first query to your agent, it will send that one-time authentication request to the MCP gateway, right? MCP gateway recognized and take your request. First, it will save your session state into the Redis, right? And then it will, you know, return back the JWT access token back to the your client, right? Once

[10:26] client will receive that JWT token, it will know that what MCP server needs to call, right? So, it will submit that tool {slash} call request on a given name space {slash} MCP, meaning let’s say Artifactory or GitHub {slash} MCP with the auth bearer JWT token into that. So, once MCP gateway receive that, it will understand that what name space, meaning MCP server needs to look up for, and then it will unwrap that JWT token, and then it will attach that user

[10:57] token in that request and send it to the respective MCP servers. Now, once MCP server receive it, it will make that respective API calls to that endpoint of that, you know, to the service and then it will exchange that ID token and return the response based on whatever scope that user is authorized to see, right? So, once the user receive the token, you know, MCP server basically, you know, unwrap that all the data, make the payload which is compatible for MCP gateway to receive, and then finally the

[11:29] final payload will send back to the client to see the data points. So, what it shows is that, you know, like we build this MCP gateway to make sure that we have a centralized authentication and routing hub that securely connect any coding assistant tool or agents to the endpoint via this MCP gateway and MCP server. This There should not be direct access provided um on any endpoints. They has to go through the MCP gateway through proper authentications uh before they’re reaching to the MCP

[11:59] server and the endpoints. All right? So, now the part is the gateway monitoring, right? We talk about again, we talk about architecture, we talk about MCP server, MCP gateway. Now, it’s a monitoring. Again, the AI agent cannot be trusted without continuous monitoring, evaluation, and feedback, right? This is why we are building the MCP gateway uh monitoring. So, the way the monitoring work is usually like the moment you submit any calls to your agent, uh it will send all the operational log into the log store. You

[12:30] can use ELK, Loki, or CloudWatch also, right? And generally, this contains the information like show me like all last 401s in my last 10 minutes call, right? And what did OAuth do when the token refresh failed, right? So, those kind of requests can goes to the log store. Now, there are some, you know, traces and metrics data um like real-time data that goes to the OpenTelemetry as well. Um OpenTelemetry again is open source solutions, which going to collect all your traces um and metrics and it’s

[13:00] going to process the data and redirect to the back-end system, right? And in this case, the traces will go to the Tempo. This is again an open source solutions, which going to store all your traces in terms of like traces in the sense like, you know, like information around like which tool was slow on this request, whether this call is coming from agent or IDE, uh what was the exact error um on this failed call or so, right? So, these kind of data are going to store into the Tempo. My bad. Okay. And then the metrics is

[13:31] about the Prometheus is all about the information about like what are P95 latencies for a given tool, right? Whether my auth rejection is spiking on a particular time or not, right? So, those kind of metrics is going to store in Prometheus. So, once you get all these data point like traces and metrics, this entire aggregate data actually save into the graph now for your visualizations.

[14:01] All right. So, the MCP server gateway and monitoring is covered. Now, we’re going to talk about the framework. So, the agent framework, right? So, we use LangGraph for most of the cases and is basically LangGraph again it’s a provided by LangChain community. It’s provide a graph based architecture that support loops, branching, state management for complex multi-agent AI workflows, right? And the way it work is like the moment

[14:31] you submit your first query, we do interpret you know, like your question first, like what type of questions it is and what response is looking for and based on that it’s create a plan, right? Then it will send for classify classify area where it will determine that hey, whether it is just like a read operations or whether it is just like a you know, modification level changes coming up or whether you really want to delete something, right? Or some sensitive operations. Based on that

[15:04] it adjust the overall structure and then plan accordingly. The next step is plan is actually itself is a sub graph where you do the major of your operations. Meaning that in the plan like once you know what operation you’re performing, it goes to the like let’s say in a fetch evidence section where it actually call that whatever the question you ask here, after all interpret and classify, um it actually go ahead and make the call to the MCP gateway, uh make sure they get authenticated, um

[15:34] and then it make the call to the MCP server using the right tool, um and get the data, and then generate that evidence, right? Once you validate all your finding, then it will check the policies. Uh it will check whether it is a read-only, then go ahead and execute, and I will save all the record points into our audit logs. But if it is a right and sensitive operations, definitely it will go through the HITL process where you wait for an approval. If it is approved, you go ahead and execute. If it is get rejected, in either case it’s going to

[16:05] save into the audit log. Right? So, if we combine all this together, like MCP gateway, MCP server, um and the agent, right? This is how things looks like. So, ultimately, whatever the agent you’re building, whatever the call uh you’re submitting, it will go through the MCP gateway for authentications, and then it will redirect to the right MCP servers to execute uh you know, your query on a given tool, uh so that it make the API call to that

[16:35] endpoint and get the response. Right? All right. If it If we think from the infrastructure perspective, this is how it looks like. So, agent is communicating to the MCP gateway, goes to the MCP server, and to the endpoint. All right? So, now the uh we talked a lot about MCP gateway, MCP servers, um the monitoring, um and the agent framework. Now we talk about uh three and four additional framework that we should have to take care of when building the end-to-end

[17:06] ecosystem, right? One is them is agent memory management. Again, it’s a uh you know, it’s a it’s refer It’s basically a process where you can save and restore the state of your workflow over the time, right? Ensuring that it’s provide you a durability and seamless recovery across across your every query run. So, the way it work is like whenever you submit any query to your agent, it actually generate a thread, right? On that given thread, when you ask your

[17:37] first question, it will going to create a run ID for that. So, the moment you ask some deeper questions, it will go on a particular node in that langraph and execute that query. And on that node, it going to save that respective checkpoint here, right? Now, if you ask a follow-up questions on the same thread, it going to create another run ID. And again, depend on your follow-up question, it go to a specific node and save the checkpoint over there, right? And all this data for your local development, you can use the SQLite SQLite DB,

[18:09] but in production, unless in GCP, you can use Cloud Spanner. And in respective databases, you can use in Azure Azure and AWS as well, right? So, just walk you through the quick demo here on the memory. So, for example, I have, you know, like just build this agent locally and then, you know, trying to run this query on SQLite DB to see if there is any data or not. So, I’m just, you know, initially I don’t have any data. Now, I submit my

[18:40] query, you will see that I received the one record, which is saying that, “Hey, this is my thread ID. This is the question I have been asked.” And exact time, you know, when this query was executed. Now, if I run the next query to see that, “Hey, how many messages I’ve been produced on a given thread?” You can get this information by running the further queries, right? Now, if I would like to run to see that, you know, like all the metadata level information on my query, I can run my query again and And can see the detail

[19:11] description around, you know, like how many tool I get invoked, what is my thread ID, what is my run ID, um you know, like and all those informations. Now, if I want to also see that, hey, what tool have been executed when I run this query, um you can go ahead and see the exact tool name as well on that given MCP servers. Now, further I will also want to see that how the progression was happened on my lang graph framework, that also you can see by um running this type of query on your memory DB. You can see that here like different kind of, you know, nodes

[19:43] been called when actually, um you know, that query has been run. All right? Now, the tracking and eval. So, just to make sure that um there is no confusion here like the we talked about earlier the MCP gateway monitoring, this is the agent level tracking. So, we do this because we really want to track that what query you have been submitting to the agent um and what the response is coming, what alarm model you have been used, what’s the cost of your token, um how many

[20:13] token you have been burned, and what’s your, you know, evaluation criteria looks like. What is the quality of your response or not, right? So, you need to store that data from the day one. And imagine that if you have a thousand plus agent, every agents will have their own um you know, um agent tracking and eval um project and the tables, right? So, if you combine, let’s say if you have 100 agents, you will have 100 different projects and each project has their own respective tracking and eval tables.

[20:45] Now, tomorrow, 6 months down the line, if somebody ask you that how your agent has been performed, what was the response, what’s was the quality, how much token you have been burned, you can aggregate all this data and you can create executive dashboards around it to see um with to see the what is the ROI in building so many agents, right? So, let me walk you through the the tracking and eval um demo here. So, um here like if I look at uh this one, so first like, you know, like if you see

[21:15] that there are six tables are listed here. One is a job tracking table, um and which is contains most of this like information around what query like what is your query, what’s the response and everything. And there are a bunch of other tables as well like your quality related and your tool invocations and then node level executions and all that. So, in this case I’m going to submit my first query on my agent um and you will see that um there will not be uh any data in the first place uh

[21:45] because it takes some time. So, I will refresh this again. And this time I will see that when I refresh, I do see that for a given query I get my request ID, my session ID, my agent name, um you know, what question I’ve been asked, um and what was the output um of that uh question, uh whether it has completed or not, and then what is the time it took, what is the model I’ve been used, um and then some of the middle level uh middle level informations, right? Further, if I look for the quality,

[22:17] again there is a eight quality checks per run, right? And you can see that this one row each for, you know, like success, like latency, cost, tool accuracy, safety, etc. Like all this has been stored here, right? Now, the eval scores. This is again this going to be a one row. This is going to be a scoreboard for your given run, which is basically varies between zero to one, which is scores uh you know, like all the quality dimension in a single row,

[22:48] right? Now, the quality metrics. So, again it’s a deep dive on that particular one run. Basically a nested field for the response quality, safety, latency, cost, uh and the tool stat in one white row, right? Now, the tool invocations, so every tool call, which MCP tool ran, how long it took, and whether it succeeded or not. Right? And now the tool agent trajectory, which is talk about step-by-step story of the run, each LLM call, and the graph state in order, like

[23:20] plan, summarize, etc. All right. So, now uh the next is the agent PIR treatment. This is very, very important because many times it happens that when you’re working in agents or uh this thing, um sometimes there’s a possibility that there are some secrets being ingested as a part of your query, right? Let’s say you’re uploading some doc which is has some sensitive informations um and sometimes while typing you may have some API keys or so. So, we have a framework

[23:51] which define that different sort of data types and their severity level. If your severity is above 90% or so, uh we will block and redact that uh secrets uh immediately. So, that uh make sure that that secret is never goes to LLM models, right? Neither it will goes to your memory DB, or nor it will go to tracking and eval tables, or tracing uh systems as well. So, the goal here is to just block this sensitive data as it is

[24:22] the moment it get ingested, right? Moment moment you type. All right. Um the last framework is all about now is the context optimizer. This is one of my favorite area where like um you know, uh whenever you submit, it’s very important, right? Whenever you submit too many queries, sometimes you upload a lot of the um data points and you upload bunch of file systems or so, right? It’s very important that time is um you know, like you make sure that you

[24:52] save your token in every query. So, we build in context optimizer framework where you actually shape your query and then you prune it before it go to LLM. In the pruning system, uh we do select the payload based on the token limit. Then we re-rank that, “Hey, which is the most relevant relevant information that we should target for when you submit this huge giant, you know, context?” And then we dedupe that, uh remove all the duplicates, and create a very unique set of uh very curated data like uh I mean the

[25:24] main data for the LLM. And then we finally compress this large payload before it goes to the LLM. So, let’s see this uh demo here. Uh this will be quick. So, for example, let’s say I will submit my first query, “Hey, find me all the artifacts in my JFrog Artifactory.” Um you see that first when before even I not submitted any query yet, there is no data here. So, the moment I submit this first query, and if I refresh my query here,

[25:54] um and then you can see that the record has been added. So, you can see there is a 24,000 token has been used. I will go back a little bit um just to show the thing. So, you can see this 24,000 token has been used for given questions. Now, if I ask uh now I enable the context optimizer behind the scene and I’m rerun the exact same query again. So, this time you will see that uh you know, for the same query, if I refresh this run, and you will see that uh this time it used just 2,400 token.

[26:26] Right? For exact same query. So, which is almost like 90% saving. I can rerun the same demo on the Slack bot as well where I’m asking Slack bot, “Hey, tell me all my Docker images across all the repositories in Artifactory.” When I run this query, there is no data. Now, I’m going to submit my query. So, once this query will run, um and if I run my query again here, and you will see the record get created. It’s again used like 24,000 for this this particular query.

[26:57] Now, what I will do is I will turn on my optimizer behind the scene and I rerun the same query in the Slack bot. Um and then if I run this query again, um it will show like it exactly used 1,500 almost token, which is again like 90% saving. In most of the cases, we get like 70 to 78% token saves. So, imagine that you have thousands of um you know, like um um if you have thousands of like agents, which is running like

[27:28] you know, many queries per day, you imagine how much token you can save with this framework. All right. So, now the key takeaway here is uh you know, like um for us is like make sure that we build an enterprise framework, um not just an agent, right? Which make sure that you have all the framework underneath. Don’t try to be in rush to building some agent quickly and deploy ship it. Make sure that it has to go through all the framework all together, so that you should not realize a letter state that, you know, I should have this framework in place.

[27:59] Right? In in the very first place. Second is like your Make sure that you have a proper gateway system. Make sure that every tool call request either you are doing this from your local or through agent, it has to go through some sort of centralized MCP gateway. Uh make sure it authenticated before it reaching to the MCP servers. And then make sure that your MCP servers take a control on what tool um you know, uh you should use uh to execute a particular query, right? And make sure

[28:29] that you have monitoring in place and complete auditing in place for that tool executions. And of course, you should um you know, keep the always human in the loop process for every um every action items, every high-risk items. Um make sure that there is a observability um and you know, um auditing has to be in place. And last but not least, make sure that context optimizer should always be there to justify your cost on your agents, right? So, just want to share is that I

[28:59] released my MCP book recently on Amazon. So, feel free to download. It’s free in Kindle. And it’s hard copy is also available. All right. Thank you so much for watching this video. And if you do have any questions, feel free to, you know, like reach out to me over LinkedIn or Twitter. I’m happy to answer. Thank you again.