Multi-agente Self-RAG: calificar, replantear, recuperar de nuevo
Multi-agent Self-RAG: los agentes encargados de calificar y formular preguntas revisan el contexto recuperado, y cuando este es deficiente, reescriben la consulta y la recuperan nuevamente antes de responder.
El RAG simple realiza una búsqueda única y espera obtener el resultado deseado. Los sistemas de estilo Self-RAG añaden bucles: evalúan si los documentos son útiles, crean preguntas más adecuadas cuando no lo son, realizan otra búsqueda y solo entonces responden. El enfoque multiagente hace que esos bucles sean explícitos, al representarlos como roles colaborativos en lugar de una cadena opaca única.
Por qué la búsqueda de un solo intento falla en casos reales
Imaginemos una pregunta de soporte que combina nombres de productos, versiones específicas y un síntoma vago. La primera búsqueda con embeddings podría llevar a un registro de cambios antiguo. Un generador que confíe en ese resultado sonará seguro pero seguirá estando equivocado. Un evaluador capaz de rechazar contextos débiles, junto con un planificador que pueda formular consultas más precisas, convierten al RAG en una búsqueda iterativa en lugar de un proceso aleatorio.
Ruta de iteración
1ª iteración: RAG simple. Se incrustan los datos de la pregunta, se seleccionan los k mejores resultados y se responde. Es una línea de base útil, pero frágil ante la ambigüedad.
2ª iteración: calificación de documentos. Un agente encargado de calificar evalúa cada fragmento en cuanto a relevancia y apoyo. El contexto irrelevante se descarta antes de la generación.
3ª iteración: generación de nuevas preguntas. Si las calificaciones son bajas, un agente especializado en preguntas propone consultas alternativas que aborden aspectos faltantes (versión, código de error, componente).
Iteración final: recuperación con nuevas preguntas. Se vuelve a realizar la recuperación con el conjunto ampliado de consultas, se fusionan las pruebas obtenidas y luego se responde con citas.
Boceto de implementación
Estado
Se almacena la pregunta original, los documentos candidatos, las calificaciones, las consultas de seguimiento y la respuesta final en un objeto de estado compartido que los nodos del grafo leen y escriben:
- - - - - - - - - - - - - - - - - - - - - - - - -
Overview of US Flight Compensation Policies To get compensation for delayed flights, you should contact your airline via their customer service or go to the customer service desk. At the same time, you should bear in mind that you will only receive compensation if the delay is not weather-related and is within the carrier`s control. According to the US Department of Transportation, US airlines are not required to compensate you if a flight is cancelled or delayed. You can be compensated if you are bumped or moved from an overbooked flight. If your provider cancels your flight less than two weeks before departure and you decide to cancel your trip entirely, you can receive a refund of both pre-paid baggage fees and your plane ticket. There will be no refund if you choose to continue your journey. In the case of a delayed flight, the airline will rebook you on a different flight. According to federal law, you will not be provided with money or other compensation. Comparative Analysis of EU vs. US Flight Compensation Policies
- - - - - - - - - - - - - - - - - - - - - - - - -
(AUTHOR-ADDED NOTE: IMPORTANT, PAY ATTENTION TO THIS)
Short-distance flight delays - if it is up to 1,500 km, you are due 250 Euro compensation.
Medium distance flight delays - for all the flights between 1,500 and 3,500 km, the compensation should be 400 Euro.
Long-distance flight delays - if it is over 3,500 km, you are due 600 Euro compensation. To receive this kind of compensation, the following conditions must be met; Your flight starts in a non-EU member state or in an EU member state and finishes in an EU member state and is organised by an EU airline. Your flight reaches the final destination with a delay that exceeds three hours. There is no force majeure.
- - - - - - - - - - - - - - - - - - - - - - - - -
Compensation policies in the EU and US are not the same, which implies that it is worth knowing more about them. While you can always count on Skycop flight cancellation compensation, you should still get acquainted with the information below.
- - - - - - - - - - - - - - - - - - - - - - - - -
Compensation for flight regulations EU: The EU does regulate flight delay compensation, which is known as EU261. US: According to the US Department of Transportation, every airline has its own policies about what should be done for delayed passengers. Compensation for flight delays EU: Just like in the United States, compensation is not provided when the flight is delayed due to uncontrollable reasons. However, there is a clear approach to compensation calculation based on distance. For example, if your flight was up to 1,500 km, you can receive 250 euros. US: There are no federal requirements. That is why every airline sets its own limits for compensation in terms of length. However, it is usually set at three hours. Overbooking EU: In the EU, they call for volunteers if the flight is overbooked. These people are entitled to a choice of: Re-routing to their final destination at the earliest opportunity. Refund of their ticket cost within a week if not travelling. Re-routing at a later date at the person`s convenience.
Definición del grafo
Nodos de recuperación, calificación, reescritura, recuperación nuevamente y generación, con aristas condicionales que omiten la reescritura cuando las calificaciones ya superan un umbral determinado:
from typing import List, Annotated
from typing_extensions import TypedDict
def append_to_list(original: list, new: list) -> list:
original.append(new)
return original
def combine_list(original: list, new: list) -> list:
return original + new
class GraphState(TypedDict):
"""
Represents the state of our graph.
Attributes:
question: question
generation: LLM generation
new_documents: newly retrieved documents for the current iteration
useful_documents: documents that are considered useful
graded_documents: documents that have been graded
new_queries: newly generated questions
hypothesis: hypothesis
"""
question: str
generation: str
new_documents: List[str]
useful_documents: Annotated[List[str], combine_list]
graded_documents: List[str]
new_queries: Annotated[List[str], append_to_list]
hypothesis: str
from langgraph.graph import END, StateGraph, START
from langgraph.checkpoint.memory import MemorySaver
from IPython.display import Image, display
workflow = StateGraph(GraphState)
# Define the nodes
workflow.add_node("retrieve", retrieve) # retrieve
workflow.add_node("grade_documents", grade_documents) # grade documents
workflow.add_node("generate", generate) # generatae
workflow.add_node("transform_query", transform_query) # transform_query
# Build graph
workflow.add_edge(START, "retrieve")
workflow.add_edge("retrieve", "grade_documents")
workflow.add_conditional_edges(
"grade_documents",
decide_to_generate,
{
"transform_query": "transform_query",
"generate": "generate",
},
)
workflow.add_edge("transform_query", "retrieve")
workflow.add_conditional_edges(
"generate",
grade_generation_v_documents_and_question,
{
"useful": END,
"not supported": "transform_query",
"not useful": "transform_query",
},
)
# Compile
memory = MemorySaver()
app = workflow.compile(checkpointer=memory)
display(Image(app.get_graph(xray=True).draw_mermaid_png()))
Los nodos de recuperación y calificación permanecen pequeños y fáciles de probar:
from pprint import pprint
config = {"configurable": {"thread_id": str(uuid4())}}
# Run
inputs = {
"question": "how much can I receive if I am denied boarding, for flights from Delhi to Munich?",
}
for output in app.stream(inputs, config):
for key, value in output.items():
# Node
pprint(f"Node '{key}':")
# Optional: print full state at each node
# print(app.get_state(config).values)
pprint("\n---\n")
# Final generation
pprint(value["generation"])
---RETRIEVE---
"Node 'retrieve':"
'\n---\n'
---CHECK DOCUMENT RELEVANCE TO QUESTION---
---GRADE: DOCUMENT NOT RELEVANT---
---GRADE: DOCUMENT RELEVANT---
---GRADE: DOCUMENT NOT RELEVANT---
---GRADE: DOCUMENT NOT RELEVANT---
---ASSESS GRADED DOCUMENTS---
---DECISION: GENERATE---
"Node 'grade_documents':"
'\n---\n'
---GENERATE---
---CHECK HALLUCINATIONS---
'---DECISION: GENERATION IS NOT GROUNDED IN DOCUMENTS, RE-TRY---'
"Node 'generate':"
'\n---\n'
---TRANSFORM QUERY---
"Node 'transform_query':"
'\n---\n'
---RETRIEVE---
"Node 'retrieve':"
'\n---\n'
---CHECK DOCUMENT RELEVANCE TO QUESTION---
---GRADE: DOCUMENT NOT RELEVANT---
---GRADE: DOCUMENT NOT RELEVANT---
---GRADE: DOCUMENT RELEVANT---
---GRADE: DOCUMENT NOT RELEVANT---
---GRADE: DOCUMENT NOT RELEVANT---
---GRADE: DOCUMENT NOT RELEVANT---
---GRADE: DOCUMENT NOT RELEVANT---
---ASSESS GRADED DOCUMENTS---
---DECISION: GENERATE---
"Node 'grade_documents':"
'\n---\n'
---GENERATE---
---CHECK HALLUCINATIONS---
---DECISION: GENERATION IS GROUNDED IN DOCUMENTS---
---GRADE GENERATION vs QUESTION---
---DECISION: GENERATION ADDRESSES QUESTION---
"Node 'generate':"
'\n---\n'
('Based on the context provided, the flight distance from Munich to Delhi is '
'5,931 km, which falls into the long-distance category (over 3,500 km). '
'Therefore, if you are denied boarding on a flight from Delhi to Munich '
'operated by an EU airline, you would be eligible for 600 Euro compensation, '
'provided that:\n'
'1. The flight is operated by an EU airline\n'
'2. There is no force majeure\n'
'3. Other applicable conditions are met\n'
'\n'
"However, it's important to note that this compensation amount is only valid "
'if all the required conditions are met as specified in the regulations.')
Expansión de preguntas y recuperación en una segunda pasada:
Based on the context provided, the flight distance from Munich to Delhi is
5,931 km, which falls into the long-distance category (over 3,500 km).
Therefore, if you are denied boarding on a flight from Delhi to Munich
operated by an EU airline, you would be eligible for 600 Euro compensation,
provided that:
1. The flight is operated by an EU airline
2. There is no force majeure
3. Other applicable conditions are met
However, it's important to note that this compensation amount is only valid
if all the required conditions are met as specified in the regulations.
print(app.get_state(config).values.get('hypothesis',""))
La generación final se basa únicamente en los documentos que han sobrevivido:
--- Output ---
To answer this question accurately, I need to determine:
1. Is this flight operated by an EU airline? (Since Delhi is non-EU and Munich is EU)
2. What is the flight distance between Delhi and Munich? (To determine compensation amount)
3. Are we dealing with a denied boarding situation due to overbooking? (As opposed to delay/cancellation)
From the context, I can find information about compensation amounts based on distance, but I need to verify:
- If the flight meets EU compensation eligibility criteria
- The exact distance between Delhi and Munich to determine which compensation tier applies (250€, 400€, or 600€)
- If denied boarding compensation follows the same amounts as delay compensation
The context doesn't explicitly state compensation amounts specifically for denied boarding, though it mentions overbooking situations in the EU require offering volunteers re-routing or refund options.
Would you like me to proceed with the information available, or would you need additional context about denied boarding compensation specifically?
Compilar e invocar con un límite de recursión para que los bucles no puedan ejecutarse indefinidamente:
for questions_batch in app.get_state(config).values.get('new_queries',""):
for q in questions_batch:
print(q)
--- Output ---
What is the flight distance between Delhi and Munich?
Does EU denied boarding compensation follow the same amounts as flight delay compensation?
Are there specific compensation rules for denied boarding versus flight delays for flights from non-EU to EU destinations?
What are the compensation rules when flying with non-EU airlines from Delhi to Munich?
What are the specific conditions that qualify as denied boarding under EU regulations?
Conclusión
Multi-agent Self-RAG es más una disciplina que una magia: rechace el contexto deficiente, haga mejores preguntas, recupere la información nuevamente y luego hable. Limite las iteraciones, registre las calificaciones y evalúe si la segunda pasada realmente mejora la fidelidad de la respuesta, no solo si la demostración parece más activa. Mantenga los entornos de prueba en buen estado, mida cada etapa por separado y se niegue a lanzar algo basándose únicamente en la intuición, cuando el próximo lanzamiento podría reintroducir el mismo modo de fallo silencioso bajo un nombre diferente. Mantenga los entornos de prueba en buen estado, mida cada etapa por separado y se niegue a lanzar algo basándose únicamente en la intuición, cuando el próximo lanzamiento podría reintroducir el mismo modo de fallo silencioso bajo un nombre diferente. Mantenga los entornos de prueba en buen estado, mida cada etapa por separado y se niegue a lanzar algo basándose únicamente en la intuición, cuando el próximo lanzamiento podría reintroducir el mismo modo de fallo silencioso bajo un nombre diferente. Mantenga los entornos de prueba en buen estado, mida cada etapa por separado y se niegue a lanzar algo basándose únicamente en la intuición, cuando el próximo lanzamiento podría reintr
Produce el mismo modo de fallo silencioso bajo un nombre nuevo. Mantenga los dispositivos en buen estado, mida cada etapa por separado y se niegue a lanzar algo basándose únicamente en intuiciones, cuando la próxima versión puede reintroducir el mismo modo de fallo silencioso bajo un nombre nuevo. Mantenga los dispositivos en buen estado, mida cada etapa por separado y se niegue a lanzar algo basándose únicamente en intuiciones, cuando la próxima versión puede reintroducir el mismo modo de fallo silencioso bajo un nombre nuevo. Mantenga los dispositivos en buen estado, mida cada etapa por separado y se niegue a lanzar algo basándose únicamente en intuiciones, cuando la próxima versión puede reintroducir el mismo modo de fallo silencioso bajo un nombre nuevo. Mantenga los dispositivos en buen estado, mida cada etapa por separado y se niegue a lanzar algo basándose únicamente en intuiciones, cuando la próxima versión puede reintroducir el mismo modo de fallo silencioso bajo un nombre nuevo. Mantenga los dispositivos en buen estado, mida cada etapa por separado y se niegue a lanzar algo basándose únicamente en intuiciones, cuando la próxima versión puede reintroducir el mismo modo de fallo silencioso bajo un nombre nuevo.Mantenga los dispositivos en buen estado, mida cada etapa por separado y se niegue a lanzar algo basándose únicamente en intuiciones, cuando la próxima versión puede reintroducir el mismo modo de fallo silencioso bajo un nombre diferente.Mantenga los dispositivos en buen estado, mida cada etapa por separado, y se niegue a enviarlos basándose únicamente en intuiciones cuando la próxima versión pueda reintroducir el mismo modo de fallo silencioso bajo un nombre diferente.Mantengan las pruebas en buen estado, midan cada etapa por separado y se nieguen a lanzar basándose únicamente en intuiciones, ya que la próxima versión puede reintroducir el mismo modo de fallo silencioso bajo un nombre diferente.Mismo modo de fallo silencioso bajo un nombre nuevo. Mantengan los dispositivos en buen estado, midan cada etapa por separado y se nieguen a lanzar algo basándose únicamente en intuiciones, cuando la próxima versión podría reintroducir el mismo modo de fallo silencioso bajo un nombre nuevo. Mantengan los dispositivos en buen estado, midan cada etapa por separado y se nieguen a lanzar algo basándose únicamente en intuiciones, cuando la próxima versión podría reintroducir el mismo modo de fallo silencioso bajo un nombre nuevo. Mantengan los dispositivos en buen estado, midan cada etapa por separado y se nieguen a lanzar algo basándose únicamente en intuiciones, cuando la próxima versión podría reintroducir el mismo modo de fallo silencioso bajo un nombre nuevo. Mantengan los dispositivos en buen estado, midan cada etapa por separado y se nieguen a lanzar algo basándose únicamente en intuiciones, cuando la próxima versión podría reintroducir el mismo modo de fallo silencioso bajo un nombre nuevo. Mantengan los dispositivos en buen estado, midan cada etapa por separado y se nieguen a lanzar algo basándose únicamente en intuiciones, cuando la próxima versión podría reintroducir el mismo modo de fallo silencioso bajo un nombre nuevo. KMantenga los componentes en estado estable, mida cada etapa por separado y se niegue a enviarlos basándose únicamente en sensaciones, ya que la próxima versión puede reintroducir el mismo modo de fallo silencioso bajo un nombre diferente.