Skip to content

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

feat: Removed assertion logic in prompt service and other fixes (#325)

Chandrasekharan M1454d90cb1ce
diff --git a/backend/prompt_studio/prompt_studio/exceptions.py b/backend/prompt_studio/prompt_studio/exceptions.py
index dd4140151..c78c3a740 100644
--- a/backend/prompt_studio/prompt_studio/exceptions.py
+++ b/backend/prompt_studio/prompt_studio/exceptions.py
@@ -14,9 +14,3 @@ class AnswerFetchError(APIException):
class ToolNotValid(APIException):
status_code = 400
default_detail = "Custom tool is not valid."
-
-
-class PromptNotValid(APIException):
- status_code = 400
- default_detail = "Input prompt instance is not valid.\
- Seems it is either empty or no prompt is mapped."
diff --git a/backend/prompt_studio/prompt_studio_core/exceptions.py b/backend/prompt_studio/prompt_studio_core/exceptions.py
index 8e03342b0..666d41241 100644
--- a/backend/prompt_studio/prompt_studio_core/exceptions.py
+++ b/backend/prompt_studio/prompt_studio_core/exceptions.py
@@ -12,12 +12,6 @@ class ToolNotValid(APIException):
default_detail = "Custom tool is not valid."
-class PromptNotValid(APIException):
- status_code = 400
- default_detail = "Input prompt instance is not valid.\
- Seems it is either empty or no prompt is mapped."
-
-
class IndexingAPIError(APIException):
status_code = 500
default_detail = "Error while indexing file"
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 7bca616e2..89f90f912 100644
--- a/backend/prompt_studio/prompt_studio_core/prompt_studio_helper.py
+++ b/backend/prompt_studio/prompt_studio_core/prompt_studio_helper.py
@@ -19,7 +19,6 @@ from prompt_studio.prompt_studio_core.exceptions import (
IndexingAPIError,
NoPromptsFound,
PermissionError,
- PromptNotValid,
ToolNotValid,
)
from prompt_studio.prompt_studio_core.models import CustomTool
@@ -310,7 +309,6 @@ class PromptStudioHelper:
id (Optional[str]): ID of the prompt
Raises:
- PromptNotValid: If a prompt could not be queried from the DB
AnswerFetchError: Error from prompt-service
Returns:
@@ -329,13 +327,10 @@ class PromptStudioHelper:
if id:
prompt_instance = PromptStudioHelper._fetch_prompt_from_id(id)
- if not prompt_instance:
- logger.error(f"[{tool_id or 'NA'}] Invalid prompt id: {id}")
- raise PromptNotValid()
-
+ prompt_name = prompt_instance.prompt_key
logger.info(f"[{tool_id}] Executing single prompt {id}")
PromptStudioHelper._publish_log(
- {"tool_id": tool_id, "prompt_id": id, "doc_name": doc_name},
+ {"tool_id": tool_id, "prompt_key": prompt_name, "doc_name": doc_name},
LogLevels.INFO,
LogLevels.RUN,
"Executing single prompt",
@@ -355,7 +350,7 @@ class PromptStudioHelper:
logger.info(f"[{tool.tool_id}] Invoking prompt service for prompt {id}")
PromptStudioHelper._publish_log(
- {"tool_id": tool_id, "prompt_id": id, "doc_name": doc_name},
+ {"tool_id": tool_id, "prompt_key": prompt_name, "doc_name": doc_name},
LogLevels.DEBUG,
LogLevels.RUN,
"Invoking prompt service",
@@ -382,7 +377,11 @@ class PromptStudioHelper:
f"[{tool.tool_id}] Error while fetching response for prompt {id}: {e}" # noqa: E501
)
PromptStudioHelper._publish_log(
- {"tool_id": tool_id, "prompt_id": id},
+ {
+ "tool_id": tool_id,
+ "prompt_key": prompt_name,
+ "doc_name": doc_name,
+ },
LogLevels.ERROR,
LogLevels.RUN,
f"Failed to fetch prompt response. {e}",
@@ -393,7 +392,7 @@ class PromptStudioHelper:
f"[{tool.tool_id}] Response fetched successfully for prompt {id}" # noqa: E501
)
PromptStudioHelper._publish_log(
- {"tool_id": tool_id, "prompt_id": id},
+ {"tool_id": tool_id, "prompt_key": prompt_name, "doc_name": doc_name},
LogLevels.INFO,
LogLevels.RUN,
"Single prompt execution completed",
@@ -539,6 +538,7 @@ class PromptStudioHelper:
)
output: dict[str, Any] = {}
+ # 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
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 4b8ecfc2e..921799198 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
@@ -270,12 +270,12 @@ class PromptStudioRegistryHelper:
if invalidated_prompts:
raise InValidCustomToolError(
- f"Cannot export tool. Prompt(s) : {invalidated_prompts} "
- "are not valid. Please enter a valid prompt."
+ f"Cannot export tool. Prompt(s): {', '.join(invalidated_prompts)} "
+ "are empty. Please enter a valid prompt."
)
if invalidated_outputs:
raise InValidCustomToolError(
- f"Cannot export tool. Prompt(s) : {invalidated_outputs} "
+ f"Cannot export tool. Prompt(s): {', '.join(invalidated_outputs)} "
"were not run. Please run them before exporting."
)
diff --git a/backend/tenant_account/migrations/0006_alter_organizationmember_is_login_onboarding_msg_and_more.py b/backend/tenant_account/migrations/0006_alter_organizationmember_is_login_onboarding_msg_and_more.py
new file mode 100644
index 000000000..e74e522c8
--- /dev/null
+++ b/backend/tenant_account/migrations/0006_alter_organizationmember_is_login_onboarding_msg_and_more.py
@@ -0,0 +1,29 @@
+# Generated by Django 4.2.1 on 2024-05-08 12:53
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("tenant_account", "0005_organizationmember_is_onboarding_msg_and_more"),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name="organizationmember",
+ name="is_login_onboarding_msg",
+ field=models.BooleanField(
+ db_comment="Flag to indicate whether the onboarding messages are shown",
+ default=True,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="organizationmember",
+ name="is_prompt_studio_onboarding_msg",
+ field=models.BooleanField(
+ db_comment="Flag to indicate whether the prompt studio messages are shown",
+ default=True,
+ ),
+ ),
+ ]
diff --git a/frontend/src/assets/index.js b/frontend/src/assets/index.js
index 20f763d3c..eb10ae3fc 100644
--- a/frontend/src/assets/index.js
+++ b/frontend/src/assets/index.js
@@ -15,7 +15,6 @@ import { ReactComponent as ListOfWfStepsPlaceholder } from "./list-of-wf-steps-p
import { ReactComponent as ListOfToolsPlaceholder } from "./list-of-tools-placeholder.svg";
import { ReactComponent as ApiDeployments } from "./api-deployments.svg";
import { ReactComponent as StepIcon } from "./steps.svg";
-import { ReactComponent as AssertionIcon } from "./assertion.svg";
import { ReactComponent as CombinedOutputIcon } from "./combined-output.svg";
import { ReactComponent as EmptyPlaceholder } from "./empty.svg";
import { ReactComponent as Desktop } from "./desktop.svg";
@@ -52,7 +51,6 @@ export {
ApiDeployments,
StepIcon,
EmptyPlaceholder,
- AssertionIcon,
CombinedOutputIcon,
Desktop,
ReachOut,
diff --git a/frontend/src/components/custom-tools/prompt-card/PromptCard.css b/frontend/src/components/custom-tools/prompt-card/PromptCard.css
index ce1257932..65509d557 100644
--- a/frontend/src/components/custom-tools/prompt-card/PromptCard.css
+++ b/frontend/src/components/custom-tools/prompt-card/PromptCard.css
@@ -91,37 +91,10 @@
margin-bottom: 2px;
}
-.assert-p-l-4 {
- padding-left: 4px;
-}
-
-.assert-p-r-4 {
- padding-right: 4px;
-}
-
-.assertion-comp {
- background-color: #eceff3;
- border-end-end-radius: 0px;
- border-end-start-radius: 0px;
-}
-
-.assertion-comp .ant-collapse-header {
- display: none !important;
- padding: 0 !important;
-}
-
-.assertion-comp .ant-collapse-content-box {
- padding: 0px !important;
-}
-
.prompt-card-action-button.ant-btn-text:disabled > .prompt-card-actions-head {
color: rgba(0, 0, 0, 0.25);
}
-.prompt-card-action-button.ant-btn-text:disabled > .assertion-icon > path {
- fill: rgba(0, 0, 0, 0.25);
-}
-
.tag-max-width {
max-width: 150px;
}
diff --git a/frontend/src/components/custom-tools/prompt-card/PromptCard.jsx b/frontend/src/components/custom-tools/prompt-card/PromptCard.jsx
index 07f372737..cb8afc4fa 100644
--- a/frontend/src/components/custom-tools/prompt-card/PromptCard.jsx
+++ b/frontend/src/components/custom-tools/prompt-card/PromptCard.jsx
@@ -1,5 +1,4 @@
import {
- ArrowDownOutlined,
CheckCircleOutlined,
DeleteOutlined,
EditOutlined,
@@ -14,9 +13,7 @@ import {
Button,
Card,
Col,
- Collapse,
Divider,
- Input,
Row,
Select,
Space,
@@ -25,11 +22,8 @@ import {
Tooltip,
Typography,
} from "antd";
-import debounce from "lodash/debounce";
import PropTypes from "prop-types";
-import { useCallback, useEffect, useRef, useState } from "react";
-
-import { AssertionIcon } from "../../../assets";
+import { useEffect, useRef, useState } from "react";
import {
displayPromptResult,
promptStudioUpdateStatus,
@@ -41,7 +35,6 @@ import { useCustomToolStore } from "../../../store/custom-tool-store";
import { useSessionStore } from "../../../store/session-store";
import { useSocketCustomToolStore } from "../../../store/socket-custom-tool";
import { ConfirmModal } from "../../widgets/confirm-modal/ConfirmModal";
-import SpaceWrapper from "../../widgets/space-wrapper/SpaceWrapper";
import { SpinnerLoader } from "../../widgets/spinner-loader/SpinnerLoader";
import { EditableText } from "../editable-text/EditableText";
import { OutputForDocModal } from "../output-for-doc-modal/OutputForDocModal";
@@ -67,7 +60,6 @@ function PromptCard({
const [enforceTypeList, setEnforceTypeList] = useState([]);
const [page, setPage] = useState(0);
const [isRunLoading, setIsRunLoading] = useState(false);
- const [displayAssertion, setDisplayAssertion] = useState(false);
const [openEval, setOpenEval] = useState(false);
const [promptKey, setPromptKey] = useState("");
const [promptText, setPromptText] = useState("");
@@ -131,9 +123,6 @@ function PromptCard({
}, [messages]);
useEffect(() => {
- if (promptDetails?.is_assert) {
- setDisplayAssertion(true);
- }
const outputTypeData = getDropdownItems("output_type");
const dropdownList1 = Object.keys(outputTypeData).map((item) => {
return { value: outputTypeData[item] };
@@ -197,17 +186,6 @@ function PromptCard({
}
}, [page]);
- useEffect(() => {
- if (displayAssertion !== promptDetails?.is_assert) {
- handleChange(
- displayAssertion,
- promptDetails?.prompt_id,
- "is_assert",
- true
- );
- }
- }, [displayAssertion]);
-
useEffect(() => {
if (isCoverageLoading && coverageTotal === listOfDocs?.length) {
setIsCoverageLoading(false);
@@ -220,13 +198,6 @@ function PromptCard({
setTokenCount({}); // Reset Token Count
};
- const onSearchDebounce = useCallback(
- debounce((event) => {
- handleChange(event, promptDetails?.prompt_id, false, true);
- }, 1000),
- []
- );
-
useEffect(() => {
const isProfilePresent = llmProfiles.some(
(profile) => profile.profile_id === selectedLlmProfileId
@@ -568,220 +539,142 @@ function PromptCard({
return (
<>
<Card className="prompt-card">
- <Collapse
- className="assertion-comp"
- ghost
- activeKey={displayAssertion ? "1" : null}
- >
- <Collapse.Panel key={"1"} showArrow={false}>
- <Row className="prompt-card-div">
- <Col span={8} className="assert-p-r-4">
- <Typography.Text strong className="font-size-12">
- Missing Context Prompt
- </Typography.Text>
- <div className="prompt-card-gap" />
- <Input.TextArea
- rows={2}
- defaultValue={promptDetails?.assert_prompt}
- name="assert_prompt"
- onChange={onSearchDebounce}
- disabled={
- disableLlmOrDocChange.includes(promptDetails?.prompt_id) ||
- isSinglePassExtractLoading ||
- indexDocs.includes(selectedDoc?.document_id)
- }
- />
- </Col>
- <Col span={8} className="assert-p-l-4 assert-p-r-4">
- <Typography.Text className="font-size-12" strong>
- False
- </Typography.Text>
- <div className="prompt-card-gap" />
- <Input.TextArea
- rows={2}
- defaultValue={promptDetails?.assertion_failure_prompt}
- name="assertion_failure_prompt"
- onChange={onSearchDebounce}
- disabled={
- disableLlmOrDocChange.includes(promptDetails?.prompt_id) ||
- isSinglePassExtractLoading ||
- indexDocs.includes(selectedDoc?.document_id)
- }
+ <div className="prompt-card-div prompt-card-bg-col1 prompt-card-rad">
+ <Space direction="vertical" className="width-100" ref={divRef}>
+ <Row>
+ <Col span={12}>
+ <EditableText
+ isEditing={isEditingTitle}
+ setIsEditing={setIsEditingTitle}
+ text={promptKey}
+ setText={setPromptKey}
+ promptId={promptDetails?.prompt_id}
+ defaultText={promptDetails?.prompt_key}
+ handleChange={handleChange}
+ placeHolder={updatePlaceHolder}
/>
</Col>
- <Col span={8} className="assert-p-l-4">
- <Typography.Text className="font-size-12" strong>
- True
- </Typography.Text>
- <div className="prompt-card-gap" />
- <SpaceWrapper>
- <Typography.Text className="font-size-12">
- The below prompt will be executed.
- </Typography.Text>
- <ArrowDownOutlined />
- </SpaceWrapper>
- </Col>
- </Row>
- </Collapse.Panel>
- </Collapse>
- <>
- {displayAssertion && <Divider className="prompt-card-divider" />}
- <div
- className={`prompt-card-div prompt-card-bg-col1 ${
- displayAssertion ? "" : "prompt-card-rad"
- }`}
- >
- <Space direction="vertical" className="width-100" ref={divRef}>
- <Row>
- <Col span={12}>
- <EditableText
- isEditing={isEditingTitle}
- setIsEditing={setIsEditingTitle}
- text={promptKey}
- setText={setPromptKey}
- promptId={promptDetails?.prompt_id}
- defaultText={promptDetails?.prompt_key}
- handleChange={handleChange}
- placeHolder={updatePlaceHolder}
- />
- </Col>
- <Col span={12} className="display-flex-right">
- {progressMsg?.message && (
- <Tooltip title={progressMsg?.message || ""}>
+ <Col span={12} className="display-flex-right">
+ {progressMsg?.message && (
+ <Tooltip title={progressMsg?.message || ""}>
+ <Tag
+ icon={isCoverageLoading && <LoadingOutlined spin />}
+ color={
+ progressMsg?.level === "ERROR" ? "error" : "processing"
+ }
+ className="display-flex-align-center"
+ >
+ <div className="tag-max-width ellipsis">
+ {progressMsg?.message}
+ </div>
+ </Tag>
+ </Tooltip>
+ )}
+ {updateStatus?.promptId === promptDetails?.prompt_id && (
+ <>
+ {updateStatus?.status ===
+ promptStudioUpdateStatus.isUpdating && (
<Tag
- icon={isCoverageLoading && <LoadingOutlined spin />}
- color={
- progressMsg?.level === "ERROR"
- ? "error"
- : "processing"
- }
+ icon={<SyncOutlined spin />}
+ color="processing"
className="display-flex-align-center"
>
- <div className="tag-max-width ellipsis">
- {progressMsg?.message}
- </div>
+ Updating
</Tag>
- </Tooltip>
- )}
- {updateStatus?.promptId === promptDetails?.prompt_id && (
- <>
- {updateStatus?.status ===
- promptStudioUpdateStatus.isUpdating && (
- <Tag
- icon={<SyncOutlined spin />}
- color="processing"
- className="display-flex-align-center"
- >
- Updating
- </Tag>
- )}
- {updateStatus?.status ===
- promptStudioUpdateStatus.done && (
- <Tag
- icon={<CheckCircleOutlined />}
- color="success"
- className="display-flex-align-center"
- >
- Done
- </Tag>
- )}
- {updateStatus?.status ===
- promptStudioUpdateStatus.validationError && (
- <Tag
- icon={<CheckCircleOutlined />}
- color="error"
- className="display-flex-align-center"
- >
- Invalid JSON Key
- </Tag>
- )}
- </>
- )}
- <Tooltip title="Edit">
+ )}
+ {updateStatus?.status === promptStudioUpdateStatus.done && (
+ <Tag
+ icon={<CheckCircleOutlined />}
+ color="success"
+ className="display-flex-align-center"
+ >
+ Done
+ </Tag>
+ )}
+ {updateStatus?.status ===
+ promptStudioUpdateStatus.validationError && (
+ <Tag
+ icon={<CheckCircleOutlined />}
+ color="error"
+ className="display-flex-align-center"
+ >
+ Invalid JSON Key
+ </Tag>
+ )}
+ </>
+ )}
+ <Tooltip title="Edit">
+ <Button
+ size="small"
+ type="text"
+ className="display-flex-align-center prompt-card-action-button"
+ onClick={enableEdit}
+ disabled={
+ disableLlmOrDocChange.includes(
+ promptDetails?.prompt_id
+ ) ||
+ isSinglePassExtractLoading ||
+ indexDocs.includes(selectedDoc?.document_id)
+ }
+ >
+ <EditOutlined className="prompt-card-actions-head" />
+ </Button>
+ </Tooltip>
+ {!singlePassExtractMode && (
+ <Tooltip title="Run">
<Button
size="small"
type="text"
- className="display-flex-align-center prompt-card-action-button"
- onClick={enableEdit}
+ className="prompt-card-action-button"
+ onClick={handleRun}
disabled={
- disableLlmOrDocChange.includes(
- promptDetails?.prompt_id
- ) ||
- isSinglePassExtractLoading ||
+ (updateStatus?.promptId === promptDetails?.prompt_id &&
+ updateStatus?.status ===
+ promptStudioUpdateStatus.isUpdating) ||
+ disableLlmOrDocChange?.length > 0 ||
indexDocs.includes(selectedDoc?.document_id)
}
>
- <EditOutlined className="prompt-card-actions-head" />
+ <PlayCircleOutlined className="prompt-card-actions-head" />
</Button>
</Tooltip>
- <Tooltip title="Assertion">
+ )}
+ <ConfirmModal
+ handleConfirm={() => handleDelete(promptDetails?.prompt_id)}
+ content="The prompt will be permanently deleted."
+ >
+ <Tooltip title="Delete">
<Button
size="small"
type="text"
- className="display-flex-align-center prompt-card-action-button"
- onClick={() => setDisplayAssertion(!displayAssertion)}
- disabled={true}
+ className="prompt-card-action-button"
+ disabled={
+ disableLlmOrDocChange.includes(
+ promptDetails?.prompt_id
+ ) ||
+ isSinglePassExtractLoading ||
+ indexDocs.includes(selectedDoc?.document_id)
+ }
>
- <AssertionIcon className="prompt-card-actions-head assertion-icon" />
+ <DeleteOutlined className="prompt-card-actions-head" />
</Button>
</Tooltip>
- {!singlePassExtractMode && (
- <Tooltip title="Run">
- <Button
- size="small"
- type="text"
- className="prompt-card-action-button"
- onClick={handleRun}
- disabled={
- (updateStatus?.promptId ===
- promptDetails?.prompt_id &&
- updateStatus?.status ===
- promptStudioUpdateStatus.isUpdating) ||
- disableLlmOrDocChange?.length > 0 ||
- indexDocs.includes(selectedDoc?.document_id)
- }
- >
- <PlayCircleOutlined className="prompt-card-actions-head" />
- </Button>
- </Tooltip>
- )}
- <ConfirmModal
- handleConfirm={() => handleDelete(promptDetails?.prompt_id)}
- content="The prompt will be permanently deleted."
- >
- <Tooltip title="Delete">
- <Button
- size="small"
- type="text"
- className="prompt-card-action-button"
- disabled={
- disableLlmOrDocChange.includes(
- promptDetails?.prompt_id
- ) ||
- isSinglePassExtractLoading ||
- indexDocs.includes(selectedDoc?.document_id)
- }
- >
- <DeleteOutlined className="prompt-card-actions-head" />
- </Button>
- </Tooltip>
- </ConfirmModal>
- </Col>
- </Row>
- <EditableText
- isEditing={isEditingPrompt}
- setIsEditing={setIsEditingPrompt}
- text={promptText}
- setText={setPromptText}
- promptId={promptDetails?.prompt_id}
- defaultText={promptDetails.prompt}
- handleChange={handleChange}
- isTextarea={true}
- placeHolder={updatePlaceHolder}
- />
- </Space>
- </div>
- </>
+ </ConfirmModal>
+ </Col>
+ </Row>
+ <EditableText
+ isEditing={isEditingPrompt}
+ setIsEditing={setIsEditingPrompt}
+ text={promptText}
+ setText={setPromptText}
+ promptId={promptDetails?.prompt_id}
+ defaultText={promptDetails.prompt}
+ handleChange={handleChange}
+ isTextarea={true}
+ placeHolder={updatePlaceHolder}
+ />
+ </Space>
+ </div>
<>
<Divider className="prompt-card-divider" />
<Space
diff --git a/frontend/src/components/custom-tools/tools-main/ToolsMain.jsx b/frontend/src/components/custom-tools/tools-main/ToolsMain.jsx
index caad513fe..376c40061 100644
--- a/frontend/src/components/custom-tools/tools-main/ToolsMain.jsx
+++ b/frontend/src/components/custom-tools/tools-main/ToolsMain.jsx
@@ -85,7 +85,6 @@ function ToolsMain() {
prompt: "",
tool_id: details?.tool_id,
prompt_type: promptType.prompt,
- is_assert: false,
profile_manager: defaultLlmProfile,
sequence_number: getSequenceNumber(),
};
diff --git a/prompt-service/sample.env b/prompt-service/sample.env
index 0caee4ed4..f8adc2341 100644
--- a/prompt-service/sample.env
+++ b/prompt-service/sample.env
@@ -14,3 +14,6 @@ REDIS_USER=default
# Platform Service
PLATFORM_SERVICE_HOST=http://unstract-platform-service
PLATFORM_SERVICE_PORT=3001
+
+# Logging
+LOG_LEVEL=INFO
diff --git a/prompt-service/src/unstract/prompt_service/config.py b/prompt-service/src/unstract/prompt_service/config.py
new file mode 100644
index 000000000..22073db6b
--- /dev/null
+++ b/prompt-service/src/unstract/prompt_service/config.py
@@ -0,0 +1,40 @@
+import logging
+from logging.config import dictConfig
+from os import environ as env
+
+from dotenv import load_dotenv
+from flask import Flask
+from unstract.prompt_service.constants import LogLevel
+
+load_dotenv()
+
+dictConfig(
+ {
+ "version": 1,
+ "formatters": {
+ "default": {
+ "format": "[%(asctime)s] %(levelname)s in %(module)s: %(message)s",
+ }
+ },
+ "handlers": {
+ "wsgi": {
+ "class": "logging.StreamHandler",
+ "stream": "ext://flask.logging.wsgi_errors_stream",
+ "formatter": "default",
+ }
+ },
+ "root": {"level": "INFO", "handlers": ["wsgi"]},
+ }
+)
+
+
+def create_app() -> Flask:
+ app = Flask("prompt-service")
+ log_level = env.get("LOG_LEVEL", LogLevel.WARN)
+ if log_level == LogLevel.DEBUG.value:
+ app.logger.setLevel(logging.DEBUG)
+ elif log_level == LogLevel.INFO.value:
+ app.logger.setLevel(logging.INFO)
+ else:
+ app.logger.setLevel(logging.WARNING)
+ return app
diff --git a/prompt-service/src/unstract/prompt_service/exceptions.py b/prompt-service/src/unstract/prompt_service/exceptions.py
index 9d0a4208c..e8f2d6c63 100644
--- a/prompt-service/src/unstract/prompt_service/exceptions.py
+++ b/prompt-service/src/unstract/prompt_service/exceptions.py
@@ -22,15 +22,16 @@ class APIError(HTTPException):
def __init__(
self,
- message: str = DEFAULT_ERR_MESSAGE,
+ message: Optional[str] = None,
code: Optional[int] = None,
payload: Any = None,
):
- super().__init__(description=message)
- self.message = message
- if code is not None:
+ if message:
+ self.message = message
+ if code:
self.code = code
self.payload = payload
+ super().__init__(description=message)
def to_dict(self):
err = ErrorResponse(
diff --git a/prompt-service/src/unstract/prompt_service/main.py b/prompt-service/src/unstract/prompt_service/main.py
index 27407a5ce..dedd5b2dd 100644
--- a/prompt-service/src/unstract/prompt_service/main.py
+++ b/prompt-service/src/unstract/prompt_service/main.py
@@ -1,15 +1,15 @@
-import logging
import traceback
from enum import Enum
from json import JSONDecodeError
from typing import Any, Optional
import peewee
-from flask import Flask, json, jsonify, request
+from flask import json, jsonify, request
from llama_index.core import VectorStoreIndex
from llama_index.core.llms import LLM
from llama_index.core.vector_stores import ExactMatchFilter, MetadataFilters
from unstract.prompt_service.authentication_middleware import AuthenticationMiddleware
+from unstract.prompt_service.config import create_app
from unstract.prompt_service.constants import PromptServiceContants as PSKeys
from unstract.prompt_service.constants import RunLevel
from unstract.prompt_service.exceptions import (
@@ -32,11 +32,6 @@ from werkzeug.exceptions import HTTPException
from unstract.core.pubsub_helper import LogPublisher
-logging.basicConfig(
- level=logging.INFO,
- format="%(asctime)s %(levelname)s %(name)s : %(message)s",
-)
-
POS_TEXT_PATH = "/tmp/pos.txt"
USE_UNSTRACT_PROMPT = True
MAX_RETRIES = 3
@@ -59,7 +54,8 @@ be_db.connect()
AuthenticationMiddleware.be_db = be_db
-app = Flask("prompt-service")
+app = create_app()
+
plugins: dict[str, dict[str, Any]] = plugin_loader(app)
@@ -170,10 +166,9 @@ def authentication_middleware(func: Any) -> Any:
@authentication_middleware
def prompt_processor() -> Any:
platform_key = AuthenticationMiddleware.get_token_from_auth_header(request)
- if request.method == "POST":
- payload: dict[Any, Any] = request.json
- if not payload:
- raise NoPayloadError()
+ payload: dict[Any, Any] = request.json
+ if not payload:
+ raise NoPayloadError
outputs = payload.get(PSKeys.OUTPUTS)
tool_id: str = payload.get(PSKeys.TOOL_ID, "")
file_hash = payload.get(PSKeys.FILE_HASH)
@@ -193,7 +188,7 @@ def prompt_processor() -> Any:
for output in outputs: # type:ignore
variable_names.append(output[PSKeys.NAME])
for output in outputs: # type:ignore
- active = output[PSKeys.ACTIVE]
+ is_active = output[PSKeys.ACTIVE]
prompt_name = output[PSKeys.NAME]
promptx = output[PSKeys.PROMPT]
chunk_size = output[PSKeys.CHUNK_SIZE]
@@ -201,7 +196,7 @@ def prompt_processor() -> Any:
tool_index = ToolIndex(tool=util)
adapter_instance_id = output[PSKeys.LLM]
- if active is False:
+ if is_active is False:
app.logger.info(f"[{tool_id}] Skipping inactive prompt: {prompt_name}")
_publish_log(
log_events_id,
@@ -293,7 +288,9 @@ def prompt_processor() -> Any:
if context is None:
# TODO: Obtain user set name for vector DB
msg = "Couldn't fetch context from vector DB"
- app.logger.error(msg + f" {output[PSKeys.VECTOR_DB]}")
+ app.logger.error(
+ f"{msg} {output[PSKeys.VECTOR_DB]} for doc_id {doc_id}"
+ )
_publish_log(
log_events_id,
{
@@ -315,102 +312,64 @@ def prompt_processor() -> Any:
"Fetched context from vector DB",
)
- assertion_failed = False
- answer = "yes"
- _publish_log(
- log_events_id,
- {"tool_id": tool_id, "prompt_key": prompt_name, "doc_name": doc_name},
- LogLevel.DEBUG,
- RunLevel.RUN,
- "Verifying assertion prompt",
- )
-
- is_assert = output[PSKeys.IS_ASSERT]
- if is_assert:
- app.logger.debug(f'Asserting prompt: {output["assert_prompt"]}')
+ if chunk_size == 0:
+ _publish_log(
+ log_events_id,
+ {
+ "tool_id": tool_id,
+ "prompt_key": prompt_name,
+ "doc_name": doc_name,
+ },
+ LogLevel.INFO,
+ RunLevel.RUN,
+ "Retrieving answer from LLM",
+ )
answer = construct_and_run_prompt(
output,
llm_helper,
llm_li,
context,
- "assert_prompt",
+ "promptx",
)
- app.logger.debug(f"Assert response: {answer}")
- if answer.startswith("No") or answer.startswith("no"):
- app.logger.info("Assert failed.")
+ else:
+ answer = "NA"
_publish_log(
log_events_id,
- {"tool_id": tool_id, "prompt_key": prompt_name, "doc_name": doc_name},
- LogLevel.DEBUG,
+ {
+ "tool_id": tool_id,
+ "prompt_key": prompt_name,
+ "doc_name": doc_name,
+ },
+ LogLevel.INFO,
RunLevel.RUN,
- "Assertion failed",
+ "Retrieving context from adapter",
)
- assertion_failed = True
- answer = ""
- if output[PSKeys.ASSERTION_FAILURE_PROMPT].lower().startswith("@assign"):
- answer = "NA"
- first_space_index = output[PSKeys.ASSERTION_FAILURE_PROMPT].find(" ")
- if first_space_index > 0:
- answer = output[PSKeys.ASSERTION_FAILURE_PROMPT][
- first_space_index + 1
- ]
- app.logger.info(f"[Assigning] {answer} to the output")
- else:
- answer = construct_and_run_prompt(
- output,
- llm_helper,
- llm_li,
- context,
- "assertion_failure_prompt",
- )
- else:
- if chunk_size == 0:
- answer = construct_and_run_prompt(
+
+ if output[PSKeys.RETRIEVAL_STRATEGY] == PSKeys.SIMPLE:
+ answer, context = simple_retriver(
output,
+ doc_id,
llm_helper,
llm_li,
- context,
- "promptx",
+ vector_index,
)
else:
- answer = "NA"
- _publish_log(
- log_events_id,
- {
- "tool_id": tool_id,
- "prompt_key": prompt_name,
- "doc_name": doc_name,
- },
- LogLevel.INFO,
- RunLevel.RUN,
- "Retrieving context from adapter",
+ app.logger.info(
+ "Invalid retrieval strategy "
+ f"passed {output[PSKeys.RETRIEVAL_STRATEGY]}"
)
- if output[PSKeys.RETRIEVAL_STRATEGY] == PSKeys.SIMPLE:
- answer, context = simple_retriver(
- output,
- doc_id,
- llm_helper,
- llm_li,
- vector_index,
- )
- else:
- app.logger.info(
- "Invalid retrieval strategy "
- f"passed {output[PSKeys.RETRIEVAL_STRATEGY]}"
- )
-
- _publish_log(
- log_events_id,
- {
- "tool_id": tool_id,
- "prompt_key": prompt_name,
- "doc_name": doc_name,
- },
- LogLevel.DEBUG,
- RunLevel.RUN,
- "Retrieved context from adapter",
- )
+ _publish_log(
+ log_events_id,
+ {
+ "tool_id": tool_id,
+ "prompt_key": prompt_name,
+ "doc_name": doc_name,
+ },
+ LogLevel.DEBUG,
+ RunLevel.RUN,
+ "Retrieved context from adapter",
+ )
_publish_log(
log_events_id,
@@ -421,7 +380,7 @@ def prompt_processor() -> Any:
)
if output[PSKeys.TYPE] == PSKeys.NUMBER:
- if assertion_failed or answer.lower() == "na":
+ if answer.lower() == "na":
structured_output[output[PSKeys.NAME]] = None
else:
# TODO: Extract these prompts as constants after pkging
@@ -450,7 +409,7 @@ def prompt_processor() -> Any:
)
structured_output[output[PSKeys.NAME]] = None
elif output[PSKeys.TYPE] == PSKeys.EMAIL:
- if assertion_failed or answer.lower() == "na":
+ if answer.lower() == "na":
structured_output[output[PSKeys.NAME]] = None
else:
prompt = f'Extract the email from the following text:\n{answer}\n\nOutput just the email. \
@@ -464,7 +423,7 @@ def prompt_processor() -> Any:
)
structured_output[output[PSKeys.NAME]] = answer
elif output[PSKeys.TYPE] == PSKeys.DATE:
- if assertion_failed or answer.lower() == "na":
+ if answer.lower() == "na":
structured_output[output[PSKeys.NAME]] = None
else:
prompt = f'Extract the date from the following text:\n{answer}\n\nOutput just the date.\
@@ -480,7 +439,7 @@ def prompt_processor() -> Any:
structured_output[output[PSKeys.NAME]] = answer
elif output[PSKeys.TYPE] == PSKeys.BOOLEAN:
- if assertion_failed or answer.lower() == "na":
+ if answer.lower() == "na":
structured_output[output[PSKeys.NAME]] = None
else:
prompt = f'Extract yes/no from the following text:\n{answer}\n\n\
@@ -498,7 +457,7 @@ def prompt_processor() -> Any:
else:
structured_output[output[PSKeys.NAME]] = False
elif output[PSKeys.TYPE] == PSKeys.JSON:
- if assertion_failed or answer.lower() == "[]" or answer.lower() == "na":
+ if answer.lower() == "[]" or answer.lower() == "na":
structured_output[output[PSKeys.NAME]] = None
else:
prompt = f"Convert the following text into valid JSON string: \
@@ -780,7 +739,7 @@ def run_completion(
except SdkRateLimitError as e:
raise RateLimitError(f"Rate limit error. {str(e)}") from e
except Exception as e:
- app.logger.info(f"Error fetching response for prompt: {e}.")
+ app.logger.error(f"Error fetching response for prompt: {e}.")
# TODO: Publish this error as a FE update
raise APIError(str(e)) from e
@@ -880,6 +839,6 @@ def handle_uncaught_exception(e):
return handle_http_exception(APIError())
+# TODO: Review if below code is needed
if __name__ == "__main__":
- # Start the server
app.run(host="0.0.0.0", port=5003)
diff --git a/tools/structure/src/main.py b/tools/structure/src/main.py
index 770eca2c1..fff0095eb 100644
--- a/tools/structure/src/main.py
+++ b/tools/structure/src/main.py
@@ -1,4 +1,5 @@
import json
+import os
import sys
from pathlib import Path
from typing import Any
@@ -65,11 +66,13 @@ class StructureTool(BaseTool):
except Exception as e:
self.stream_error_and_exit(f"Error fetching data and indexing: {e}")
+ _, file_name = os.path.split(input_file)
# TODO : Check if reindex. If Yes, reindex, else continue.
payload = {
"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)