LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
UN-2298 [FEAT] Advanced retrieval options in Prompt Studio (#1463)
harini-venkataraman67d0a227dc3f
diff --git a/backend/prompt_studio/prompt_profile_manager_v2/migrations/0002_alter_profilemanager_retrieval_strategy.py b/backend/prompt_studio/prompt_profile_manager_v2/migrations/0002_alter_profilemanager_retrieval_strategy.pynew file mode 100644index 000000000..56c8f8f92--- /dev/null+++ b/backend/prompt_studio/prompt_profile_manager_v2/migrations/0002_alter_profilemanager_retrieval_strategy.py@@ -0,0 +1,29 @@+# Generated by Django 4.2.1 on 2025-07-30 09:11++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("prompt_profile_manager_v2", "0001_initial"),+ ]++ operations = [+ migrations.AlterField(+ model_name="profilemanager",+ name="retrieval_strategy",+ field=models.TextField(+ blank=True,+ choices=[+ ("simple", "Simple retrieval"),+ ("subquestion", "Subquestion retrieval"),+ ("fusion", "Fusion retrieval"),+ ("recursive", "Recursive retrieval"),+ ("router", "Router retrieval"),+ ("keyword_table", "Keyword table retrieval"),+ ("automerging", "Auto-merging retrieval"),+ ],+ db_comment="Field to store the retrieval strategy for prompts",+ ),+ ),+ ]diff --git a/backend/prompt_studio/prompt_profile_manager_v2/migrations/0003_alter_profilemanager_retrieval_strategy.py b/backend/prompt_studio/prompt_profile_manager_v2/migrations/0003_alter_profilemanager_retrieval_strategy.pynew file mode 100644index 000000000..f6fbca8ed--- /dev/null+++ b/backend/prompt_studio/prompt_profile_manager_v2/migrations/0003_alter_profilemanager_retrieval_strategy.py@@ -0,0 +1,30 @@+# Generated by Django 4.2.1 on 2025-08-01 10:04++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("prompt_profile_manager_v2", "0002_alter_profilemanager_retrieval_strategy"),+ ]++ operations = [+ migrations.AlterField(+ model_name="profilemanager",+ name="retrieval_strategy",+ field=models.TextField(+ blank=True,+ choices=[+ ("simple", "Simple retrieval"),+ ("subquestion", "Subquestion retrieval"),+ ("fusion", "Fusion retrieval"),+ ("recursive", "Recursive retrieval"),+ ("router", "Router retrieval"),+ ("keyword_table", "Keyword table retrieval"),+ ("automerging", "Auto-merging retrieval"),+ ],+ db_comment="Field to store the retrieval strategy for prompts",+ default="simple",+ ),+ ),+ ]diff --git a/backend/prompt_studio/prompt_profile_manager_v2/models.py b/backend/prompt_studio/prompt_profile_manager_v2/models.pyindex 533deaaf6..8a814618c 100644--- a/backend/prompt_studio/prompt_profile_manager_v2/models.py+++ b/backend/prompt_studio/prompt_profile_manager_v2/models.py@@ -15,6 +15,11 @@ class ProfileManager(BaseModel):class RetrievalStrategy(models.TextChoices):SIMPLE = "simple", "Simple retrieval"SUBQUESTION = "subquestion", "Subquestion retrieval"+ FUSION = "fusion", "Fusion retrieval"+ RECURSIVE = "recursive", "Recursive retrieval"+ ROUTER = "router", "Router retrieval"+ KEYWORD_TABLE = "keyword_table", "Keyword table retrieval"+ AUTOMERGING = "automerging", "Auto-merging retrieval"profile_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)profile_name = models.TextField(blank=False)@@ -56,6 +61,7 @@ class ProfileManager(BaseModel):choices=RetrievalStrategy.choices,blank=True,db_comment="Field to store the retrieval strategy for prompts",+ default=RetrievalStrategy.SIMPLE,)similarity_top_k = models.IntegerField(blank=True,diff --git a/backend/prompt_studio/prompt_studio_core_v2/retrieval_strategies.py b/backend/prompt_studio/prompt_studio_core_v2/retrieval_strategies.pynew file mode 100644index 000000000..657ea74e7--- /dev/null+++ b/backend/prompt_studio/prompt_studio_core_v2/retrieval_strategies.py@@ -0,0 +1,182 @@+"""Retrieval Strategy Metadata for Prompt Studio.++This module contains detailed information about each retrieval strategy+including descriptions, use cases, performance impacts, and technical details.+"""++RETRIEVAL_STRATEGY_METADATA = {+ "simple": {+ "key": "simple",+ "title": "Simple Vector Retrieval",+ "icon": "SearchOutlined",+ "description": (+ "Basic semantic similarity search using vector embeddings with top-k retrieval."+ ),+ "best_for": [+ "Standard document search and Q&A",+ "General knowledge retrieval tasks",+ "Simple semantic similarity matching",+ ],+ "token_usage": "Low (2-5k tokens typical)",+ "cost_impact": "Low ($0.01-0.05 per query)",+ "technical_details": (+ "Uses cosine similarity on document embeddings to find the most relevant chunks. "+ "Simple and efficient for straightforward retrieval tasks."+ ),+ },+ "fusion": {+ "key": "fusion",+ "title": "Fusion Retrieval (RAG Fusion)",+ "icon": "ForkOutlined",+ "description": (+ "Generates multiple query variations and combines results using "+ "Reciprocal Rank Fusion (RRF) for improved relevance."+ ),+ "best_for": [+ "Complex queries requiring comprehensive coverage",+ "Handling ambiguous or multi-faceted questions",+ "Improving recall when simple retrieval misses context",+ ],+ "token_usage": "High (10-25k tokens typical)",+ "cost_impact": "High ($0.15-0.40 per query)",+ "technical_details": (+ "Creates 3-5 query variations using LLM, retrieves results for each, "+ "then applies RRF scoring to merge and rank results. Significantly improves "+ "retrieval quality at higher cost."+ ),+ },+ "subquestion": {+ "key": "subquestion",+ "title": "Sub-Question Retrieval",+ "icon": "QuestionCircleOutlined",+ "description": (+ "Decomposes complex queries into sub-questions and retrieves relevant "+ "context for each before synthesizing the final answer."+ ),+ "best_for": [+ "Multi-part analytical questions",+ "Research queries requiring multiple perspectives",+ "Complex reasoning tasks spanning multiple topics",+ ],+ "token_usage": "High (15-30k tokens typical)",+ "cost_impact": "High ($0.20-0.50 per query)",+ "technical_details": (+ "Uses LlamaIndex SubQuestionQueryEngine to break down complex queries, "+ "retrieve context for each sub-question, then synthesize comprehensive answers."+ ),+ },+ "recursive": {+ "key": "recursive",+ "title": "Recursive Retrieval",+ "icon": "ReloadOutlined",+ "description": (+ "Follows document relationships and references recursively to build "+ "comprehensive context from connected information."+ ),+ "best_for": [+ "Documents with hierarchical structures",+ "Following citation trails and references",+ "Building context from interconnected content",+ ],+ "token_usage": "Very High (20-50k tokens typical)",+ "cost_impact": "Very High ($0.30-0.80 per query)",+ "technical_details": (+ "Uses LlamaIndex RecursiveRetriever with configurable depth limits. "+ "Traverses document relationships to gather comprehensive context, "+ "ideal for structured documents."+ ),+ },+ "router": {+ "key": "router",+ "title": "Router-based Retrieval",+ "icon": "ShareAltOutlined",+ "description": (+ "Intelligently routes queries to different retrieval strategies or "+ "data sources based on query analysis."+ ),+ "best_for": [+ "Multi-domain knowledge bases",+ "Adaptive retrieval strategy selection",+ "Handling diverse query types in single system",+ ],+ "token_usage": "Variable (5-20k tokens typical)",+ "cost_impact": "Variable ($0.08-0.30 per query)",+ "technical_details": (+ "Uses LlamaIndex RouterQueryEngine to analyze queries and route to "+ "appropriate retrievers (vector, keyword, or summary-based) dynamically."+ ),+ },+ "keyword_table": {+ "key": "keyword_table",+ "title": "Keyword Table Retrieval",+ "icon": "TableOutlined",+ "description": (+ "Extracts and indexes keywords from documents, then performs exact "+ "and fuzzy keyword matching for retrieval."+ ),+ "best_for": [+ "Technical documentation with specific terminology",+ "Exact term and phrase matching",+ "Complementing semantic search with keyword precision",+ ],+ "token_usage": "Low (3-8k tokens typical)",+ "cost_impact": "Low ($0.02-0.08 per query)",+ "technical_details": (+ "Uses LlamaIndex SimpleKeywordTableIndex to extract keywords during indexing "+ "and match against query keywords with TF-IDF scoring."+ ),+ },+ "automerging": {+ "key": "automerging",+ "title": "Auto-Merging Retrieval",+ "icon": "MergeCellsOutlined",+ "description": (+ "Automatically merges adjacent and related document chunks to provide "+ "more comprehensive context while avoiding fragmentation."+ ),+ "best_for": [+ "Long-form documents with narrative flow",+ "Maintaining context across chunk boundaries",+ "Reducing information fragmentation",+ ],+ "token_usage": "Medium (8-18k tokens typical)",+ "cost_impact": "Medium ($0.10-0.25 per query)",+ "technical_details": (+ "Uses LlamaIndex AutoMergingRetriever to dynamically merge leaf nodes "+ "with parent nodes when retrieved chunks are related, preserving document coherence."+ ),+ },+}+++def get_retrieval_strategy_metadata():+ """Get all retrieval strategy metadata.++ Returns:+ dict: Dictionary containing metadata for all retrieval strategies.+ """+ return RETRIEVAL_STRATEGY_METADATA+++def get_retrieval_strategy_choices():+ """Get retrieval strategy choices for select fields.++ Returns:+ list: List of tuples (key, title) for use in Django choice fields.+ """+ return [+ (strategy["key"], strategy["title"])+ for strategy in RETRIEVAL_STRATEGY_METADATA.values()+ ]+++def get_retrieval_strategy_by_key(key):+ """Get retrieval strategy metadata by key.++ Args:+ key (str): The strategy key (e.g., 'simple', 'fusion', etc.)++ Returns:+ dict: Strategy metadata or None if not found.+ """+ return RETRIEVAL_STRATEGY_METADATA.get(key)diff --git a/backend/prompt_studio/prompt_studio_core_v2/static/select_choices.json b/backend/prompt_studio/prompt_studio_core_v2/static/select_choices.jsonindex 81d76bfb8..ea4fdfca2 100644--- a/backend/prompt_studio/prompt_studio_core_v2/static/select_choices.json+++ b/backend/prompt_studio/prompt_studio_core_v2/static/select_choices.json@@ -26,7 +26,12 @@},"retrieval_strategy":{"simple":"simple",- "subquestion":"subquestion"+ "subquestion":"subquestion",+ "fusion":"fusion",+ "recursive":"recursive",+ "router":"router",+ "keyword_table":"keyword_table",+ "automerging":"automerging"},"vector_store":{"Postgres pg_vector":"Postgres pg_vector",diff --git a/backend/prompt_studio/prompt_studio_core_v2/urls.py b/backend/prompt_studio/prompt_studio_core_v2/urls.pyindex bc91f168b..8989b355e 100644--- a/backend/prompt_studio/prompt_studio_core_v2/urls.py+++ b/backend/prompt_studio/prompt_studio_core_v2/urls.py@@ -15,6 +15,9 @@ prompt_studio_detail = PromptStudioCoreView.as_view(})prompt_studio_choices = PromptStudioCoreView.as_view({"get": "get_select_choices"})+prompt_studio_retrieval_strategies = PromptStudioCoreView.as_view(+ {"get": "get_retrieval_strategies"}+)prompt_studio_profiles = PromptStudioCoreView.as_view({"get": "list_profiles", "patch": "make_profile_default"})@@ -66,6 +69,11 @@ urlpatterns = format_suffix_patterns(prompt_studio_choices,name="prompt-studio-choices",),+ path(+ "prompt-studio/<uuid:pk>/get_retrieval_strategies/",+ prompt_studio_retrieval_strategies,+ name="prompt-studio-retrieval-strategies",+ ),path("prompt-studio/prompt-studio-profile/<uuid:pk>/",prompt_studio_profiles,diff --git a/backend/prompt_studio/prompt_studio_core_v2/views.py b/backend/prompt_studio/prompt_studio_core_v2/views.pyindex 3eeba87bd..07e993622 100644--- a/backend/prompt_studio/prompt_studio_core_v2/views.py+++ b/backend/prompt_studio/prompt_studio_core_v2/views.py@@ -44,6 +44,9 @@ from prompt_studio.prompt_studio_core_v2.exceptions import (ToolDeleteError,)from prompt_studio.prompt_studio_core_v2.prompt_studio_helper import PromptStudioHelper+from prompt_studio.prompt_studio_core_v2.retrieval_strategies import (+ get_retrieval_strategy_metadata,+)from prompt_studio.prompt_studio_document_manager_v2.models import DocumentManagerfrom prompt_studio.prompt_studio_document_manager_v2.prompt_studio_document_helper import ( # noqa: E501PromptStudioDocumentHelper,@@ -167,6 +170,30 @@ class PromptStudioCoreView(viewsets.ModelViewSet):logger.error(f"Error occured while fetching select fields {e}")return Response(select_choices, status=status.HTTP_204_NO_CONTENT)+ @action(detail=True, methods=["get"])+ def get_retrieval_strategies(self, request: HttpRequest, pk: Any = None) -> Response:+ """Method to return all retrieval strategy metadata.++ Returns detailed information about each retrieval strategy including+ descriptions, use cases, performance impacts, and technical details.++ Args:+ request (HttpRequest): The HTTP request+ pk (Any): Primary key of the tool (not used in this method)++ Returns:+ Response: Response containing retrieval strategy metadata+ """+ try:+ strategies = get_retrieval_strategy_metadata()+ return Response(strategies, status=status.HTTP_200_OK)+ except Exception as e:+ logger.error(f"Error occurred while fetching retrieval strategies: {e}")+ return Response(+ {"error": "Failed to fetch retrieval strategies"},+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,+ )+@action(detail=True, methods=["get"])def list_profiles(self, request: HttpRequest, pk: Any = None) -> Response:prompt_tool = (diff --git a/frontend/src/components/api/prompt-studio-service.js b/frontend/src/components/api/prompt-studio-service.jsindex 8a2a7c17c..603b430fe 100644--- a/frontend/src/components/api/prompt-studio-service.js+++ b/frontend/src/components/api/prompt-studio-service.js@@ -14,5 +14,16 @@ export const usePromptStudioService = () => {return response.data.count;}, [axiosPrivate, getUrl]);- return { getPromptStudioCount };+ const getRetrievalStrategies = useCallback(+ async (toolId) => {+ const response = await axiosPrivate({+ method: "GET",+ url: getUrl(`/prompt-studio/${toolId}/get_retrieval_strategies`),+ });+ return response.data;+ },+ [axiosPrivate, getUrl]+ );++ return { getPromptStudioCount, getRetrievalStrategies };};diff --git a/frontend/src/components/custom-tools/add-llm-profile/AddLlmProfile.css b/frontend/src/components/custom-tools/add-llm-profile/AddLlmProfile.cssindex 555441c58..b4a330b15 100644--- a/frontend/src/components/custom-tools/add-llm-profile/AddLlmProfile.css+++ b/frontend/src/components/custom-tools/add-llm-profile/AddLlmProfile.css@@ -1,5 +1,67 @@/* Styles for AddLlmProfile */.add-llm-profile-row {- width: 100%;+ width: 100%;+}++.add-llm-profile-panel {+ margin-bottom: 16px;+}++.retrieval-strategy-selector {+ border: 1px solid #d9d9d9;+ border-radius: 6px;+ padding: 4px 11px;+ cursor: pointer;+ background-color: #fff;+ display: flex;+ justify-content: space-between;+ align-items: center;+ min-height: 32px;+ transition: all 0.2s ease-in-out !important;+ width: 100%;+ font-family: inherit;+ font-size: inherit;+ text-align: left;+}++.retrieval-strategy-selector:hover {+ border-color: #40a9ff !important;+ box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);+}++.retrieval-strategy-selector:active {+ border-color: #1890ff !important;+ box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.15);+}++.retrieval-strategy-text {+ flex: 1;+ user-select: none;+}++.retrieval-strategy-text--selected {+ color: #000;+}++.retrieval-strategy-text--placeholder {+ color: #bfbfbf;+}++.retrieval-strategy-actions {+ display: flex;+ align-items: center;+ gap: 4px;+}++.retrieval-strategy-settings-icon {+ color: #1890ff;+ font-size: 12px;+ cursor: pointer;+}++.retrieval-strategy-dropdown-icon {+ color: #bfbfbf;+ font-size: 10px;+ cursor: pointer;}diff --git a/frontend/src/components/custom-tools/add-llm-profile/AddLlmProfile.jsx b/frontend/src/components/custom-tools/add-llm-profile/AddLlmProfile.jsxindex d1c72e1b0..82fc54c3f 100644--- a/frontend/src/components/custom-tools/add-llm-profile/AddLlmProfile.jsx+++ b/frontend/src/components/custom-tools/add-llm-profile/AddLlmProfile.jsx@@ -1,4 +1,9 @@-import { ArrowLeftOutlined, CaretRightOutlined } from "@ant-design/icons";+import {+ ArrowLeftOutlined,+ CaretRightOutlined,+ DownOutlined,+ SettingOutlined,+} from "@ant-design/icons";import {Button,Col,@@ -24,6 +29,8 @@ import { CustomButton } from "../../widgets/custom-button/CustomButton";import SpaceWrapper from "../../widgets/space-wrapper/SpaceWrapper";import "./AddLlmProfile.css";import usePostHogEvents from "../../../hooks/usePostHogEvents";+import RetrievalStrategyModal from "../retrieval-strategy-modal/RetrievalStrategyModal";+import { useRetrievalStrategies } from "../../../hooks/useRetrievalStrategies";function AddLlmProfile({editLlmProfileId,@@ -36,6 +43,7 @@ function AddLlmProfile({const [resetForm, setResetForm] = useState(false);const [backendErrors, setBackendErrors] = useState(null);const [retrievalItems, setRetrievalItems] = useState([]);+ const [hasLoadedFromApi, setHasLoadedFromApi] = useState(false);const [llmItems, setLlmItems] = useState([]);const [vectorDbItems, setVectorDbItems] = useState([]);const [embeddingItems, setEmbeddingItems] = useState([]);@@ -44,36 +52,47 @@ function AddLlmProfile({const [loading, setLoading] = useState(false);const [modalTitle, setModalTitle] = useState("");const [areAdaptersReady, setAreAdaptersReady] = useState(false);+ const [isRetrievalModalVisible, setIsRetrievalModalVisible] = useState(false);const { sessionDetails } = useSessionStore();- const { details, getDropdownItems, llmProfiles, updateCustomTool } =- useCustomToolStore();+ const { details, llmProfiles, updateCustomTool } = useCustomToolStore();const { setAlertDetails } = useAlertStore();const axiosPrivate = useAxiosPrivate();const { token } = theme.useToken();const handleException = useExceptionHandler();const { setPostHogCustomEvent } = usePostHogEvents();- const panelStyle = {- marginBottom: 16,- };+ const { getStrategies } = useRetrievalStrategies();useEffect(() => {setAdaptorProfilesDropdown();- const data = getDropdownItems("retrieval_strategy");- if (!data) {- return;- }- const items = Object.keys(data).map((name) => {- return {- value: data[name],- };- });- setRetrievalItems(items);return () => {setEditLlmProfileId(null);};}, []);+ // Load retrieval strategies when tool_id is available (only once)+ useEffect(() => {+ if (details?.tool_id && !hasLoadedFromApi) {+ const loadStrategies = async () => {+ try {+ const strategies = await getStrategies(details.tool_id);+ const items =+ strategies?.map((strategy) => ({+ value: strategy?.key,+ label: strategy?.title,+ })) || [];+ setRetrievalItems(items);+ setHasLoadedFromApi(true);+ } catch (error) {+ console.error("Error loading retrieval strategies:", error);+ setHasLoadedFromApi(true);+ }+ };++ loadStrategies();+ }+ }, [details?.tool_id, hasLoadedFromApi]); // getStrategies intentionally omitted to prevent infinite re-renders+useEffect(() => {if (editLlmProfileId) {return;@@ -243,11 +262,11 @@ function AddLlmProfile({});};- const getItems = (panelStyle) => [+ const getItems = () => [{key: "1",label: "Advanced Settings",- style: panelStyle,+ className: "add-llm-profile-panel",children: (<div><Form.Item@@ -260,7 +279,35 @@ function AddLlmProfile({}help={getBackendErrorDetail("retrieval_strategy", backendErrors)}>- <Select options={retrievalItems} />+ <button+ type="button"+ className="retrieval-strategy-selector"+ onClick={handleRetrievalModalOpen}+ aria-label="Select retrieval strategy"+ aria-expanded={isRetrievalModalVisible}+ aria-haspopup="dialog"+ >+ <span+ className={`retrieval-strategy-text ${+ formDetails.retrieval_strategy+ ? "retrieval-strategy-text--selected"+ : "retrieval-strategy-text--placeholder"+ }`}+ >+ {formDetails.retrieval_strategy+ ? retrievalItems.find(+ (item) => item.value === formDetails.retrieval_strategy+ )?.label || "Select retrieval strategy"+ : "Select retrieval strategy"}+ </span>+ <div className="retrieval-strategy-actions">+ <SettingOutlined+ className="retrieval-strategy-settings-icon"+ title="Configure retrieval strategy"+ />+ <DownOutlined className="retrieval-strategy-dropdown-icon" />+ </div>+ </button></Form.Item><Form.Itemlabel="Matching count limit (similarity top-k)"@@ -401,6 +448,34 @@ function AddLlmProfile({return tokenSize;}+ const handleRetrievalModalOpen = () => {+ setIsRetrievalModalVisible(true);+ };++ const handleRetrievalStrategySelect = (strategy) => {+ const strategyLabel =+ retrievalItems.find((item) => item.value === strategy)?.label || strategy;+ form.setFieldsValue({ retrieval_strategy: strategy });+ setFormDetails({ ...formDetails, retrieval_strategy: strategy });+ setIsRetrievalModalVisible(false);++ // Clear any existing backend errors for this field+ setBackendErrors((prevErrors) => {+ if (prevErrors) {+ const updatedErrors = prevErrors.errors.filter(+ (error) => error.attr !== "retrieval_strategy"+ );+ return { ...prevErrors, errors: updatedErrors };+ }+ return null;+ });++ setAlertDetails({+ type: "success",+ content: `Retrieval strategy set to: ${strategyLabel}`,+ });+ };+return (<div className="settings-body-pad-top"><Form@@ -576,7 +651,7 @@ function AddLlmProfile({style={{background: token.colorBgContainer,}}- items={getItems(panelStyle)}+ items={getItems()}activeKey={activeKey && "1"}onChange={handleCollapse}/>@@ -590,6 +665,14 @@ function AddLlmProfile({</Space></Form.Item></Form>++ <RetrievalStrategyModal+ visible={isRetrievalModalVisible}+ onCancel={() => setIsRetrievalModalVisible(false)}+ onOk={handleRetrievalStrategySelect}+ currentStrategy={formDetails.retrieval_strategy}+ loading={false}+ /></div>);}diff --git a/frontend/src/components/custom-tools/retrieval-strategy-modal/RetrievalStrategyModal.css b/frontend/src/components/custom-tools/retrieval-strategy-modal/RetrievalStrategyModal.cssnew file mode 100644index 000000000..ea4940b2d--- /dev/null+++ b/frontend/src/components/custom-tools/retrieval-strategy-modal/RetrievalStrategyModal.css@@ -0,0 +1,217 @@+.retrieval-strategy-modal .ant-modal-header {+ border-bottom: 1px solid #f0f0f0;+ padding: 16px 24px;+}++.retrieval-strategy-modal .ant-modal-body {+ padding: 24px;+ max-height: 70vh;+ overflow-y: auto;+}++.retrieval-strategy-modal .ant-radio-group {+ display: flex;+ flex-direction: column;+ gap: 12px;+}++.retrieval-strategy-modal .ant-radio-wrapper {+ display: flex;+ align-items: flex-start;+ padding: 12px;+ border: 1px solid #f0f0f0;+ border-radius: 6px;+ transition: all 0.3s ease;+}++.retrieval-strategy-modal .ant-radio-wrapper:hover {+ border-color: #1890ff;+ background-color: #f6ffed;+}++.retrieval-strategy-modal .ant-radio-wrapper-checked {+ border-color: #1890ff;+ background-color: #e6f7ff;+}++.retrieval-strategy-modal .ant-typography h4 {+ margin-bottom: 8px;+ color: #262626;+}++.retrieval-strategy-modal .ant-typography p {+ color: #595959;+ line-height: 1.5;+}++.retrieval-strategy-modal ul {+ padding-left: 20px;+}++.retrieval-strategy-modal ul li {+ margin-bottom: 4px;+ color: #595959;+}++.retrieval-strategy-modal .ant-divider {+ margin: 16px 0;+}++.retrieval-strategy-modal .resource-impact-item {+ display: flex;+ align-items: center;+ gap: 8px;+ margin-bottom: 8px;+}++.retrieval-strategy-modal .resource-impact-item .anticon {+ color: #8c8c8c;+}++.retrieval-strategy-modal .technical-details {+ background-color: #fafafa;+ padding: 12px;+ border-radius: 4px;+ border-left: 3px solid #1890ff;+}++.retrieval-strategy-modal .strategy-icon {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 20px;+ height: 20px;+ margin-right: 8px;+}++/* New styles for inline style replacement */+.retrieval-strategy-modal__loading {+ text-align: center;+ padding: 40px 0;+}++.retrieval-strategy-modal__alert {+ margin-bottom: 16px;+}++.retrieval-strategy-modal__content {+ display: flex;+ gap: 16px;+}++.retrieval-strategy-modal__selection {+ flex: 1;+}++.retrieval-strategy-modal__radio-group {+ width: 100%;+}++.retrieval-strategy-modal__radio-space {+ width: 100%;+}++.retrieval-strategy-modal__radio-item {+ width: 100%;+}++.retrieval-strategy-modal__radio-content {+ display: flex;+ align-items: center;+ gap: 8px;+}++.retrieval-strategy-modal__selected-indicator {+ font-size: 12px;+ margin-left: 8px;+ font-weight: normal;+}++.retrieval-strategy-modal__empty-state {+ text-align: center;+ padding: 20px 0;+}++.retrieval-strategy-modal__details {+ flex: 1.5;+ padding-left: 16px;+ border-left: 1px solid #f0f0f0;+}++.retrieval-strategy-modal__title {+ margin-bottom: 8px;+}++.retrieval-strategy-modal__description {+ margin-bottom: 16px;+}++.retrieval-strategy-modal__best-for {+ margin-bottom: 16px;+}++.retrieval-strategy-modal__best-for-list {+ margin-top: 8px;+ margin-bottom: 0;+}++.retrieval-strategy-modal__performance {+ margin-bottom: 16px;+}++.retrieval-strategy-modal__performance-content {+ margin-top: 8px;+}++.retrieval-strategy-modal__performance-item {+ margin-bottom: 8px;+}++.retrieval-strategy-modal__technical-details {+ margin-top: 8px;+ font-size: 12px;+}++.retrieval-strategy-modal__token-usage-low {+ color: #52c41a;+}++.retrieval-strategy-modal__token-usage-medium {+ color: #faad14;+}++.retrieval-strategy-modal__token-usage-high {+ color: #ff4d4f;+}++.retrieval-strategy-modal__cost-impact-low {+ color: #52c41a;+}++.retrieval-strategy-modal__cost-impact-medium {+ color: #faad14;+}++.retrieval-strategy-modal__cost-impact-high {+ color: #ff4d4f;+}++/* Responsive adjustments */+@media (max-width: 768px) {+ .retrieval-strategy-modal {+ width: 95% !important;+ max-width: none !important;+ }++ .retrieval-strategy-modal__content {+ flex-direction: column;+ }++ .retrieval-strategy-modal__details {+ border-left: none;+ border-top: 1px solid #f0f0f0;+ padding-left: 0;+ padding-top: 16px;+ margin-top: 16px;+ }+}diff --git a/frontend/src/components/custom-tools/retrieval-strategy-modal/RetrievalStrategyModal.jsx b/frontend/src/components/custom-tools/retrieval-strategy-modal/RetrievalStrategyModal.jsxnew file mode 100644index 000000000..be08afebd--- /dev/null+++ b/frontend/src/components/custom-tools/retrieval-strategy-modal/RetrievalStrategyModal.jsx@@ -0,0 +1,277 @@+import { useState, useEffect } from "react";+import {+ Modal,+ Radio,+ Space,+ Typography,+ Button,+ Alert,+ Divider,+ Spin,+} from "antd";+import {+ SearchOutlined,+ QuestionCircleOutlined,+ ForkOutlined,+ ReloadOutlined,+ ShareAltOutlined,+ TableOutlined,+ MergeCellsOutlined,+} from "@ant-design/icons";+import PropTypes from "prop-types";+import { useParams } from "react-router-dom";++import { useRetrievalStrategies } from "../../../hooks/useRetrievalStrategies";+import "./RetrievalStrategyModal.css";++const { Title, Text, Paragraph } = Typography;++const ICON_MAP = {+ SearchOutlined: <SearchOutlined />,+ QuestionCircleOutlined: <QuestionCircleOutlined />,+ ForkOutlined: <ForkOutlined />,+ ReloadOutlined: <ReloadOutlined />,+ ShareAltOutlined: <ShareAltOutlined />,+ TableOutlined: <TableOutlined />,+ MergeCellsOutlined: <MergeCellsOutlined />,+};++const RetrievalStrategyModal = ({+ visible,+ onCancel,+ onOk,+ currentStrategy = "simple",+ loading = false,+}) => {+ const [selectedStrategy, setSelectedStrategy] = useState(+ currentStrategy || "simple"+ );++ // Update selectedStrategy when currentStrategy prop changes or modal opens+ useEffect(() => {+ if (visible && currentStrategy) {+ setSelectedStrategy(currentStrategy);+ }+ }, [currentStrategy, visible]);+ const { id } = useParams();+ const {+ strategies,+ isLoading: isLoadingStrategies,+ getStrategies,+ } = useRetrievalStrategies();++ useEffect(() => {+ if (visible && id) {+ getStrategies(id);+ }+ }, [visible, id, getStrategies]);++ const retrievalStrategies = strategies || [];++ // Transform strategies to include React icons+ const strategiesWithIcons = retrievalStrategies.map((strategy) => ({+ ...strategy,+ icon: ICON_MAP[strategy.icon] || <SearchOutlined />,+ }));++ const selectedDetails = strategiesWithIcons.find(+ (s) => s.key === selectedStrategy+ );++ const handleStrategyChange = (e) => {+ setSelectedStrategy(e.target.value);+ };++ const handleSubmit = () => {+ onOk(selectedStrategy);+ };++ const getTokenUsageClassName = (usage) => {+ if (usage.includes("Low"))+ return "retrieval-strategy-modal__token-usage-low";+ if (usage.includes("Medium"))+ return "retrieval-strategy-modal__token-usage-medium";+ if (usage.includes("Very High"))+ return "retrieval-strategy-modal__token-usage-high";+ if (usage.includes("High"))+ return "retrieval-strategy-modal__token-usage-high";+ return "";+ };++ const getCostImpactClassName = (impact) => {+ if (impact.includes("Low"))+ return "retrieval-strategy-modal__cost-impact-low";+ if (impact.includes("Medium"))+ return "retrieval-strategy-modal__cost-impact-medium";+ if (impact.includes("Very High"))+ return "retrieval-strategy-modal__cost-impact-high";+ if (impact.includes("High"))+ return "retrieval-strategy-modal__cost-impact-high";+ return "";+ };++ return (+ <Modal+ title="Retrieval Strategy Selection"+ open={visible}+ onCancel={onCancel}+ width={900}+ aria-label="Retrieval Strategy Selection Dialog"+ aria-describedby="retrieval-strategy-description"+ footer={[+ <Button key="cancel" onClick={onCancel}>+ Cancel+ </Button>,+ <Button+ key="submit"+ type="primary"+ onClick={handleSubmit}+ loading={loading}+ >+ Select Strategy+ </Button>,+ ]}+ className="retrieval-strategy-modal"+ >+ {isLoadingStrategies ? (+ <div className="retrieval-strategy-modal__loading">+ <Spin size="large" tip="Loading strategies..." />+ </div>+ ) : (+ <>+ <Alert+ id="retrieval-strategy-description"+ message="Choose Your Retrieval Strategy"+ description="Different retrieval strategies optimize for various use cases. Consider your document types, query complexity, and performance requirements when selecting."+ type="info"+ showIcon+ className="retrieval-strategy-modal__alert"+ />++ <div className="retrieval-strategy-modal__content">+ {/* Strategy Selection */}+ <div className="retrieval-strategy-modal__selection">+ <Radio.Group+ value={selectedStrategy}+ onChange={handleStrategyChange}+ className="retrieval-strategy-modal__radio-group"+ >+ <Space+ direction="vertical"+ className="retrieval-strategy-modal__radio-space"+ >+ {strategiesWithIcons.length > 0 ? (+ strategiesWithIcons.map((strategy) => (+ <Radio+ key={strategy?.key}+ value={strategy?.key}+ className="retrieval-strategy-modal__radio-item"+ >+ <div className="retrieval-strategy-modal__radio-content">+ {strategy?.icon}+ <Text strong>{strategy?.title}</Text>+ {strategy?.key === currentStrategy && (+ <Text+ type="success"+ className="retrieval-strategy-modal__selected-indicator"+ >+ (Selected)+ </Text>+ )}+ </div>+ </Radio>+ ))+ ) : (+ <div className="retrieval-strategy-modal__empty-state">+ <Text type="secondary">+ No retrieval strategies available. Please try refreshing+ the page.+ </Text>+ </div>+ )}+ </Space>+ </Radio.Group>+ </div>++ {/* Strategy Details */}+ <div className="retrieval-strategy-modal__details">+ {selectedDetails && (+ <>+ <Title level={4} className="retrieval-strategy-modal__title">+ {selectedDetails?.title}+ </Title>++ <Paragraph className="retrieval-strategy-modal__description">+ {selectedDetails?.description}+ </Paragraph>++ <div className="retrieval-strategy-modal__best-for">+ <Text strong>Best For:</Text>+ <ul className="retrieval-strategy-modal__best-for-list">+ {selectedDetails?.bestFor &&+ selectedDetails?.bestFor?.length > 0 ? (+ selectedDetails.bestFor.map((item) => (+ <li key={item}>{item}</li>+ ))+ ) : (+ <li>No specific use cases defined</li>+ )}+ </ul>+ </div>++ <div className="retrieval-strategy-modal__performance">+ <Text strong>Performance Impact:</Text>+ <div className="retrieval-strategy-modal__performance-content">+ <div className="retrieval-strategy-modal__performance-item">+ <Text>Token Usage: </Text>+ <Text+ strong+ className={getTokenUsageClassName(+ selectedDetails?.tokenUsage || "Unknown"+ )}+ >+ {selectedDetails?.tokenUsage || "Unknown"}+ </Text>+ </div>+ <div>+ <Text>Cost Impact: </Text>+ <Text+ strong+ className={getCostImpactClassName(+ selectedDetails?.costImpact || "Unknown"+ )}+ >+ {selectedDetails?.costImpact || "Unknown"}+ </Text>+ </div>+ </div>+ </div>++ <Divider />++ <div>+ <Text strong>Technical Details:</Text>+ <Paragraph className="retrieval-strategy-modal__technical-details">+ {selectedDetails?.technicalDetails ||+ "No technical details available"}+ </Paragraph>+ </div>+ </>+ )}+ </div>+ </div>+ </>+ )}+ </Modal>+ );+};++RetrievalStrategyModal.propTypes = {+ visible: PropTypes.bool.isRequired,+ onCancel: PropTypes.func.isRequired,+ onOk: PropTypes.func.isRequired,+ currentStrategy: PropTypes.string,+ loading: PropTypes.bool,+};++export default RetrievalStrategyModal;diff --git a/frontend/src/hooks/useRetrievalStrategies.js b/frontend/src/hooks/useRetrievalStrategies.jsnew file mode 100644index 000000000..d4c94619a--- /dev/null+++ b/frontend/src/hooks/useRetrievalStrategies.js@@ -0,0 +1,91 @@+import { useCallback } from "react";++import { usePromptStudioService } from "../components/api/prompt-studio-service";+import { useRetrievalStrategiesStore } from "../store/retrieval-strategies-store";++const ICON_MAP = {+ SearchOutlined: "SearchOutlined",+ QuestionCircleOutlined: "QuestionCircleOutlined",+ ForkOutlined: "ForkOutlined",+ ReloadOutlined: "ReloadOutlined",+ ShareAltOutlined: "ShareAltOutlined",+ TableOutlined: "TableOutlined",+ MergeCellsOutlined: "MergeCellsOutlined",+};++export const useRetrievalStrategies = () => {+ const {+ strategies,+ isLoading,+ error,+ setStrategies,+ setLoading,+ setError,+ shouldFetch,+ } = useRetrievalStrategiesStore();++ const { getRetrievalStrategies } = usePromptStudioService();++ const fetchStrategies = useCallback(+ async (toolId) => {+ // Check if we need to fetch (not cached or cache expired)+ if (!shouldFetch()) {+ return strategies;+ }++ setLoading(true);++ try {+ const data = await getRetrievalStrategies(toolId);++ // Transform the backend data to match our frontend format+ const transformedStrategies = Object.values(data).map((strategy) => ({+ ...strategy,+ icon: ICON_MAP[strategy.icon] || "SearchOutlined",+ bestFor: strategy.best_for || [],+ tokenUsage: strategy.token_usage || "Unknown",+ costImpact: strategy.cost_impact || "Unknown",+ technicalDetails: strategy.technical_details || "",+ }));++ setStrategies(transformedStrategies);+ return transformedStrategies;+ } catch (error) {+ console.error("Error fetching retrieval strategies:", error);+ setError(error.message);++ // Don't return hardcoded fallback - let the calling component handle the error+ throw error;+ }+ },+ [+ shouldFetch,+ strategies,+ setStrategies,+ setLoading,+ setError,+ getRetrievalStrategies,+ ]+ );++ const getStrategies = useCallback(+ (toolId) => {+ // If we have cached strategies and they're not expired, return them immediately+ if (strategies && !shouldFetch()) {+ return Promise.resolve(strategies);+ }++ // Otherwise fetch from API+ return fetchStrategies(toolId);+ },+ [strategies, shouldFetch, fetchStrategies]+ );++ return {+ strategies,+ isLoading,+ error,+ getStrategies,+ fetchStrategies,+ };+};diff --git a/frontend/src/store/retrieval-strategies-store.js b/frontend/src/store/retrieval-strategies-store.jsnew file mode 100644index 000000000..46645b751--- /dev/null+++ b/frontend/src/store/retrieval-strategies-store.js@@ -0,0 +1,43 @@+import { create } from "zustand";++const defaultState = {+ strategies: null,+ isLoading: false,+ error: null,+ lastFetched: null,+};++const useRetrievalStrategiesStore = create((set, get) => ({+ ...defaultState,++ setStrategies: (strategies) =>+ set({+ strategies,+ isLoading: false,+ error: null,+ lastFetched: Date.now(),+ }),++ setLoading: (isLoading) => set({ isLoading }),++ setError: (error) =>+ set({+ error,+ isLoading: false,+ }),++ clearStrategies: () => set({ ...defaultState }),++ // Check if strategies need to be fetched (cache for 1 hour)+ shouldFetch: () => {+ const { strategies, lastFetched } = get();+ if (!strategies) return true;++ const oneHour = 60 * 60 * 1000; // 1 hour in milliseconds+ const now = Date.now();++ return !lastFetched || now - lastFetched > oneHour;+ },+}));++export { useRetrievalStrategiesStore };diff --git a/prompt-service/src/unstract/prompt_service/constants.py b/prompt-service/src/unstract/prompt_service/constants.pyindex d41d246ba..03a57def6 100644--- a/prompt-service/src/unstract/prompt_service/constants.py+++ b/prompt-service/src/unstract/prompt_service/constants.py@@ -25,8 +25,6 @@ class PromptServiceConstants:IS_ASSERT = "is_assert"ASSERTION_FAILURE_PROMPT = "assertion_failure_prompt"RETRIEVAL_STRATEGY = "retrieval-strategy"- SIMPLE = "simple"- SUBQUESTION = "subquestion"TYPE = "type"NUMBER = "number"EMAIL = "email"@@ -148,6 +146,18 @@ class VariableType(str, Enum):DYNAMIC = "DYNAMIC"+class RetrievalStrategy(str, Enum):+ """Available retrieval strategies for prompt service."""++ SIMPLE = "simple"+ SUBQUESTION = "subquestion"+ FUSION = "fusion"+ RECURSIVE = "recursive"+ ROUTER = "router"+ KEYWORD_TABLE = "keyword_table"+ AUTOMERGING = "automerging"++class VariableConstants:"""Constants for variable extraction."""diff --git a/prompt-service/src/unstract/prompt_service/controllers/answer_prompt.py b/prompt-service/src/unstract/prompt_service/controllers/answer_prompt.pyindex b48d7f93c..35ad2d5c0 100644--- a/prompt-service/src/unstract/prompt_service/controllers/answer_prompt.py+++ b/prompt-service/src/unstract/prompt_service/controllers/answer_prompt.py@@ -7,7 +7,7 @@ from flask import current_app as appfrom unstract.core.flask.exceptions import APIErrorfrom unstract.prompt_service.constants import PromptServiceConstants as PSKeys-from unstract.prompt_service.constants import RunLevel+from unstract.prompt_service.constants import RetrievalStrategy, RunLevelfrom unstract.prompt_service.exceptions import BadRequestfrom unstract.prompt_service.helpers.auth import AuthHelperfrom unstract.prompt_service.helpers.plugin import PluginManager@@ -372,7 +372,10 @@ def prompt_processor() -> Any:retrieval_strategy = output.get(PSKeys.RETRIEVAL_STRATEGY)- if retrieval_strategy in {PSKeys.SIMPLE, PSKeys.SUBQUESTION}:+ # Get all valid retrieval strategies+ valid_strategies = {strategy.value for strategy in RetrievalStrategy}++ if retrieval_strategy in valid_strategies:app.logger.info(f"[{tool_id}] Performing retrieval for : {file_path}")answer, context = RetrievalService.perform_retrieval(tool_settings=tool_settings,diff --git a/prompt-service/src/unstract/prompt_service/core/retrievers/automerging.py b/prompt-service/src/unstract/prompt_service/core/retrievers/automerging.pynew file mode 100644index 000000000..3df2a3776--- /dev/null+++ b/prompt-service/src/unstract/prompt_service/core/retrievers/automerging.py@@ -0,0 +1,85 @@+import logging++from llama_index.core import VectorStoreIndex+from llama_index.core.retrievers import AutoMergingRetriever as LlamaAutoMergingRetriever+from llama_index.core.vector_stores import ExactMatchFilter, MetadataFilters++from unstract.prompt_service.core.retrievers.base_retriever import BaseRetriever+from unstract.prompt_service.exceptions import RetrievalError++logger = logging.getLogger(__name__)+++class AutomergingRetriever(BaseRetriever):+ """Automerging retrieval using LlamaIndex's native AutoMergingRetriever.++ This retriever merges smaller chunks into larger ones when the smaller chunks+ don't contain enough information, providing better context for answers.+ """++ def retrieve(self) -> set[str]:+ """Retrieve text chunks using LlamaIndex's native AutoMergingRetriever.++ Returns:+ set[str]: A set of text chunks retrieved from the database.+ """+ try:+ logger.info(+ f"Retrieving chunks for {self.doc_id} using LlamaIndex AutoMergingRetriever."+ )++ # Get the vector store index+ vector_store_index: VectorStoreIndex = self.vector_db.get_vector_store_index()++ # Create base vector retriever with metadata filters+ base_retriever = vector_store_index.as_retriever(+ similarity_top_k=self.top_k,+ filters=MetadataFilters(+ filters=[+ ExactMatchFilter(key="doc_id", value=self.doc_id),+ ],+ ),+ )++ # Try to use native AutoMergingRetriever+ try:+ # Create AutoMergingRetriever with the base retriever+ auto_merging_retriever = LlamaAutoMergingRetriever(+ base_retriever,+ storage_context=self.vector_db.get_storage_context()+ if hasattr(self.vector_db, "get_storage_context")+ else None,+ verbose=False,+ )++ # Retrieve nodes using auto-merging+ nodes = auto_merging_retriever.retrieve(self.prompt)++ except Exception as e:+ logger.error(f"AutoMergingRetriever failed : {e}")+ raise RetrievalError(f"AutoMergingRetriever failed: {str(e)}") from e++ # Extract unique text chunks+ chunks: set[str] = set()+ for node in nodes:+ if node.score > 0:+ chunks.add(node.get_content())+ else:+ logger.info(+ f"Node score is less than 0. "+ f"Ignored: {node.node_id} with score {node.score}"+ )++ logger.info(+ f"Successfully retrieved {len(chunks)} chunks using AutoMergingRetriever."+ )+ return chunks++ except (ValueError, AttributeError, KeyError, ImportError) as e:+ logger.error(f"Error during auto-merging retrieval for {self.doc_id}: {e}")+ raise RetrievalError(str(e)) from e+ except Exception as e:+ logger.error(+ f"Unexpected error during auto-merging retrieval for {self.doc_id}: {e}"+ )+ raise RetrievalError(f"Unexpected error: {str(e)}") from ediff --git a/prompt-service/src/unstract/prompt_service/core/retrievers/fusion.py b/prompt-service/src/unstract/prompt_service/core/retrievers/fusion.pynew file mode 100644index 000000000..99f24516e--- /dev/null+++ b/prompt-service/src/unstract/prompt_service/core/retrievers/fusion.py@@ -0,0 +1,94 @@+import logging++from llama_index.core import VectorStoreIndex+from llama_index.core.retrievers import QueryFusionRetriever+from llama_index.core.vector_stores import ExactMatchFilter, MetadataFilters++from unstract.prompt_service.core.retrievers.base_retriever import BaseRetriever+from unstract.prompt_service.exceptions import RetrievalError++logger = logging.getLogger(__name__)+++class FusionRetriever(BaseRetriever):+ """Fusion retrieval class using LlamaIndex's native QueryFusionRetriever.++ This technique generates multiple query variations and combines results+ using reciprocal rank fusion for improved relevance.+ """++ def retrieve(self) -> set[str]:+ """Retrieve text chunks using LlamaIndex's QueryFusionRetriever.++ Returns:+ set[str]: A set of text chunks retrieved from the database.+ """+ try:+ logger.info(+ f"Retrieving chunks for {self.doc_id} using LlamaIndex QueryFusionRetriever."+ )++ # Get the vector store index+ vector_store_index: VectorStoreIndex = self.vector_db.get_vector_store_index()++ # Create multiple retrievers with different parameters for true fusion+ filters = MetadataFilters(+ filters=[+ ExactMatchFilter(key="doc_id", value=self.doc_id),+ ],+ )++ # Retriever 1: Standard similarity search+ retriever_1 = vector_store_index.as_retriever(+ similarity_top_k=self.top_k,+ filters=filters,+ )++ # Retriever 2: Broader search with more candidates+ retriever_2 = vector_store_index.as_retriever(+ similarity_top_k=self.top_k * 2,+ filters=filters,+ )++ # Retriever 3: Focused search with fewer candidates+ retriever_3 = vector_store_index.as_retriever(+ similarity_top_k=max(1, self.top_k // 2),+ filters=filters,+ )++ # Create LlamaIndex QueryFusionRetriever with multiple retrievers+ fusion_retriever = QueryFusionRetriever(+ [retriever_1, retriever_2, retriever_3], # Multiple retrievers for fusion+ similarity_top_k=self.top_k,+ num_queries=4, # Generate multiple query variations+ mode="simple", # Use simple fusion mode (reciprocal rank fusion)+ use_async=False,+ verbose=True,+ llm=self.llm, # LLM generates query variations+ )++ # Retrieve nodes using fusion technique+ nodes = fusion_retriever.retrieve(self.prompt)++ # Extract unique text chunks+ chunks: set[str] = set()+ for node in nodes:+ if node.score > 0:+ chunks.add(node.get_content())+ else:+ logger.info(+ f"Node score is less than 0. "+ f"Ignored: {node.node_id} with score {node.score}"+ )++ logger.info(f"Successfully retrieved {len(chunks)} chunks using fusion.")+ return chunks++ except (ValueError, AttributeError, KeyError, ImportError) as e:+ logger.error(f"Error during fusion retrieval for {self.doc_id}: {e}")+ raise RetrievalError(str(e)) from e+ except Exception as e:+ logger.error(+ f"Unexpected error during fusion retrieval for {self.doc_id}: {e}"+ )+ raise RetrievalError(f"Unexpected error: {str(e)}") from ediff --git a/prompt-service/src/unstract/prompt_service/core/retrievers/keyword_table.py b/prompt-service/src/unstract/prompt_service/core/retrievers/keyword_table.pynew file mode 100644index 000000000..8d92a7154--- /dev/null+++ b/prompt-service/src/unstract/prompt_service/core/retrievers/keyword_table.py@@ -0,0 +1,79 @@+import logging++from llama_index.core import VectorStoreIndex+from llama_index.core.indices.keyword_table import KeywordTableIndex+from llama_index.core.vector_stores import ExactMatchFilter, MetadataFilters++from unstract.prompt_service.core.retrievers.base_retriever import BaseRetriever+from unstract.prompt_service.exceptions import RetrievalError++logger = logging.getLogger(__name__)+++class KeywordTableRetriever(BaseRetriever):+ """Keyword table retrieval using LlamaIndex's native KeywordTableIndex."""++ def retrieve(self) -> set[str]:+ """Retrieve text chunks using LlamaIndex's native KeywordTableIndex.++ Returns:+ set[str]: A set of text chunks retrieved from the database.+ """+ try:+ logger.info(+ f"Retrieving chunks for {self.doc_id} using LlamaIndex KeywordTableIndex."+ )++ # Get documents from vector index for keyword indexing+ vector_store_index: VectorStoreIndex = self.vector_db.get_vector_store_index()++ # Get all nodes for the document+ all_retriever = vector_store_index.as_retriever(+ similarity_top_k=1000, # Get all nodes+ filters=MetadataFilters(+ filters=[+ ExactMatchFilter(key="doc_id", value=self.doc_id),+ ],+ ),+ )++ # Retrieve all nodes to build keyword index+ all_nodes = all_retriever.retrieve(" ")++ if not all_nodes:+ logger.warning(f"No nodes found for doc_id: {self.doc_id}")+ return set()++ # Create KeywordTableIndex from nodes using our provided LLM+ keyword_index = KeywordTableIndex(+ nodes=[node.node for node in all_nodes],+ show_progress=True,+ llm=self.llm, # Use the provided LLM instead of defaulting to OpenAI+ )++ # Create retriever from keyword index+ keyword_retriever = keyword_index.as_retriever(+ similarity_top_k=self.top_k,+ )++ # Retrieve nodes using keyword matching+ nodes = keyword_retriever.retrieve(self.prompt)++ # Extract unique text chunks+ chunks: set[str] = set()+ for node in nodes:+ chunks.add(node.get_content())++ logger.info(+ f"Successfully retrieved {len(chunks)} chunks using KeywordTableIndex."+ )+ return chunks++ except (ValueError, AttributeError, KeyError, ImportError) as e:+ logger.error(f"Error during keyword retrieval for {self.doc_id}: {e}")+ raise RetrievalError(str(e)) from e+ except Exception as e:+ logger.error(+ f"Unexpected error during keyword retrieval for {self.doc_id}: {e}"+ )+ raise RetrievalError(f"Unexpected error: {str(e)}") from ediff --git a/prompt-service/src/unstract/prompt_service/core/retrievers/recursive.py b/prompt-service/src/unstract/prompt_service/core/retrievers/recursive.pynew file mode 100644index 000000000..dcec3d617--- /dev/null+++ b/prompt-service/src/unstract/prompt_service/core/retrievers/recursive.py@@ -0,0 +1,77 @@+import logging++from llama_index.core import VectorStoreIndex+from llama_index.core.retrievers import RecursiveRetriever+from llama_index.core.vector_stores import ExactMatchFilter, MetadataFilters++from unstract.prompt_service.core.retrievers.base_retriever import BaseRetriever+from unstract.prompt_service.exceptions import RetrievalError++logger = logging.getLogger(__name__)+++class RecursiveRetrieval(BaseRetriever):+ """Recursive retrieval using LlamaIndex's native RecursiveRetriever.++ This retriever performs recursive retrieval by breaking down queries+ and refining results through multiple retrieval steps.+ """++ def retrieve(self) -> set[str]:+ """Retrieve text chunks using LlamaIndex's native RecursiveRetriever.++ Returns:+ set[str]: A set of text chunks retrieved from the database.+ """+ try:+ logger.info(+ f"Retrieving chunks for {self.doc_id} using LlamaIndex RecursiveRetriever."+ )++ # Get the vector store index+ vector_store_index: VectorStoreIndex = self.vector_db.get_vector_store_index()++ # Create base retriever with metadata filters+ base_retriever = vector_store_index.as_retriever(+ similarity_top_k=self.top_k,+ filters=MetadataFilters(+ filters=[+ ExactMatchFilter(key="doc_id", value=self.doc_id),+ ],+ ),+ )++ # Create RecursiveRetriever+ recursive_retriever = RecursiveRetriever(+ "vector", # root retriever key+ retriever_dict={"vector": base_retriever},+ verbose=True,+ )++ # Retrieve nodes using RecursiveRetriever+ nodes = recursive_retriever.retrieve(self.prompt)++ # Extract unique text chunks+ chunks: set[str] = set()+ for node in nodes:+ if node.score > 0:+ chunks.add(node.get_content())+ else:+ logger.info(+ f"Node score is less than 0. "+ f"Ignored: {node.node_id} with score {node.score}"+ )++ logger.info(+ f"Successfully retrieved {len(chunks)} chunks using RecursiveRetriever."+ )+ return chunks++ except (ValueError, AttributeError, KeyError, ImportError) as e:+ logger.error(f"Error during recursive retrieval for {self.doc_id}: {e}")+ raise RetrievalError(str(e)) from e+ except Exception as e:+ logger.error(+ f"Unexpected error during recursive retrieval for {self.doc_id}: {e}"+ )+ raise RetrievalError(f"Unexpected error: {str(e)}") from ediff --git a/prompt-service/src/unstract/prompt_service/core/retrievers/router.py b/prompt-service/src/unstract/prompt_service/core/retrievers/router.pynew file mode 100644index 000000000..b5bc4efe1--- /dev/null+++ b/prompt-service/src/unstract/prompt_service/core/retrievers/router.py@@ -0,0 +1,157 @@+import logging++from llama_index.core import VectorStoreIndex+from llama_index.core.query_engine import RouterQueryEngine+from llama_index.core.selectors import LLMSingleSelector+from llama_index.core.tools import QueryEngineTool, ToolMetadata+from llama_index.core.vector_stores import ExactMatchFilter, MetadataFilters++from unstract.prompt_service.core.retrievers.base_retriever import BaseRetriever+from unstract.prompt_service.exceptions import RetrievalError++logger = logging.getLogger(__name__)+++class RouterRetriever(BaseRetriever):+ """Router retrieval class using LlamaIndex's native RouterQueryEngine.++ This technique intelligently routes queries to different retrieval strategies+ based on query analysis.+ """++ def _create_metadata_filters(self):+ """Create metadata filters for doc_id."""+ return MetadataFilters(+ filters=[+ ExactMatchFilter(key="doc_id", value=self.doc_id),+ ],+ )++ def _create_base_query_engine(self, vector_store_index, filters):+ """Create the base vector query engine."""+ return vector_store_index.as_query_engine(+ similarity_top_k=self.top_k,+ filters=filters,+ llm=self.llm,+ )++ def _add_keyword_search_tool(self, query_engine_tools, vector_store_index, filters):+ """Add keyword search tool to query engine tools list."""+ try:+ keyword_query_engine = vector_store_index.as_query_engine(+ similarity_top_k=self.top_k * 2,+ filters=filters,+ llm=self.llm,+ )+ query_engine_tools.append(+ QueryEngineTool(+ query_engine=keyword_query_engine,+ metadata=ToolMetadata(+ name="keyword_search",+ description=(+ "Best for finding specific terms, names, numbers, dates, "+ "or exact phrases. Use when looking for precise matches."+ ),+ ),+ )+ )+ except Exception as e:+ logger.debug(f"Could not create keyword search engine: {e}")++ def _add_broad_search_tool(self, query_engine_tools, vector_store_index, filters):+ """Add broad search tool to query engine tools list."""+ try:+ broad_query_engine = vector_store_index.as_query_engine(+ similarity_top_k=self.top_k * 3,+ filters=filters,+ llm=self.llm,+ )+ query_engine_tools.append(+ QueryEngineTool(+ query_engine=broad_query_engine,+ metadata=ToolMetadata(+ name="broad_search",+ description=(+ "Useful for general questions, exploratory queries, "+ "or when you need comprehensive information on a topic."+ ),+ ),+ )+ )+ except Exception as e:+ logger.debug(f"Could not create broad search engine: {e}")++ def _extract_chunks_from_response(self, response):+ """Extract chunks from router query response."""+ chunks: set[str] = set()+ if hasattr(response, "source_nodes"):+ for node in response.source_nodes:+ if node.score > 0:+ chunks.add(node.get_content())+ else:+ logger.info(+ f"Node score is less than 0. "+ f"Ignored: {node.node_id} with score {node.score}"+ )+ return chunks++ def retrieve(self) -> set[str]:+ """Retrieve text chunks using LlamaIndex's RouterQueryEngine.++ Returns:+ set[str]: A set of text chunks retrieved from the database.+ """+ try:+ logger.info(+ f"Retrieving chunks for {self.doc_id} using LlamaIndex RouterQueryEngine."+ )++ vector_store_index: VectorStoreIndex = self.vector_db.get_vector_store_index()+ filters = self._create_metadata_filters()+ vector_query_engine = self._create_base_query_engine(+ vector_store_index, filters+ )++ if not self.llm:+ return set()++ # Create base query engine tools+ query_engine_tools = [+ QueryEngineTool(+ query_engine=vector_query_engine,+ metadata=ToolMetadata(+ name="vector_search",+ description=(+ "Useful for semantic similarity search, conceptual questions, "+ "and finding information based on meaning and context."+ ),+ ),+ ),+ ]++ # Add additional search strategies+ self._add_keyword_search_tool(query_engine_tools, vector_store_index, filters)+ self._add_broad_search_tool(query_engine_tools, vector_store_index, filters)++ # Create and execute router query+ router_query_engine = RouterQueryEngine.from_defaults(+ selector=LLMSingleSelector.from_defaults(llm=self.llm),+ query_engine_tools=query_engine_tools,+ verbose=True,+ llm=self.llm,+ )++ response = router_query_engine.query(self.prompt)+ chunks = self._extract_chunks_from_response(response)++ logger.info(f"Successfully retrieved {len(chunks)} chunks using router.")+ return chunks++ except (ValueError, AttributeError, KeyError, ImportError) as e:+ logger.error(f"Error during router retrieval for {self.doc_id}: {e}")+ raise RetrievalError(str(e)) from e+ except Exception as e:+ logger.error(+ f"Unexpected error during router retrieval for {self.doc_id}: {e}"+ )+ raise RetrievalError(f"Unexpected error: {str(e)}") from ediff --git a/prompt-service/src/unstract/prompt_service/core/retrievers/subquestion.py b/prompt-service/src/unstract/prompt_service/core/retrievers/subquestion.pyindex 9efa9ecd0..af44b76eb 100644--- a/prompt-service/src/unstract/prompt_service/core/retrievers/subquestion.py+++ b/prompt-service/src/unstract/prompt_service/core/retrievers/subquestion.py@@ -51,6 +51,9 @@ class SubquestionRetriever(BaseRetriever):logger.info(f"Successfully retrieved {len(chunks)} chunks.")return chunks- except Exception as e:+ except (ValueError, AttributeError, KeyError, ImportError) as e:logger.error(f"Error during retrieving chunks {self.doc_id}: {e}")raise RetrievalError(str(e)) from e+ except Exception as e:+ logger.error(f"Unexpected error during retrieving chunks {self.doc_id}: {e}")+ raise RetrievalError(f"Unexpected error: {str(e)}") from ediff --git a/prompt-service/src/unstract/prompt_service/helpers/retrieval.py b/prompt-service/src/unstract/prompt_service/helpers/retrieval.pydeleted file mode 100644index 97dd9acc3..000000000--- a/prompt-service/src/unstract/prompt_service/helpers/retrieval.py+++ /dev/null@@ -1,44 +0,0 @@-from typing import Any--from unstract.prompt_service.constants import PromptServiceConstants as PSKeys-from unstract.prompt_service.core.retrievers.simple import SimpleRetriever-from unstract.prompt_service.core.retrievers.subquestion import SubquestionRetriever-from unstract.prompt_service.utils.file_utils import FileUtils-from unstract.sdk.llm import LLM-from unstract.sdk.vector_db import VectorDB---class RetrievalHelper:- @staticmethod- def run_retrieval( # type:ignore- output: dict[str, Any],- doc_id: str,- llm: LLM,- vector_db: VectorDB,- retrieval_type: str,- ) -> set[str]:- context: set[str] = set()- prompt = output[PSKeys.PROMPTX]- top_k = output[PSKeys.SIMILARITY_TOP_K]- if retrieval_type == PSKeys.SUBQUESTION:- context = SubquestionRetriever(- vector_db=vector_db, doc_id=doc_id, prompt=prompt, top_k=top_k, llm=llm- ).retrieve()- if retrieval_type == PSKeys.SIMPLE:- context = SimpleRetriever(- vector_db=vector_db, doc_id=doc_id, prompt=prompt, top_k=top_k- ).retrieve()-- return context-- @staticmethod- def retrieve_complete_context(execution_source: str, file_path: str) -> str:- """Loads full context from raw file for zero chunk size retrieval- Args:- path (str): Path to the directory containing text file.-- Returns:- str: context from extracted file.- """- fs_instance = FileUtils.get_fs_instance(execution_source=execution_source)- return fs_instance.read(path=file_path, mode="r")diff --git a/prompt-service/src/unstract/prompt_service/services/retrieval.py b/prompt-service/src/unstract/prompt_service/services/retrieval.pyindex 6aa3b28dd..848dd6270 100644--- a/prompt-service/src/unstract/prompt_service/services/retrieval.py+++ b/prompt-service/src/unstract/prompt_service/services/retrieval.py@@ -2,6 +2,12 @@ import datetimefrom typing import Anyfrom unstract.prompt_service.constants import PromptServiceConstants as PSKeys+from unstract.prompt_service.constants import RetrievalStrategy+from unstract.prompt_service.core.retrievers.automerging import AutomergingRetriever+from unstract.prompt_service.core.retrievers.fusion import FusionRetriever+from unstract.prompt_service.core.retrievers.keyword_table import KeywordTableRetriever+from unstract.prompt_service.core.retrievers.recursive import RecursiveRetrieval+from unstract.prompt_service.core.retrievers.router import RouterRetrieverfrom unstract.prompt_service.core.retrievers.simple import SimpleRetrieverfrom unstract.prompt_service.core.retrievers.subquestion import SubquestionRetrieverfrom unstract.prompt_service.services.answer_prompt import AnswerPromptService@@ -69,22 +75,32 @@ class RetrievalService:top_k = output[PSKeys.SIMILARITY_TOP_K]prompt_key = output[PSKeys.NAME]retrieval_start_time = datetime.datetime.now()- if retrieval_type == PSKeys.SUBQUESTION:- context = SubquestionRetriever(- vector_db=vector_db,- doc_id=doc_id,- prompt=prompt,- top_k=top_k,- llm=llm,- ).retrieve()- if retrieval_type == PSKeys.SIMPLE:- context = SimpleRetriever(- vector_db=vector_db,- doc_id=doc_id,- prompt=prompt,- top_k=top_k,- llm=llm,- ).retrieve()++ # Map retrieval type to retriever class+ retriever_map = {+ RetrievalStrategy.SIMPLE.value: SimpleRetriever,+ RetrievalStrategy.SUBQUESTION.value: SubquestionRetriever,+ RetrievalStrategy.FUSION.value: FusionRetriever,+ RetrievalStrategy.RECURSIVE.value: RecursiveRetrieval,+ RetrievalStrategy.ROUTER.value: RouterRetriever,+ RetrievalStrategy.KEYWORD_TABLE.value: KeywordTableRetriever,+ RetrievalStrategy.AUTOMERGING.value: AutomergingRetriever,+ }++ # Get the appropriate retriever class+ retriever_class = retriever_map.get(retrieval_type)+ if not retriever_class:+ raise ValueError(f"Unknown retrieval type: {retrieval_type}")++ # Create and execute retriever+ retriever = retriever_class(+ vector_db=vector_db,+ doc_id=doc_id,+ prompt=prompt,+ top_k=top_k,+ llm=llm,+ )+ context = retriever.retrieve()context_retrieval_metrics[prompt_key] = {"time_taken(s)": Metrics.elapsed_time(start_time=retrieval_start_time)}