Skip to content

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

Challenge configuration (#166)

Deepak Kc52e6d13bb62
diff --git a/backend/prompt_studio/prompt_studio_core/constants.py b/backend/prompt_studio/prompt_studio_core/constants.py
index 52173f93a..81eb38256 100644
--- a/backend/prompt_studio/prompt_studio_core/constants.py
+++ b/backend/prompt_studio/prompt_studio_core/constants.py
@@ -77,8 +77,11 @@ class ToolStudioPromptKeys:
SUMMARIZED_RESULT = "summarized_result"
DOCUMENT_ID = "document_id"
EXTRACT = "extract"
- LLM_PROFILE_MANAGER = "llm_profile_manager"
+ TOOL_SETTINGS = "tool_settings"
+ ENABLE_CHALLENGE = "enable_challenge"
+ CHALLENGE_LLM = "challenge_llm"
SINGLE_PASS_EXTRACTION_MODE = "single_pass_extraction_mode"
+ SINGLE_PASS_EXTRACTION = "single_pass_extraction"
class LogLevels:
diff --git a/backend/prompt_studio/prompt_studio_core/migrations/0010_customtool_challenge_llm_customtool_enable_challenge_and_more.py b/backend/prompt_studio/prompt_studio_core/migrations/0010_customtool_challenge_llm_customtool_enable_challenge_and_more.py
new file mode 100644
index 000000000..ae838aefd
--- /dev/null
+++ b/backend/prompt_studio/prompt_studio_core/migrations/0010_customtool_challenge_llm_customtool_enable_challenge_and_more.py
@@ -0,0 +1,59 @@
+# Generated by Django 4.2.1 on 2024-03-24 00:31
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ (
+ "adapter_processor",
+ "0007_remove_adapterinstance_is_default_userdefaultadapter",
+ ),
+ (
+ "prompt_studio_core",
+ "0009_customtool_single_pass_extraction_mode_and_more",
+ ),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="customtool",
+ name="challenge_llm",
+ field=models.ForeignKey(
+ blank=True,
+ db_comment="Field to store challenge llm",
+ null=True,
+ on_delete=django.db.models.deletion.PROTECT,
+ related_name="challenge_customtools",
+ to="adapter_processor.adapterinstance",
+ ),
+ ),
+ migrations.AddField(
+ model_name="customtool",
+ name="enable_challenge",
+ field=models.BooleanField(
+ db_comment="Flag to enable or disable challenge", default=False
+ ),
+ ),
+ migrations.AlterField(
+ model_name="customtool",
+ name="monitor_llm",
+ field=models.ForeignKey(
+ blank=True,
+ db_comment="Field to store monitor llm",
+ null=True,
+ on_delete=django.db.models.deletion.PROTECT,
+ related_name="monitor_customtoos",
+ to="adapter_processor.adapterinstance",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="customtool",
+ name="single_pass_extraction_mode",
+ field=models.BooleanField(
+ db_comment="Flag to enable or disable single pass extraction mode",
+ default=False,
+ ),
+ ),
+ ]
diff --git a/backend/prompt_studio/prompt_studio_core/models.py b/backend/prompt_studio/prompt_studio_core/models.py
index bed468549..1ecda5ebd 100644
--- a/backend/prompt_studio/prompt_studio_core/models.py
+++ b/backend/prompt_studio/prompt_studio_core/models.py
@@ -59,6 +59,7 @@ class CustomTool(BaseModel):
db_comment="Field to store monitor llm",
null=True,
blank=True,
+ related_name="monitor_customtools",
)
created_by = models.ForeignKey(
User,
@@ -84,3 +85,14 @@ class CustomTool(BaseModel):
db_comment="Flag to enable or disable single pass extraction mode",
default=False,
)
+ challenge_llm = models.ForeignKey(
+ AdapterInstance,
+ on_delete=models.PROTECT,
+ db_comment="Field to store challenge llm",
+ null=True,
+ blank=True,
+ related_name="challenge_customtools",
+ )
+ enable_challenge = models.BooleanField(
+ db_comment="Flag to enable or disable challenge", default=False
+ )
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 1df3f6dc6..16a930d41 100644
--- a/backend/prompt_studio/prompt_studio_core/prompt_studio_helper.py
+++ b/backend/prompt_studio/prompt_studio_core/prompt_studio_helper.py
@@ -397,7 +397,7 @@ class PromptStudioHelper:
OutputManagerHelper.handle_prompt_output_update(
prompts=prompts,
- outputs=response["single_pass_extraction"],
+ outputs=response[TSPKeys.SINGLE_PASS_EXTRACTION],
document_id=document_id,
is_single_pass_extract=True,
)
@@ -447,6 +447,8 @@ class PromptStudioHelper:
"""
monitor_llm_instance: Optional[AdapterInstance] = tool.monitor_llm
monitor_llm: Optional[str] = None
+ challenge_llm_instance: Optional[AdapterInstance] = tool.challenge_llm
+ challenge_llm: Optional[str] = None
prompt_grammer = tool.prompt_grammer
outputs: list[dict[str, Any]] = []
grammer_dict = {}
@@ -459,6 +461,13 @@ class PromptStudioHelper:
default_profile = ProfileManager.get_default_llm_profile(tool)
monitor_llm = str(default_profile.llm.id)
+ # Using default profile manager llm if challenge_llm is None
+ if challenge_llm_instance:
+ challenge_llm = str(challenge_llm_instance.id)
+ else:
+ default_profile = ProfileManager.get_default_llm_profile(tool)
+ challenge_llm = str(default_profile.llm.id)
+
# Adding validations
if prompt_grammer:
for word, synonyms in prompt_grammer.items():
@@ -528,6 +537,8 @@ 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
@@ -646,6 +657,13 @@ class PromptStudioHelper:
grammar: list[dict[str, Any]] = []
prompt_grammar = tool.prompt_grammer
default_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_profile.llm.id)
# Need to check the user who created profile manager
# has access to adapters configured in profile manager
PromptStudioHelper.validate_profile_manager_owner_access(
@@ -673,18 +691,18 @@ class PromptStudioHelper:
embedding_model = str(default_profile.embedding_model.id)
llm = str(default_profile.llm.id)
x2text = str(default_profile.x2text.id)
- llm_profile_manager = {}
- llm_profile_manager[TSPKeys.PREAMBLE] = tool.preamble
- llm_profile_manager[TSPKeys.POSTAMBLE] = tool.postamble
- llm_profile_manager[TSPKeys.GRAMMAR] = grammar
- llm_profile_manager[TSPKeys.LLM] = llm
- llm_profile_manager[TSPKeys.X2TEXT_ADAPTER] = x2text
- llm_profile_manager[TSPKeys.VECTOR_DB] = vector_db
- llm_profile_manager[TSPKeys.EMBEDDING] = embedding_model
- llm_profile_manager[TSPKeys.CHUNK_SIZE] = default_profile.chunk_size
- llm_profile_manager[
- TSPKeys.CHUNK_OVERLAP
- ] = default_profile.chunk_overlap
+ tool_settings = {}
+ tool_settings[TSPKeys.PREAMBLE] = tool.preamble
+ tool_settings[TSPKeys.POSTAMBLE] = tool.postamble
+ tool_settings[TSPKeys.GRAMMAR] = grammar
+ tool_settings[TSPKeys.LLM] = llm
+ tool_settings[TSPKeys.X2TEXT_ADAPTER] = x2text
+ tool_settings[TSPKeys.VECTOR_DB] = vector_db
+ tool_settings[TSPKeys.EMBEDDING] = embedding_model
+ tool_settings[TSPKeys.CHUNK_SIZE] = default_profile.chunk_size
+ tool_settings[TSPKeys.CHUNK_OVERLAP] = default_profile.chunk_overlap
+ tool_settings[TSPKeys.ENABLE_CHALLENGE] = tool.enable_challenge
+ tool_settings[TSPKeys.CHALLENGE_LLM] = challenge_llm
for prompt in prompts:
output: dict[str, Any] = {}
@@ -702,7 +720,7 @@ class PromptStudioHelper:
file_hash = ToolUtils.get_hash_from_file(file_path=file_path)
payload = {
- TSPKeys.LLM_PROFILE_MANAGER: llm_profile_manager,
+ TSPKeys.TOOL_SETTINGS: tool_settings,
TSPKeys.OUTPUTS: outputs,
TSPKeys.TOOL_ID: tool_id,
TSPKeys.FILE_HASH: file_hash,
diff --git a/backend/tenant_account/serializer.py b/backend/tenant_account/serializer.py
index 7983ea5f1..305efa749 100644
--- a/backend/tenant_account/serializer.py
+++ b/backend/tenant_account/serializer.py
@@ -91,7 +91,7 @@ class InviteUserSerializer(serializers.Serializer):
def get_users(
self, validated_data: dict[str, Any]
) -> list[dict[str, Union[str, None]]]:
- return validated_data.get("users", []) # type: ignore
+ return validated_data.get("users", [])
class RemoveUserFromOrganizationSerializer(serializers.Serializer):
diff --git a/backend/utils/filtering.py b/backend/utils/filtering.py
index 99e6b7df0..44be4254a 100644
--- a/backend/utils/filtering.py
+++ b/backend/utils/filtering.py
@@ -1,9 +1,11 @@
+from typing import Any
+
from rest_framework.request import Request
class FilterHelper:
@staticmethod
- def build_filter_args(request: Request, *params: str) -> dict[str, str]:
+ def build_filter_args(request: Request, *params: str) -> dict[str, Any]:
"""Builds a dict of filter to pass to the QueryManager from the
request.
@@ -11,9 +13,9 @@ class FilterHelper:
request (Request): Request to obtain query from
Returns:
- dict[str, str]: Filter dict to pass to request
+ dict[str, Any]: Filter dict to pass to request
"""
- filter_args: dict[str, str] = {}
+ filter_args: dict[str, Any] = {}
for queryParam in params:
paramValue = request.query_params.get(queryParam)
if paramValue is not None:
diff --git a/frontend/src/components/custom-tools/settings-modal/SettingsModal.jsx b/frontend/src/components/custom-tools/settings-modal/SettingsModal.jsx
index 46c26d05e..d6e6411b1 100644
--- a/frontend/src/components/custom-tools/settings-modal/SettingsModal.jsx
+++ b/frontend/src/components/custom-tools/settings-modal/SettingsModal.jsx
@@ -19,11 +19,14 @@ import "./SettingsModal.css";
let SummarizeManager = null;
let EvaluationManager = null;
+let ChallengeManager = null;
try {
SummarizeManager =
require("../../../plugins/summarize-manager/SummarizeManager").SummarizeManager;
EvaluationManager =
require("../../../plugins/evaluation-manager/EvaluationManager").EvaluationManager;
+ ChallengeManager =
+ require("../../../plugins/challenge-manager/ChallengeManager").ChallengeManager;
} catch {
// Component will remain null if it is not present.
}
@@ -37,21 +40,21 @@ function SettingsModal({ open, setOpen, handleUpdateTool }) {
useEffect(() => {
const items = [
getMenuItem("Manage LLM Profiles", 1, <CodeOutlined />),
- getMenuItem("Manage Grammar", 4, <MessageOutlined />),
- getMenuItem("Preamble", 5, <DiffOutlined />),
- getMenuItem("Postamble", 6, <DiffOutlined />),
+ getMenuItem("Manage Grammar", 5, <MessageOutlined />),
+ getMenuItem("Preamble", 6, <DiffOutlined />),
+ getMenuItem("Postamble", 7, <DiffOutlined />),
];
const listOfComponents = {
1: <ManageLlmProfiles />,
- 4: <CustomSynonyms />,
- 5: (
+ 5: <CustomSynonyms />,
+ 6: (
<PreAndPostAmbleModal
type="PREAMBLE"
handleUpdateTool={handleUpdateTool}
/>
),
- 6: (
+ 7: (
<PreAndPostAmbleModal
type="POSTAMBLE"
handleUpdateTool={handleUpdateTool}
@@ -59,7 +62,7 @@ function SettingsModal({ open, setOpen, handleUpdateTool }) {
),
};
- if (SummarizeManager && EvaluationManager) {
+ if (SummarizeManager && EvaluationManager && ChallengeManager) {
// Add Summary Manager menu item to the existing list
items.splice(
1,
@@ -67,6 +70,7 @@ function SettingsModal({ open, setOpen, handleUpdateTool }) {
...[
getMenuItem("Summary Manager", 2, <FileTextOutlined />),
getMenuItem("Evaluation Manager", 3, <FileTextOutlined />),
+ getMenuItem("Challenge Manager", 4, <FileTextOutlined />),
]
);
listOfComponents[2] = (
@@ -78,6 +82,9 @@ function SettingsModal({ open, setOpen, handleUpdateTool }) {
listOfComponents[3] = (
<EvaluationManager handleUpdateTool={handleUpdateTool} />
);
+ listOfComponents[4] = (
+ <ChallengeManager handleUpdateTool={handleUpdateTool} />
+ );
}
setMenuItems(items);
diff --git a/prompt-service/src/unstract/prompt_service/constants.py b/prompt-service/src/unstract/prompt_service/constants.py
index 5afe5a9bc..205667f9a 100644
--- a/prompt-service/src/unstract/prompt_service/constants.py
+++ b/prompt-service/src/unstract/prompt_service/constants.py
@@ -42,8 +42,10 @@ class PromptServiceContants:
EVAL_SETTINGS_EVALUATE = "evaluate"
EVAL_SETTINGS_MONITOR_LLM = "monitor_llm"
EVAL_SETTINGS_EXCLUDE_FAILED = "exclude_failed"
- LLM_PROFILE_MANAGER = "llm_profile_manager"
+ TOOL_SETTINGS = "tool_settings"
LOG_EVENTS_ID = "log_events_id"
+ CHALLENGE_LLM = "challenge_llm"
+ USAGE = "usage"
class LogLevel(Enum):
diff --git a/prompt-service/src/unstract/prompt_service/main.py b/prompt-service/src/unstract/prompt_service/main.py
index 72c40057b..df89e18cc 100644
--- a/prompt-service/src/unstract/prompt_service/main.py
+++ b/prompt-service/src/unstract/prompt_service/main.py
@@ -55,7 +55,7 @@ AuthenticationMiddleware.be_db = be_db
app = Flask("prompt-service")
-plugins = plugin_loader(app)
+plugins: dict[str, dict[str, Any]] = plugin_loader(app)
def _publish_log(
@@ -325,7 +325,7 @@ def prompt_processor() -> Any:
is_assert = output[PSKeys.IS_ASSERT]
if is_assert:
app.logger.debug(f'Asserting prompt: {output["assert_prompt"]}')
- answer = construct_and_run_prompt(
+ answer, usage = construct_and_run_prompt(
output,
llm_helper,
llm_li,
@@ -359,7 +359,7 @@ def prompt_processor() -> Any:
]
app.logger.info(f"[Assigning] {answer} to the output")
else:
- answer = construct_and_run_prompt(
+ answer, usage = construct_and_run_prompt(
output,
llm_helper,
llm_li,
@@ -368,7 +368,7 @@ def prompt_processor() -> Any:
)
else:
if chunk_size == 0:
- answer = construct_and_run_prompt(
+ answer, usage = construct_and_run_prompt(
output,
llm_helper,
llm_li,
@@ -377,6 +377,7 @@ def prompt_processor() -> Any:
)
else:
answer = "NA"
+ usage = {}
_publish_log(
log_events_id,
{"tool_id": tool_id, "prompt_key": name},
@@ -386,7 +387,7 @@ def prompt_processor() -> Any:
)
if output[PSKeys.RETRIEVAL_STRATEGY] == PSKeys.SIMPLE:
- answer, context = simple_retriver(
+ answer, context, usage = simple_retriver(
output,
doc_id,
llm_helper,
@@ -430,7 +431,7 @@ def prompt_processor() -> Any:
percentages or other grouping \
characters. No explanation is required.\
If you cannot extract the number, output 0."
- answer = run_completion(
+ answer, usage = run_completion(
llm_helper,
llm_li,
prompt,
@@ -450,7 +451,7 @@ def prompt_processor() -> Any:
prompt = f'Extract the email from the following text:\n{answer}\n\nOutput just the email. \
The email should be directly assignable to a string variable. \
No explanation is required. If you cannot extract the email, output "NA".' # noqa
- answer = run_completion(
+ answer, usage = run_completion(
llm_helper,
llm_li,
prompt,
@@ -464,7 +465,7 @@ def prompt_processor() -> Any:
The date should be in ISO date time format. No explanation is required. \
The date should be directly assignable to a date variable. \
If you cannot convert the string into a date, output "NA".' # noqa
- answer = run_completion(
+ answer, usage = run_completion(
llm_helper,
llm_li,
prompt,
@@ -513,6 +514,39 @@ def prompt_processor() -> Any:
output[PSKeys.NAME]
].rstrip("\n")
+ # Challenge condition
+ if "enable_challenge" in output and output["enable_challenge"]:
+ challenge_plugin: dict[str, Any] = plugins.get("challenge", {})
+ try:
+ if challenge_plugin:
+ tool_settings: dict[str, Any] = {
+ PSKeys.PREAMBLE: output[PSKeys.PREAMBLE],
+ PSKeys.POSTAMBLE: output[PSKeys.POSTAMBLE],
+ PSKeys.GRAMMAR: output[PSKeys.GRAMMAR],
+ PSKeys.LLM: output[PSKeys.LLM],
+ PSKeys.CHALLENGE_LLM: output[PSKeys.CHALLENGE_LLM],
+ }
+ challenge = challenge_plugin["entrypoint_cls"](
+ llm_helper=llm_helper,
+ context=context,
+ tool_settings=tool_settings,
+ output=output,
+ structured_output=structured_output,
+ logger=app.logger,
+ platform_key=platform_key,
+ )
+ # Will inline replace the structured output passed.
+ challenge.run()
+ else:
+ app.logger.info(
+ "No challenge plugin found to evaluate prompt: %s",
+ output["name"],
+ )
+ except challenge_plugin["exception_cls"] as e:
+ app.logger.error(
+ "Failed to challenge prompt %s: %s", output["name"], str(e)
+ )
+
#
# Evaluate the prompt.
#
@@ -596,6 +630,7 @@ def prompt_processor() -> Any:
RunLevel.RUN,
"Execution complete",
)
+ structured_output[f"{name}__usage"] = usage
return structured_output
@@ -616,7 +651,7 @@ def simple_retriver( # type:ignore
f"Generate a sub-question from the following verbose prompt that will"
f" help extract relevant documents from a vector store:\n\n{prompt}"
)
- answer: str = run_completion(
+ answer, usage = run_completion(
llm_helper,
llm_li,
subq_prompt,
@@ -643,14 +678,14 @@ def simple_retriver( # type:ignore
"Node score is less than 0.6. " f"Ignored: {node.score}"
)
- answer: str = construct_and_run_prompt( # type:ignore
+ answer, usage = construct_and_run_prompt( # type:ignore
output,
llm_helper,
llm_li,
text,
"promptx",
)
- return (answer, text)
+ return (answer, text, usage)
def construct_and_run_prompt(
@@ -659,7 +694,7 @@ def construct_and_run_prompt(
llm_li: Optional[LLM],
context: str,
prompt: str,
-) -> str:
+) -> tuple[str, dict[str, Any]]:
prompt = construct_prompt(
preamble=output[PSKeys.PREAMBLE],
prompt=output[prompt],
@@ -667,23 +702,18 @@ def construct_and_run_prompt(
grammar_list=output[PSKeys.GRAMMAR],
context=context,
)
- try:
- answer: str = run_completion(
- llm_helper,
- llm_li,
- prompt,
- )
- return answer
- except Exception as e:
- app.logger.info(f"Error completing prompt: {e}.")
- raise e
+ return run_completion(
+ llm_helper,
+ llm_li,
+ prompt,
+ )
def run_completion(
llm_helper: ToolLLM,
llm_li: Optional[LLM],
prompt: str,
-) -> str:
+) -> tuple[str, dict[str, Any]]:
try:
platform_api_key = llm_helper.tool.get_env_or_die(
PSKeys.PLATFORM_SERVICE_API_KEY
@@ -693,7 +723,10 @@ def run_completion(
)
answer: str = completion[PSKeys.RESPONSE].text
- return answer
+ usage = {}
+ if PSKeys.USAGE in completion:
+ usage = completion[PSKeys.USAGE]
+ return answer, usage
except Exception as e:
app.logger.info(f"Error completing prompt: {e}.")
raise e
@@ -729,7 +762,9 @@ def enable_single_pass_extraction() -> None:
"single-pass-extraction", {}
)
if single_pass_extration_plugin:
- single_pass_extration_plugin["entrypoint_cls"](app)
+ single_pass_extration_plugin["entrypoint_cls"](
+ app=app, challenge_plugin=plugins.get("challenge", {})
+ )
enable_single_pass_extraction()