Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

Enabled settings for exported tool (#360)

Deepak K9f7e0698c89c
diff --git a/backend/prompt_studio/prompt_studio_core/prompt_studio_helper.py b/backend/prompt_studio/prompt_studio_core/prompt_studio_helper.py
index 782385622..8cde1838b 100644
--- a/backend/prompt_studio/prompt_studio_core/prompt_studio_helper.py
+++ b/backend/prompt_studio/prompt_studio_core/prompt_studio_helper.py
@@ -577,10 +577,6 @@ class PromptStudioHelper:
grammar_list.append(grammer_dict)
grammer_dict = {}
- # TODO: Deprecate and remove assertion related elements
- output[TSPKeys.ASSERTION_FAILURE_PROMPT] = prompt.assertion_failure_prompt
- output[TSPKeys.ASSERT_PROMPT] = prompt.assert_prompt
- output[TSPKeys.IS_ASSERT] = prompt.is_assert
output[TSPKeys.PROMPT] = prompt.prompt
output[TSPKeys.ACTIVE] = prompt.active
output[TSPKeys.CHUNK_SIZE] = prompt.profile_manager.chunk_size
@@ -588,9 +584,6 @@ class PromptStudioHelper:
output[TSPKeys.EMBEDDING] = embedding_model
output[TSPKeys.CHUNK_OVERLAP] = prompt.profile_manager.chunk_overlap
output[TSPKeys.LLM] = llm
- output[TSPKeys.PREAMBLE] = tool.preamble
- output[TSPKeys.POSTAMBLE] = tool.postamble
- output[TSPKeys.GRAMMAR] = grammar_list
output[TSPKeys.TYPE] = prompt.enforce_type
output[TSPKeys.NAME] = prompt.prompt_key
output[TSPKeys.RETRIEVAL_STRATEGY] = prompt.profile_manager.retrieval_strategy
@@ -604,9 +597,6 @@ class PromptStudioHelper:
output[TSPKeys.EVAL_SETTINGS][
TSPKeys.EVAL_SETTINGS_EXCLUDE_FAILED
] = tool.exclude_failed
- output[TSPKeys.ENABLE_CHALLENGE] = tool.enable_challenge
- output[TSPKeys.CHALLENGE_LLM] = challenge_llm
- output[TSPKeys.SINGLE_PASS_EXTRACTION_MODE] = tool.single_pass_extraction_mode
for attr in dir(prompt):
if attr.startswith(TSPKeys.EVAL_METRIC_PREFIX):
attr_val = getattr(prompt, attr)
@@ -614,11 +604,22 @@ class PromptStudioHelper:
outputs.append(output)
+ tool_settings = {}
+ tool_settings[TSPKeys.ENABLE_CHALLENGE] = tool.enable_challenge
+ tool_settings[TSPKeys.CHALLENGE_LLM] = challenge_llm
+ tool_settings[TSPKeys.SINGLE_PASS_EXTRACTION_MODE] = (
+ tool.single_pass_extraction_mode
+ )
+ tool_settings[TSPKeys.PREAMBLE] = tool.preamble
+ tool_settings[TSPKeys.POSTAMBLE] = tool.postamble
+ tool_settings[TSPKeys.GRAMMAR] = grammar_list
+
tool_id = str(tool.tool_id)
file_hash = ToolUtils.get_hash_from_file(file_path=doc_path)
payload = {
+ TSPKeys.TOOL_SETTINGS: tool_settings,
TSPKeys.OUTPUTS: outputs,
TSPKeys.TOOL_ID: tool_id,
TSPKeys.RUN_ID: run_id,
diff --git a/backend/prompt_studio/prompt_studio_registry/constants.py b/backend/prompt_studio/prompt_studio_registry/constants.py
index 4c8713636..0b7ab8835 100644
--- a/backend/prompt_studio/prompt_studio_registry/constants.py
+++ b/backend/prompt_studio/prompt_studio_registry/constants.py
@@ -56,8 +56,6 @@ class JsonSchemaKey:
X2TEXT_ADAPTER = "x2text_adapter"
CHUNK_OVERLAP = "chunk-overlap"
LLM = "llm"
- IS_ASSERT = "is_assert"
- ASSERTION_FAILURE_PROMPT = "assertion_failure_prompt"
RETRIEVAL_STRATEGY = "retrieval-strategy"
SIMPLE = "simple"
TYPE = "type"
@@ -77,7 +75,6 @@ class JsonSchemaKey:
WORD = "word"
SYNONYMS = "synonyms"
OUTPUTS = "outputs"
- ASSERT_PROMPT = "assert_prompt"
SECTION = "section"
DEFAULT = "default"
AUTHOR = "author"
@@ -88,6 +85,15 @@ class JsonSchemaKey:
FUNCTION_NAME = "function_name"
PROMPT_REGISTRY_ID = "prompt_registry_id"
NOTES = "NOTES"
+ TOOL_SETTINGS = "tool_settings"
+ ENABLE_CHALLENGE = "enable_challenge"
+ CHALLENGE_LLM = "challenge_llm"
+ ENABLE_SINGLE_PASS_EXTRACTION = "enable_single_pass_extraction"
+ IMAGE_URL = "image_url"
+ IMAGE_NAME = "image_name"
+ IMAGE_TAG = "image_tag"
+ SUMMARIZE_PROMPT = "summarize_prompt"
+ SUMMARIZE_AS_SOURCE = "summarize_as_source"
class SpecKey:
diff --git a/backend/prompt_studio/prompt_studio_registry/prompt_studio_registry_helper.py b/backend/prompt_studio/prompt_studio_registry/prompt_studio_registry_helper.py
index 73b4205db..e7bd232cd 100644
--- a/backend/prompt_studio/prompt_studio_registry/prompt_studio_registry_helper.py
+++ b/backend/prompt_studio/prompt_studio_registry/prompt_studio_registry_helper.py
@@ -2,6 +2,7 @@ import logging
from typing import Any, Optional
from account.models import User
+from adapter_processor.models import AdapterInstance
from django.conf import settings
from django.db import IntegrityError
from prompt_studio.prompt_profile_manager.models import ProfileManager
@@ -41,7 +42,40 @@ class PromptStudioRegistryHelper:
Returns:
dict: spec dict
"""
- spec = Spec(title=str(tool.tool_id), description=tool.description)
+ properties = {
+ "challenge_llm": {
+ "type": "string",
+ "title": "Challenge LLM",
+ "adapterType": "LLM",
+ "description": "LLM to use for challenge",
+ "adapterIdKey": "challenge_llm_adapter_id",
+ },
+ "enable_challenge": {
+ "type": "boolean",
+ "title": "Enable challenge",
+ "default": False,
+ "description": "Enables Challenge",
+ },
+ "summarize_as_source": {
+ "type": "boolean",
+ "title": "Summarize and use summary as source",
+ "default": False,
+ "description": "Enables summary and use summarized content as source",
+ },
+ "single_pass_extraction_mode": {
+ "type": "boolean",
+ "title": "Enable Single pass extraction",
+ "default": False,
+ "description": "Enables single pass extraction",
+ },
+ }
+
+ spec = Spec(
+ title=str(tool.tool_id),
+ description=tool.description,
+ required=[JsonSchemaKey.CHALLENGE_LLM],
+ properties=properties,
+ )
return spec
@staticmethod
@@ -85,14 +119,25 @@ class PromptStudioRegistryHelper:
f"ID {prompt_registry_id}: {e} "
)
return None
+ # The below properties are introduced after 0.20.0
+ # So defaulting to 0.20.0 if the properties are not found
+ image_url = prompt_registry_tool.tool_metadata.get(
+ JsonSchemaKey.IMAGE_URL, "docker:unstract/tool-structure:0.0.20"
+ )
+ image_name = prompt_registry_tool.tool_metadata.get(
+ JsonSchemaKey.IMAGE_NAME, "unstract/tool-structure"
+ )
+ image_tag = prompt_registry_tool.tool_metadata.get(
+ JsonSchemaKey.IMAGE_TAG, "0.0.20"
+ )
return Tool(
tool_uid=prompt_registry_tool.prompt_registry_id,
properties=Properties.from_dict(prompt_registry_tool.tool_property),
spec=Spec.from_dict(prompt_registry_tool.tool_spec),
icon=prompt_registry_tool.icon,
- image_url=settings.STRUCTURE_TOOL_IMAGE_URL,
- image_name=settings.STRUCTURE_TOOL_IMAGE_NAME,
- image_tag=settings.STRUCTURE_TOOL_IMAGE_TAG,
+ image_url=image_url,
+ image_name=image_name,
+ image_tag=image_tag,
)
@staticmethod
@@ -197,14 +242,45 @@ class PromptStudioRegistryHelper:
export_metadata[JsonSchemaKey.DESCRIPTION] = tool.description
export_metadata[JsonSchemaKey.AUTHOR] = tool.author
export_metadata[JsonSchemaKey.TOOL_ID] = str(tool.tool_id)
+ export_metadata[JsonSchemaKey.IMAGE_URL] = settings.STRUCTURE_TOOL_IMAGE_URL
+ export_metadata[JsonSchemaKey.IMAGE_NAME] = settings.STRUCTURE_TOOL_IMAGE_NAME
+ export_metadata[JsonSchemaKey.IMAGE_TAG] = settings.STRUCTURE_TOOL_IMAGE_TAG
+
+ default_llm_profile = ProfileManager.get_default_llm_profile(tool)
+ challenge_llm_instance: Optional[AdapterInstance] = tool.challenge_llm
+ challenge_llm: Optional[str] = None
+ # Using default profile manager llm if challenge_llm is None
+ if challenge_llm_instance:
+ challenge_llm = str(challenge_llm_instance.id)
+ else:
+ challenge_llm = str(default_llm_profile.llm.id)
- vector_db = ""
embedding_suffix = ""
adapter_id = ""
- llm = ""
- embedding_model = ""
+ vector_db = str(default_llm_profile.vector_store.id)
+ embedding_model = str(default_llm_profile.embedding_model.id)
+ llm = str(default_llm_profile.llm.id)
+ x2text = str(default_llm_profile.x2text.id)
+
+ # Tool settings
+ tool_settings = {}
+ tool_settings[JsonSchemaKey.SUMMARIZE_PROMPT] = tool.summarize_prompt
+ tool_settings[JsonSchemaKey.SUMMARIZE_AS_SOURCE] = tool.summarize_as_source
+ tool_settings[JsonSchemaKey.PREAMBLE] = tool.preamble
+ tool_settings[JsonSchemaKey.POSTAMBLE] = tool.postamble
+ tool_settings[JsonSchemaKey.GRAMMAR] = grammar_list
+ tool_settings[JsonSchemaKey.LLM] = llm
+ tool_settings[JsonSchemaKey.X2TEXT_ADAPTER] = x2text
+ tool_settings[JsonSchemaKey.VECTOR_DB] = vector_db
+ tool_settings[JsonSchemaKey.EMBEDDING] = embedding_model
+ tool_settings[JsonSchemaKey.CHUNK_SIZE] = default_llm_profile.chunk_size
+ tool_settings[JsonSchemaKey.CHUNK_OVERLAP] = default_llm_profile.chunk_overlap
+ tool_settings[JsonSchemaKey.ENABLE_CHALLENGE] = tool.enable_challenge
+ tool_settings[JsonSchemaKey.CHALLENGE_LLM] = challenge_llm
+ tool_settings[JsonSchemaKey.ENABLE_SINGLE_PASS_EXTRACTION] = (
+ tool.single_pass_extraction_mode
+ )
- default_llm_profile = ProfileManager.get_default_llm_profile(tool)
for prompt in prompts:
if not prompt.prompt:
@@ -233,12 +309,6 @@ class PromptStudioRegistryHelper:
adapter_id = str(prompt.profile_manager.embedding_model.adapter_id)
embedding_suffix = adapter_id.split("|")[0]
- # TODO: Remove these fields related to assertion
- output[JsonSchemaKey.ASSERTION_FAILURE_PROMPT] = (
- prompt.assertion_failure_prompt
- )
- output[JsonSchemaKey.ASSERT_PROMPT] = prompt.assert_prompt
- output[JsonSchemaKey.IS_ASSERT] = prompt.is_assert
output[JsonSchemaKey.PROMPT] = prompt.prompt
output[JsonSchemaKey.ACTIVE] = prompt.active
output[JsonSchemaKey.CHUNK_SIZE] = prompt.profile_manager.chunk_size
@@ -279,7 +349,7 @@ class PromptStudioRegistryHelper:
f"Cannot export tool. Prompt(s): {', '.join(invalidated_outputs)} "
"were not run. Please run them before exporting."
)
-
+ export_metadata[JsonSchemaKey.TOOL_SETTINGS] = tool_settings
export_metadata[JsonSchemaKey.OUTPUTS] = outputs
return export_metadata
diff --git a/prompt-service/src/unstract/prompt_service/main.py b/prompt-service/src/unstract/prompt_service/main.py
index c960e079c..bf48d8b72 100644
--- a/prompt-service/src/unstract/prompt_service/main.py
+++ b/prompt-service/src/unstract/prompt_service/main.py
@@ -167,6 +167,7 @@ def prompt_processor() -> Any:
payload: dict[Any, Any] = request.json
if not payload:
raise NoPayloadError
+ tool_settings = payload.get(PSKeys.TOOL_SETTINGS, {})
outputs = payload.get(PSKeys.OUTPUTS)
tool_id: str = payload.get(PSKeys.TOOL_ID, "")
run_id: str = payload.get(PSKeys.RUN_ID, "")
@@ -357,10 +358,11 @@ def prompt_processor() -> Any:
"Retrieving answer from LLM",
)
answer = construct_and_run_prompt(
- output,
- llm,
- context,
- "promptx",
+ tool_settings=tool_settings,
+ output=output,
+ llm=llm,
+ context=context,
+ prompt="promptx",
)
else:
answer = "NA"
@@ -376,19 +378,19 @@ def prompt_processor() -> Any:
"Retrieving context from adapter",
)
- if output[PSKeys.RETRIEVAL_STRATEGY] == PSKeys.SIMPLE:
- answer, context = run_retrieval(
- output, doc_id, llm, vector_index, PSKeys.SIMPLE
- )
- elif output[PSKeys.RETRIEVAL_STRATEGY] == PSKeys.SUBQUESTION:
- answer, context = run_retrieval(
- output, doc_id, llm, vector_index, PSKeys.SUBQUESTION
- )
- else:
- app.logger.info(
- "Invalid retrieval strategy "
- f"passed {output[PSKeys.RETRIEVAL_STRATEGY]}"
- )
+ retrieval_strategy = output.get(PSKeys.RETRIEVAL_STRATEGY)
+
+ if retrieval_strategy in {PSKeys.SIMPLE, PSKeys.SUBQUESTION}:
+ answer, context = run_retrieval(
+ tool_settings=tool_settings,
+ output=output,
+ doc_id=doc_id,
+ llm=llm,
+ vector_index=vector_index,
+ retrieval_type=retrieval_strategy,
+ )
+ else:
+ app.logger.info("Invalid retrieval strategy passed: %s", retrieval_strategy)
_publish_log(
log_events_id,
@@ -514,7 +516,7 @@ def prompt_processor() -> Any:
].rstrip("\n")
# Challenge condition
- if "enable_challenge" in output and output["enable_challenge"]:
+ if tool_settings.get("enable_challenge"):
challenge_plugin: dict[str, Any] = plugins.get("challenge", {})
try:
if challenge_plugin:
@@ -529,16 +531,9 @@ def prompt_processor() -> Any:
RunLevel.CHALLENGE,
"Challenging response",
)
- tool_settings: dict[str, Any] = {
- PSKeys.PREAMBLE: output[PSKeys.PREAMBLE],
- PSKeys.POSTAMBLE: output[PSKeys.POSTAMBLE],
- PSKeys.GRAMMAR: output[PSKeys.GRAMMAR],
- PSKeys.LLM: adapter_instance_id,
- PSKeys.CHALLENGE_LLM: output[PSKeys.CHALLENGE_LLM],
- }
challenge_llm = LLM(
tool=util,
- adapter_instance_id=output[PSKeys.CHALLENGE_LLM],
+ adapter_instance_id=tool_settings[PSKeys.CHALLENGE_LLM],
usage_kwargs=usage_kwargs,
)
challenge = challenge_plugin["entrypoint_cls"](
@@ -674,6 +669,7 @@ def prompt_processor() -> Any:
def run_retrieval( # type:ignore
+ tool_settings: dict[str, Any],
output: dict[str, Any],
doc_id: str,
llm: LLM,
@@ -681,10 +677,10 @@ def run_retrieval( # type:ignore
retrieval_type: str,
) -> tuple[str, str]:
prompt = construct_prompt_for_engine(
- preamble=output["preamble"],
- prompt=output["promptx"],
- postamble=output["postamble"],
- grammar_list=output["grammar"],
+ preamble=tool_settings.get(PSKeys.PREAMBLE, ""),
+ prompt=output[PSKeys.PROMPTX],
+ postamble=tool_settings.get(PSKeys.POSTAMBLE, ""),
+ grammar_list=tool_settings.get(PSKeys.GRAMMAR, []),
)
if retrieval_type is PSKeys.SUBQUESTION:
subq_prompt = (
@@ -709,10 +705,11 @@ def run_retrieval( # type:ignore
context = _retrieve_context(output, doc_id, vector_index, prompt)
answer = construct_and_run_prompt( # type:ignore
- output,
- llm,
- context,
- "promptx",
+ tool_settings=tool_settings,
+ output=output,
+ llm=llm,
+ context=context,
+ prompt="promptx",
)
return (answer, context)
@@ -741,16 +738,17 @@ def _retrieve_context(output, doc_id, vector_index, answer) -> str:
def construct_and_run_prompt(
+ tool_settings: dict[str, Any],
output: dict[str, Any],
llm: LLM,
context: str,
prompt: str,
) -> tuple[str, dict[str, Any]]:
prompt = construct_prompt(
- preamble=output[PSKeys.PREAMBLE],
+ preamble=tool_settings.get(PSKeys.PREAMBLE, ""),
prompt=output[prompt],
- postamble=output[PSKeys.POSTAMBLE],
- grammar_list=output[PSKeys.GRAMMAR],
+ postamble=tool_settings.get(PSKeys.POSTAMBLE, ""),
+ grammar_list=tool_settings.get(PSKeys.GRAMMAR, []),
context=context,
)
return run_completion(
@@ -800,18 +798,23 @@ def extract_variable(
return promptx
-def enable_single_pass_extraction() -> None:
- """Enables single-pass-extraction plugin if available."""
+def enable_plugins() -> None:
+ """Enables plugins if available."""
single_pass_extration_plugin: dict[str, Any] = plugins.get(
"single-pass-extraction", {}
)
+ summarize_plugin: dict[str, Any] = plugins.get("summarize", {})
if single_pass_extration_plugin:
single_pass_extration_plugin["entrypoint_cls"](
app=app, challenge_plugin=plugins.get("challenge", {})
)
+ if summarize_plugin:
+ summarize_plugin["entrypoint_cls"](
+ app=app,
+ )
-enable_single_pass_extraction()
+enable_plugins()
def log_exceptions(e: HTTPException):
diff --git a/tools/structure/requirements.txt b/tools/structure/requirements.txt
index fa65c7aa3..1cf39ef9d 100644
--- a/tools/structure/requirements.txt
+++ b/tools/structure/requirements.txt
@@ -1,4 +1,4 @@
# Add your dependencies here
# Required for all unstract tools
-unstract-sdk~=0.26.0
+unstract-sdk~=0.29.0
diff --git a/tools/structure/src/constants.py b/tools/structure/src/constants.py
index 21d2af4ba..e00de3dc8 100644
--- a/tools/structure/src/constants.py
+++ b/tools/structure/src/constants.py
@@ -17,8 +17,6 @@ class SettingsKeys:
X2TEXT_ADAPTER = "x2text_adapter"
CHUNK_OVERLAP = "chunk-overlap"
LLM = "llm"
- IS_ASSERT = "is_assert"
- ASSERTION_FAILURE_PROMPT = "assertion_failure_prompt"
RETRIEVAL_STRATEGY = "retrieval-strategy"
SIMPLE = "simple"
TYPE = "type"
@@ -38,7 +36,6 @@ class SettingsKeys:
WORD = "word"
SYNONYMS = "synonyms"
OUTPUTS = "outputs"
- ASSERT_PROMPT = "assert_prompt"
SECTION = "section"
DEFAULT = "default"
AUTHOR = "author"
@@ -47,3 +44,21 @@ class SettingsKeys:
# PDF_TO_TEXT_CONVERTER = "pdf-to-text-converters"
REINDEX = "reindex"
STRUCTURE_OUTPUT = "structure_output"
+ TOOL_SETTINGS = "tool_settings"
+ ENABLE_SINGLE_PASS_EXTRACTION = "enable_single_pass_extraction"
+ CHALLENGE_LLM = "challenge_llm"
+ ENABLE_CHALLENGE = "enable_challenge"
+ SINGLE_PASS_EXTRACTION_MODE = "single_pass_extraction_mode"
+ CHALLENGE_LLM_ADAPTER_ID = "challenge_llm_adapter_id"
+ SUMMARIZE_AS_SOURCE = "summarize_as_source"
+ TOOL_DATA_DIR = "TOOL_DATA_DIR"
+ SUMMARIZE_PROMPT = "summarize_prompt"
+ CONTEXT = "context"
+ ERROR = "error"
+ LLM_ADAPTER_INSTANCE_ID = "llm_adapter_instance_id"
+ RUN_ID = "run_id"
+ PROMPT_KEYS = "prompt_keys"
+ DATA = "data"
+ EXTRACT = "EXTRACT"
+ STATUS = "status"
+ OK = "OK"
diff --git a/tools/structure/src/main.py b/tools/structure/src/main.py
index bc00f3d50..020d548b2 100644
--- a/tools/structure/src/main.py
+++ b/tools/structure/src/main.py
@@ -6,7 +6,7 @@ from typing import Any
from constants import SettingsKeys # type: ignore [attr-defined]
from unstract.sdk.constants import LogState, MetadataKey
-from unstract.sdk.index import ToolIndex
+from unstract.sdk.index import Index
from unstract.sdk.prompt import PromptTool
from unstract.sdk.tool.base import BaseTool
from unstract.sdk.tool.entrypoint import ToolEntrypoint
@@ -23,12 +23,17 @@ class StructureTool(BaseTool):
output_dir: str,
) -> None:
prompt_registry_id: str = settings[SettingsKeys.PROMPT_REGISTRY_ID]
- responder = PromptTool(
+ challenge_llm: str = settings[SettingsKeys.CHALLENGE_LLM_ADAPTER_ID]
+ enable_challenge: bool = settings[SettingsKeys.ENABLE_CHALLENGE]
+ summarize_as_source: bool = settings[SettingsKeys.SUMMARIZE_AS_SOURCE]
+ single_pass_extraction_mode: bool = settings[
+ SettingsKeys.SINGLE_PASS_EXTRACTION_MODE
+ ]
+ responder: PromptTool = PromptTool(
tool=self,
prompt_port=self.get_env_or_die(SettingsKeys.PROMPT_PORT),
prompt_host=self.get_env_or_die(SettingsKeys.PROMPT_HOST),
)
-
self.stream_log(f"Fetching metadata for tool {prompt_registry_id}")
try:
exported_tool = responder.get_exported_tool(
@@ -45,43 +50,97 @@ class StructureTool(BaseTool):
self.stream_update(input_log, state=LogState.INPUT_UPDATE)
self.stream_update(output_log, state=LogState.OUTPUT_UPDATE)
- self.stream_log("Indexing document...")
file_hash = self.get_exec_metadata.get(MetadataKey.SOURCE_HASH)
- tool_index = ToolIndex(tool=self)
+ index = Index(tool=self)
tool_id = tool_metadata[SettingsKeys.TOOL_ID]
+ tool_settings = tool_metadata[SettingsKeys.TOOL_SETTINGS]
outputs = tool_metadata[SettingsKeys.OUTPUTS]
- try:
- for output in outputs:
- tool_index.index_file(
- tool_id=tool_metadata[SettingsKeys.TOOL_ID],
- embedding_type=output[SettingsKeys.EMBEDDING],
- vector_db=output[SettingsKeys.VECTOR_DB],
- x2text_adapter=output[SettingsKeys.X2TEXT_ADAPTER],
- file_path=input_file,
- file_hash=file_hash,
- chunk_size=output[SettingsKeys.CHUNK_SIZE],
- chunk_overlap=output[SettingsKeys.CHUNK_OVERLAP],
- reindex=output[SettingsKeys.REINDEX],
- )
- except Exception as e:
- self.stream_error_and_exit(f"Error fetching data and indexing: {e}")
+ tool_settings[SettingsKeys.CHALLENGE_LLM] = challenge_llm
+ tool_settings[SettingsKeys.ENABLE_CHALLENGE] = enable_challenge
+ tool_settings[SettingsKeys.ENABLE_SINGLE_PASS_EXTRACTION] = (
+ single_pass_extraction_mode
+ )
+ prompt_service_resp = None
_, file_name = os.path.split(input_file)
+ tool_data_dir = Path(self.get_env_or_die(SettingsKeys.TOOL_DATA_DIR))
# TODO : Resolve and pass log events ID
payload = {
+ "tool_settings": tool_settings,
"outputs": outputs,
"tool_id": tool_id,
"file_hash": file_hash,
"file_name": file_name,
}
- self.stream_log("Fetching responses for prompts...")
- prompt_service_resp = responder.answer_prompt(payload=payload)
+
+ # TODO: Need to split extraction and indexing
+ # to avoid unwanted indexing
+ self.stream_log("Indexing document")
+ if tool_settings[SettingsKeys.ENABLE_SINGLE_PASS_EXTRACTION]:
+ index.index_file(
+ tool_id=tool_metadata[SettingsKeys.TOOL_ID],
+ embedding_instance_id=tool_settings[SettingsKeys.EMBEDDING],
+ vector_db_instance_id=tool_settings[SettingsKeys.VECTOR_DB],
+ x2text_instance_id=tool_settings[SettingsKeys.X2TEXT_ADAPTER],
+ file_path=input_file,
+ file_hash=file_hash,
+ chunk_size=tool_settings[SettingsKeys.CHUNK_SIZE],
+ chunk_overlap=tool_settings[SettingsKeys.CHUNK_OVERLAP],
+ output_file_path=tool_data_dir / SettingsKeys.EXTRACT,
+ reindex=True,
+ )
+ if summarize_as_source:
+ self._summarize_and_index(
+ tool_id=tool_id,
+ tool_settings=tool_settings,
+ tool_data_dir=tool_data_dir,
+ responder=responder,
+ outputs=outputs,
+ index=index,
+ )
+ self.stream_log("Fetching response for single pass extraction")
+ prompt_service_resp = responder.single_pass_extraction(payload=payload)
+ else:
+ try:
+ # To reindex even if file is already
+ # indexed to get the output in required path
+ reindex = True
+ for output in outputs:
+ index.index_file(
+ tool_id=tool_metadata[SettingsKeys.TOOL_ID],
+ embedding_instance_id=output[SettingsKeys.EMBEDDING],
+ vector_db_instance_id=output[SettingsKeys.VECTOR_DB],
+ x2text_instance_id=output[SettingsKeys.X2TEXT_ADAPTER],
+ file_path=input_file,
+ file_hash=file_hash,
+ chunk_size=output[SettingsKeys.CHUNK_SIZE],
+ chunk_overlap=output[SettingsKeys.CHUNK_OVERLAP],
+ output_file_path=tool_data_dir / SettingsKeys.EXTRACT,
+ reindex=reindex,
+ )
+ if summarize_as_source:
+ self._summarize_and_index(
+ tool_id=tool_id,
+ tool_settings=tool_settings,
+ tool_data_dir=tool_data_dir,
+ responder=responder,
+ outputs=output,
+ index=index,
+ )
+ # For summary indexing should be done
+ # only once. So breaking the loop
+ break
+ reindex = False
+ except Exception as e:
+ self.stream_error_and_exit(f"Error fetching data and indexing: {e}")
+ self.stream_log("Fetching responses for prompts...")
+ prompt_service_resp = responder.answer_prompt(payload=payload)
# TODO: Make use of dataclasses
- if prompt_service_resp["status"] == "ERROR":
+ if prompt_service_resp[SettingsKeys.STATUS] != SettingsKeys.OK:
self.stream_error_and_exit(
f"Failed to fetch responses for "
- f"prompts: {prompt_service_resp['error']}"
+ f"prompts: {prompt_service_resp[SettingsKeys.ERROR]}"
)
structured_output = prompt_service_resp[SettingsKeys.STRUCTURE_OUTPUT]
@@ -108,6 +167,53 @@ class StructureTool(BaseTool):
self.stream_error_and_exit(f"Error encoding JSON: {e}")
self.write_tool_result(data=json.loads(structured_output))
+ def _summarize_and_index(
+ self,
+ tool_id: str,
+ tool_settings: str,
+ tool_data_dir: Path,
+ responder: PromptTool,
+ outputs: dict[str, Any],
+ index: Index,
+ ) -> str:
+ llm_adapter_instance_id: str = tool_settings[SettingsKeys.LLM]
+ summarize_prompt: str = tool_settings[SettingsKeys.SUMMARIZE_PROMPT]
+ context = ""
+ extract_file_path = tool_data_dir / SettingsKeys.EXTRACT
+ with open(extract_file_path, encoding="utf-8") as file:
+ context = file.read()
+ prompt_keys = [output["name"] for output in outputs]
+ self.stream_log("Summarizing context")
+ # Handle run_id along with prompt run
+ payload = {
+ SettingsKeys.LLM_ADAPTER_INSTANCE_ID: llm_adapter_instance_id,
+ SettingsKeys.SUMMARIZE_PROMPT: summarize_prompt,
+ SettingsKeys.CONTEXT: context,
+ SettingsKeys.PROMPT_KEYS: prompt_keys,
+ }
+ response = responder.summarize(payload=payload)
+ if response[SettingsKeys.STATUS] != SettingsKeys.OK:
+ self.stream_error_and_exit(
+ f"Error summarizing response: {response[SettingsKeys.ERROR]}"
+ )
+ structure_output = json.loads(response["structure_output"])
+ summarized_context = structure_output.get(SettingsKeys.DATA, "")
+ self.stream_log("Writing summarized context to a file")
+ summarize_file_path = tool_data_dir / "SUMMARIZE"
+ with open(summarize_file_path, "w", encoding="utf-8") as f:
+ f.write(summarized_context)
+ self.stream_log("Indexing summarized context")
+ file_hash: str = index.index_file(
+ tool_id=tool_id,
+ embedding_instance_id=tool_settings[SettingsKeys.EMBEDDING],
+ vector_db_instance_id=tool_settings[SettingsKeys.VECTOR_DB],
+ x2text_instance_id=tool_settings[SettingsKeys.X2TEXT_ADAPTER],
+ file_path=summarize_file_path,
+ chunk_size=0,
+ chunk_overlap=0,
+ )
+ return file_hash
+
if __name__ == "__main__":
args = sys.argv[1:]