A técnica de RAG (Retrieval-Augmented Generation) revolucionou a forma como modelos de linguagem acessam bases de conhecimento. No entanto, o avanço dos Agentes Autônomos e frameworks como o LangGraph abriu espaço para uma evolução dessa técnica: o Agentic RAG.
Neste post, explicamos o que é o Agentic RAG, como ele se diferencia do RAG tradicional e apresentamos um estudo de caso construído com base nas Atas do COPOM, mostrando passo a passo como criar um agente que busca, avalia, reescreve e responde perguntas complexas sobre política monetária.
Para obter o código e o tutorial deste exercício faça parte do Clube AM e receba toda semana os códigos em R/Python, vídeos, tutoriais e suporte completo para dúvidas.
RAG Tradicional
O RAG tradicional combina recuperação de informações com geração de respostas. A lógica é simples:
-
O usuário faz uma pergunta.
-
O sistema busca documentos relevantes em uma base vetorial.
-
O modelo de linguagem gera a resposta com base nos documentos recuperados.
Essa abordagem é eficaz para perguntas diretas com contexto localizado, mas tem limitações quando a consulta exige interpretação semântica mais profunda, múltiplas buscas ou reescrita da pergunta.
Agentic RAG
Já o Agentic RAG representa uma evolução: o sistema não apenas recupera dados, mas atua como um agente autônomo que raciocina, avalia, decide e interage com ferramentas. Ele pode:
-
Reescrever perguntas para melhorar a precisão da busca;
-
Avaliar a relevância dos documentos retornados;
-
Decidir quando deve buscar mais, reformular ou gerar a resposta;
-
Trabalhar com ciclos iterativos até encontrar a melhor informação.
Esse fluxo é possível graças à utilização do LangGraph, que permite criar um grafo de decisões com múltiplos nós (ações) e transições condicionais entre eles.
Estudo de caso: análise automatizada das Atas do COPOM
Para ilustrar a aplicação prática do Agentic RAG, construímos um sistema baseado em agentes com LangGraph para responder perguntas sobre as atas do Comitê de Política Monetária (COPOM) do Banco Central.
Etapa 1: Coleta e estruturação dos dados
-
Foram coletadas as últimas 10 atas do COPOM diretamente da API do Banco Central.
-
Os documentos foram processados com o
PyPDFLoader
e convertidos em objetos manipuláveis pelo LangChain. -
As atas foram divididas em trechos menores (chunks) e armazenadas em uma base vetorial com embeddings do modelo Gemini.
Etapa 2: RAG tradicional
Como ponto de partida, foi implementado um sistema RAG clássico:
-
Usuário envia uma pergunta.
-
O sistema busca os trechos mais relevantes.
-
O modelo responde com base nos trechos encontrados.
Esse sistema foi funcional, mas limitado. Por exemplo, se a pergunta estivesse mal formulada ou se os documentos retornados fossem irrelevantes, o modelo não conseguia se adaptar.
Etapa 3: Evoluindo para Agentic RAG
Com o LangGraph, criamos um grafo de execução com múltiplos nós, incluindo:
-
Agente principal: interpreta a pergunta e decide se precisa acionar ferramentas.
-
Ferramenta de recuperação: busca documentos com base na pergunta.
-
Avaliador de relevância: decide se os documentos são úteis para responder.
-
Gerador de resposta: monta a resposta com base no conteúdo extraído.
-
Reescritor de pergunta: reformula a pergunta, caso a busca inicial tenha sido irrelevante.
Esse fluxo permite raciocínio iterativo, onde o sistema passa por várias etapas até atingir uma resposta final satisfatória.
Exemplo de uso
Pergunta:
“Qual foi a avaliação do COPOM em sua última reunião sobre o cenário inflacionário global?”
Ciclo executado pelo Agentic RAG:
-
O agente analisa a pergunta.
-
Decide buscar os documentos das atas.
-
Avalia a relevância dos trechos encontrados.
-
Considera que os documentos são úteis e gera uma resposta explicativa com base neles.
Resultado gerado pelo Agente:
================================ Human Message ================================= Qual foi a avaliação do COPOM em sua última reunião sobre o cenário inflacionário global? ---CHAMAR AGENTE--- ================================== Ai Message ================================== Tool Calls: retrieve_atas_copom (4c002a48-1372-4010-8e46-4ac3a57c8585) Call ID: 4c002a48-1372-4010-8e46-4ac3a57c8585 Args: query: Qual foi a avaliação do COPOM em sua última reunião sobre o cenário inflacionário global? ---VERIFICAR RELEVÂNCIA--- ---DECISÃO: DOCUMENTOS RELEVANTES--- ================================= Tool Message ================================= Name: retrieve_atas_copom 1. The global environment is more adverse and uncertain due to the economic policy and economic outlook in the United States, mainly regarding its trade and fiscal policies and their effects. 2. Therefore, the behavior and the volatility of different asset classes have been impacted, altering global financial conditions. This scenario requires particular caution from emerging market economies amid heightened geopolitical tensions. 3. Regarding the domestic scenario, the set of indicators on economic activity has shown some moderation in growth, as expected, but the labor market is still showing strength. 4. In recent releases, headline inflation and measures of underlying inflation remained above the inflation target. Inflation expectations for 2025 and 2026 collected by the Focus survey remained above the inflation target and stand at 5.1% and 4.4%, respectively. B) Scenarios and risk analysis 5. The inflation outlook remains challenging in several dimensions. Copom assessed the international scenario, economic activity, aggregate demand, inflation expectations, and current inflation. Copom then discussed inflation projections and expectations before deliberating on the current decision and future communication. 6. The global environment is more adverse and uncertain. If, on the one hand, the approval of certain trade agreements, along with recent inflation and economic activity data from the U.S., could suggest a reduction in global uncertainty, on the other hand, the U.S. fiscal policy – and, particularly for Brazil, the U.S. trade policy – make the outlook more uncertain and adverse. The increase of trade tariffs by the U.S. to Brazil has significant sectoral impacts and still uncertain aggregate effects that depen d on the unfolding of the next steps in the negotiations and the perception of risk inherent to this process. The Committee is closely monitoring the potential impacts on the real 1. The global environment is more adverse and uncertain due to the economic policy and economic outlook in the United States, mainly regarding its trade and fiscal policies and their effects. 2. Therefore, the behavior and the volatility of different asset classes have been impacted, altering global financial conditions. This scenario requires particular caution from emerging market economies amid heightened geopolitical tensions. 3. Regarding the domestic scenario, the set of indicators on economic activity has shown some moderation in growth, as expected, but the labor market is still showing strength. 4. In recent releases, headline inflation and measures of underlying inflation remained above the inflation target. Inflation expectations for 2025 and 2026 collected by the Focus survey remained above the inflation target and stand at 5.1% and 4.4%, respectively. B) Scenarios and risk analysis 5. The inflation outlook remains challenging in several dimensions. Copom assessed the international scenario, economic activity, aggregate demand, inflation expectations, and current inflation. Copom then discussed inflation projections and expectations before deliberating on the current decision and future communication. 6. The global environment is more adverse and uncertain. If, on the one hand, the approval of certain trade agreements, along with recent inflation and economic activity data from the U.S., could suggest a reduction in global uncertainty, on the other hand, the U.S. fiscal policy – and, particularly for Brazil, the U.S. trade policy – make the outlook more uncertain and adverse. The increase of trade tariffs by the U.S. to Brazil has significant sectoral impacts and still uncertain aggregate effects that depen d on the unfolding of the next steps in the negotiations and the perception of risk inherent to this process. The Committee is closely monitoring the potential impacts on the real dimensions, lags, and prospects. Part of the debate focused on the more recent inflation path, i n which industrial goods and food -at-home inflation no longer contribute to disinflation at this stage of the disinflationary process. At the same time, services inflation, which has greater inertia, plays a major role in the disinflationary dynamics at the current stage. 14. Copom concluded by assessing that the inflation outlook has become more challenging, with the increase of medium -term inflation projections, even conditioned on a higher interest rate. Benign surprises were noted in the recent period, but also the rise in projections for shorter periods, involving market prices. In the end, Copom unanimously concluded that a more contractionary and more cautious monetary policy was needed to reinforce the disinflationary dynamics. 15. The Committee emphasizes that risks to its scenarios remain in both directions. Among the upside risks for the inflationary scenario and inflation expectations, it should be emphasized (i) a greater persistence of global inflationary pressures; and (ii) a stronger-than-expected resilience of services inflation due to a tighter output gap. Among the downside risks, it should be noted (i) a greater-than-projected deceleration of global economic activity; and (ii) an impact on global inflation larger than expected from sync hronized monetary policy tightening. The Committee judges that the domestic and international environments remain more uncertain, requiring greater caution on the conduct of monetary policy. The balance of risks was again under discussion. On the one hand, it was emphasized that the reassessment of the output gap had already incorporated into the central scenario part of the upside asymmetry related to activity. On the other, there was a concern that the output gap remains resilient, and that food inflation is more persistent at the recently observed levels. After to the inflation outlook. Copom assessed that, among the upside risks for the inflation outlook and inflation expectations, it should be emphasized (i) a more prolonged period of deanchoring of inflation expectations; (ii) a stronger -than-expected resilience of services inflation due to a more positive output gap; and (iii) a conjunction of inter nal and external economic policies with a stronger -than-expected inflationary impact, for example, through a persistently more depreciated currency. Among the downside risks, it should be noted (i) a greater -than-projected deceleration of domestic economic activity, impacting the inflation scenario; (ii) a steeper global slowdown stemming from the trade shock and the scenario of heightened uncertainty; and (iii) a reduction in commodity prices with disinflationary effects. 20. Prospectively, the Committee will continue monitoring the pace of economic activity, which is a fundamental driver of inflation, particularly services inflation; the exchange rate pass -through to inflation, after a process of increased exchange rate volatility; and inflation expectations, which remain deanchored and are drivers of future inflation behavior. It was emphasized that inflationary vectors remain adverse, such as the economic activity resilience and labor market pressures, deanchored inflation expectations, and high inflation projections. This scenario prescribes a significantly contractionary monetary policy for a very prolonged period to ensure the convergence of inflation to the target. C) Discussion of the conduct of monetary policy 21. Copom then discussed the conduct of monetary policy, considering the set of projections evaluated, as well as the balance of risks for prospective inflation. 22. Following a swift and firm interest rate hike cycle, the Committee anticipates, as its monetary policy strategy, continuity of the interruption of the rate hiking cycle to from emerging market economies amid escalation of the geopolitical tension. 3. Regarding the domestic scenario, the set of indicators on economic activity and labor market is still exhibiting some strength, even though we observe some moderation in growth. 4. In recent releases, headline inflation and measures of underlying inflation remained above the inflation target. Inflation expectations for 2025 and 2026 collected by the Focus survey remained above the inflation target and stand at 5.2% and 4.5%, respectively. B) Scenarios and risk analysis 5. The inflation outlook remains challenging in several dimensions. Copom assessed the international scenario, economic activity, aggregate demand, inflation expectations, and current inflation. Copom then discussed inflation projections and expectations before deliberating on the current decision and future communication. 6. The global environment has been adverse and particularly uncertain. The Committee assessed that there were some developments that could suggest an improvement in the global scenario, such as the partial reversal of tariffs, but the prevailing view remained that the international scenari o is still uncertain and volatile. In particular, the Committee continues to assess that the uncertainty shock may be significant. It is also unclear what the fiscal trajectory will be in the U.S., both in terms of the magnit ude of the stimulus and the final fiscal consolidation. Moreover, the geopolitical conflict in the Middle East and its potential consequences for the oil market also add uncertainty to the prospective external environment. This scenario has already led to changes in investment and consumption decisions. It is still early to conclude what the magnitude of the impact will be on the domestic economy. On the one hand, it seems less affected by the recent tariffs than other countries, but, on the other, it is impacted by an adverse global scenario. ---GERAR RESPOSTA--- ================================== Ai Message ================================== O Copom avaliou que o cenário inflacionário global tornou-se mais desafiador, com o aumento das projeções de inflação de médio prazo, mesmo condicionado a uma taxa de juros mais alta.
Conclusão
A diferença entre RAG e Agentic RAG está no nível de raciocínio e autonomia. Enquanto o primeiro executa uma tarefa direta de busca e resposta, o segundo raciocina, avalia, decide e interage, simulando o comportamento de um analista humano.
No estudo de caso com as atas do COPOM, o Agentic RAG se mostrou mais robusto, adaptável e capaz de lidar com perguntas ambíguas ou complexas. O uso de LangGraph foi fundamental para implementar essa lógica flexível e escalável.
Essa abordagem é especialmente útil em cenários onde o conteúdo é extenso, o contexto muda frequentemente ou a pergunta não está bem formulada — como é comum em aplicações financeiras, jurídicas, jornalísticas e acadêmicas.
Quer aprender mais?
Conheça nossa Formação do Zero à Análise de Dados Econômicos e Financeiros usando Python e Inteligência Artificial. Aprenda do ZERO a coletar, tratar, construir modelos e apresentar dados econômicos e financeiros com o uso de Python e IA.
Referências
-
LangChain Blog: Agentic RAG with LangGraph
-
OpenAI Cookbook: Retrieval-Augmented Generation
-
ReAct Paper: https://arxiv.org/abs/2210.03629
-
RAG Original Paper (Facebook AI): https://arxiv.org/abs/2005.11401