Skip to content

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

FEAT: Prompt Collapse and Re-Ordering (#391)

Tahier Hussaindd79450d93f7
diff --git a/backend/prompt_studio/prompt_studio/constants.py b/backend/prompt_studio/prompt_studio/constants.py
index 4df053d82..6554a9f8c 100644
--- a/backend/prompt_studio/prompt_studio/constants.py
+++ b/backend/prompt_studio/prompt_studio/constants.py
@@ -13,6 +13,10 @@ class ToolStudioPromptKeys:
PROMPT_KEY = "prompt_key"
EVAL_METRIC_PREFIX = "eval_"
EVAL_RESULT_DELIM = "__"
+ SEQUENCE_NUMBER = "sequence_number"
+ START_SEQUENCE_NUMBER = "start_sequence_number"
+ END_SEQUENCE_NUMBER = "end_sequence_number"
+ PROMPT_ID = "prompt_id"
class ToolStudioPromptErrors:
diff --git a/backend/prompt_studio/prompt_studio/controller.py b/backend/prompt_studio/prompt_studio/controller.py
new file mode 100644
index 000000000..4a0280200
--- /dev/null
+++ b/backend/prompt_studio/prompt_studio/controller.py
@@ -0,0 +1,58 @@
+import logging
+
+from prompt_studio.prompt_studio.constants import ToolStudioPromptKeys
+from prompt_studio.prompt_studio.helper import PromptStudioHelper
+from prompt_studio.prompt_studio.models import ToolStudioPrompt
+from prompt_studio.prompt_studio.serializers import ReorderPromptsSerializer
+from rest_framework import status
+from rest_framework.request import Request
+from rest_framework.response import Response
+
+logger = logging.getLogger(__name__)
+
+
+class PromptStudioController:
+ def reorder_prompts(self, request: Request) -> Response:
+ """Reorder the sequence of prompts based on the start and end sequence
+ numbers.
+
+ This action handles the reordering of prompts by updating their sequence
+ numbers. It increments or decrements the sequence numbers of the relevant
+ prompts to reflect the new order. If the start and end sequence numbers
+ are equal, it returns a bad request response.
+
+ Args:
+ request (Request): The HTTP request object containing the data to
+ reorder prompts.
+
+ Returns:
+ Response: A Response object with the status of the reordering operation.
+ """
+ try:
+ # Validate request data
+ serializer = ReorderPromptsSerializer(data=request.data)
+ serializer.is_valid(raise_exception=True)
+
+ # Extract validated data from the serializer
+ start_sequence_number = serializer.validated_data.get(
+ ToolStudioPromptKeys.START_SEQUENCE_NUMBER
+ )
+ end_sequence_number = serializer.validated_data.get(
+ ToolStudioPromptKeys.END_SEQUENCE_NUMBER
+ )
+ prompt_id = serializer.validated_data.get(ToolStudioPromptKeys.PROMPT_ID)
+
+ filtered_prompts_data = PromptStudioHelper.reorder_prompts_helper(
+ prompt_id=prompt_id,
+ start_sequence_number=start_sequence_number,
+ end_sequence_number=end_sequence_number,
+ )
+
+ logger.info("Re-ordering completed successfully.")
+ return Response(status=status.HTTP_200_OK, data=filtered_prompts_data)
+
+ except ToolStudioPrompt.DoesNotExist:
+ logger.error(f"Prompt with ID {prompt_id} not found.")
+ return Response(
+ status=status.HTTP_404_NOT_FOUND, data={"detail": "Prompt not found."}
+ )
diff --git a/backend/prompt_studio/prompt_studio/helper.py b/backend/prompt_studio/prompt_studio/helper.py
new file mode 100644
index 000000000..f362104c2
--- /dev/null
+++ b/backend/prompt_studio/prompt_studio/helper.py
@@ -0,0 +1,111 @@
+import logging
+
+from prompt_studio.prompt_studio.models import ToolStudioPrompt
+
+logger = logging.getLogger(__name__)
+
+
+class PromptStudioHelper:
+ @staticmethod
+ def reorder_prompts_helper(
+ prompt_id: str, start_sequence_number: int, end_sequence_number: int
+ ) -> list[dict[str, int]]:
+ """Helper method to reorder prompts based on sequence numbers.
+
+ Args:
+ prompt_id (str): The ID of the prompt to be reordered.
+ start_sequence_number (int): The initial sequence number of the prompt.
+ end_sequence_number (int): The new sequence number of the prompt.
+
+ Returns:
+ list[dict[str, int]]: A list of updated prompt data with their IDs
+ and new sequence numbers.
+ """
+ prompt_instance: ToolStudioPrompt = ToolStudioPrompt.objects.get(pk=prompt_id)
+ filtered_prompts_data = []
+ tool_id = prompt_instance.tool_id
+
+ # Determine the direction of sequence adjustment based on start
+ # and end sequence numbers
+ if start_sequence_number < end_sequence_number:
+ logger.info(
+ "Start sequence number is less than end sequence number. "
+ "Decrementing sequence numbers."
+ )
+ filters = {
+ "sequence_number__gt": start_sequence_number,
+ "sequence_number__lte": end_sequence_number,
+ "tool_id": tool_id,
+ }
+ increment = False
+
+ elif start_sequence_number > end_sequence_number:
+ logger.info(
+ "Start sequence number is greater than end sequence number. "
+ "Incrementing sequence numbers."
+ )
+ filters = {
+ "sequence_number__lt": start_sequence_number,
+ "sequence_number__gte": end_sequence_number,
+ "tool_id": tool_id,
+ }
+ increment = True
+
+ # Call helper method to update sequence numbers and get filtered prompt data
+ filtered_prompts_data = PromptStudioHelper.update_sequence_numbers(
+ filters, increment
+ )
+
+ # Update the sequence number of the moved prompt
+ prompt_instance.sequence_number = end_sequence_number
+ prompt_instance.save()
+
+ # Append the updated prompt instance data to the response
+ filtered_prompts_data.append(
+ {
+ "id": prompt_instance.prompt_id,
+ "sequence_number": prompt_instance.sequence_number,
+ }
+ )
+
+ return filtered_prompts_data
+
+ @staticmethod
+ def update_sequence_numbers(filters: dict, increment: bool) -> list[dict[str, int]]:
+ """Update the sequence numbers for prompts based on the provided
+ filters and increment flag.
+
+ Args:
+ filters (dict): The filter criteria for selecting prompts.
+ increment (bool): Whether to increment (True) or decrement (False)
+ the sequence numbers.
+
+ Returns:
+ list[dict[str, int]]: A list of updated prompt data with their IDs
+ and new sequence numbers.
+ """
+ # Filter prompts based on the provided filters
+ filtered_prompts = ToolStudioPrompt.objects.filter(**filters)
+
+ # List to hold updated prompt data
+ filtered_prompts_data = []
+
+ # Prepare updates and collect data
+ for prompt in filtered_prompts:
+ if increment:
+ prompt.sequence_number += 1
+ else:
+ prompt.sequence_number -= 1
+
+ # Append prompt data to the list
+ filtered_prompts_data.append(
+ {
+ "id": prompt.prompt_id,
+ "sequence_number": prompt.sequence_number,
+ }
+ )
+
+ # Bulk update the sequence numbers
+ ToolStudioPrompt.objects.bulk_update(filtered_prompts, ["sequence_number"])
+
+ return filtered_prompts_data
diff --git a/backend/prompt_studio/prompt_studio/serializers.py b/backend/prompt_studio/prompt_studio/serializers.py
index 56d7f0faf..e1adddc33 100644
--- a/backend/prompt_studio/prompt_studio/serializers.py
+++ b/backend/prompt_studio/prompt_studio/serializers.py
@@ -14,3 +14,20 @@ class ToolStudioPromptSerializer(AuditSerializer):
class ToolStudioIndexSerializer(serializers.Serializer):
file_name = serializers.CharField()
tool_id = serializers.CharField()
+
+
+class ReorderPromptsSerializer(serializers.Serializer):
+ start_sequence_number = serializers.IntegerField(required=True)
+ end_sequence_number = serializers.IntegerField(required=True)
+ prompt_id = serializers.CharField(required=True)
+
+ def validate(self, data):
+ start_sequence_number = data.get("start_sequence_number")
+ end_sequence_number = data.get("end_sequence_number")
+
+ if start_sequence_number == end_sequence_number:
+ raise serializers.ValidationError(
+ "Start and end sequence numbers cannot be the same."
+ )
+
+ return data
diff --git a/backend/prompt_studio/prompt_studio/urls.py b/backend/prompt_studio/prompt_studio/urls.py
index e2f06d824..3d8c3d74c 100644
--- a/backend/prompt_studio/prompt_studio/urls.py
+++ b/backend/prompt_studio/prompt_studio/urls.py
@@ -12,6 +12,8 @@ prompt_studio_prompt_detail = ToolStudioPromptView.as_view(
}
)
+reorder_prompts = ToolStudioPromptView.as_view({"post": "reorder_prompts"})
+
urlpatterns = format_suffix_patterns(
[
path(
@@ -19,5 +21,10 @@ urlpatterns = format_suffix_patterns(
prompt_studio_prompt_detail,
name="tool-studio-prompt-detail",
),
+ path(
+ "prompt/reorder",
+ reorder_prompts,
+ name="reorder_prompts",
+ ),
]
)
diff --git a/backend/prompt_studio/prompt_studio/views.py b/backend/prompt_studio/prompt_studio/views.py
index aa1604bc7..ef68a13a5 100644
--- a/backend/prompt_studio/prompt_studio/views.py
+++ b/backend/prompt_studio/prompt_studio/views.py
@@ -1,18 +1,18 @@
-import logging
from typing import Optional
from django.db.models import QuerySet
from prompt_studio.permission import PromptAcesssToUser
from prompt_studio.prompt_studio.constants import ToolStudioPromptKeys
+from prompt_studio.prompt_studio.controller import PromptStudioController
+from prompt_studio.prompt_studio.models import ToolStudioPrompt
+from prompt_studio.prompt_studio.serializers import ToolStudioPromptSerializer
from rest_framework import viewsets
+from rest_framework.decorators import action
+from rest_framework.request import Request
+from rest_framework.response import Response
from rest_framework.versioning import URLPathVersioning
from utils.filtering import FilterHelper
-from .models import ToolStudioPrompt
-from .serializers import ToolStudioPromptSerializer
-
-logger = logging.getLogger(__name__)
-
class ToolStudioPromptView(viewsets.ModelViewSet):
"""Viewset to handle all Tool Studio prompt related API logics.
@@ -41,3 +41,16 @@ class ToolStudioPromptView(viewsets.ModelViewSet):
else:
queryset = ToolStudioPrompt.objects.all()
return queryset
+
+ @action(detail=True, methods=["post"])
+ def reorder_prompts(self, request: Request) -> Response:
+ """Reorder the sequence of prompts based on the provided data.
+
+ Args:
+ request (Request): The HTTP request containing the reorder data.
+
+ Returns:
+ Response: The HTTP response indicating the status of the reorder operation.
+ """
+ prompt_studio_controller = PromptStudioController()
+ return prompt_studio_controller.reorder_prompts(request)
diff --git a/frontend/src/components/custom-tools/document-parser/DocumentParser.jsx b/frontend/src/components/custom-tools/document-parser/DocumentParser.jsx
index 390ae6c41..a98fa81b2 100644
--- a/frontend/src/components/custom-tools/document-parser/DocumentParser.jsx
+++ b/frontend/src/components/custom-tools/document-parser/DocumentParser.jsx
@@ -1,7 +1,9 @@
import PropTypes from "prop-types";
import { useEffect, useRef, useState } from "react";
-import "./DocumentParser.css";
+import { DndProvider } from "react-dnd";
+import { HTML5Backend } from "react-dnd-html5-backend";
+import "./DocumentParser.css";
import {
promptStudioUpdateStatus,
promptType,
@@ -11,9 +13,8 @@ import { useAlertStore } from "../../../store/alert-store";
import { useCustomToolStore } from "../../../store/custom-tool-store";
import { useSessionStore } from "../../../store/session-store";
import { EmptyState } from "../../widgets/empty-state/EmptyState";
-import { NotesCard } from "../notes-card/NotesCard";
-import { PromptCard } from "../prompt-card/PromptCard";
import { useExceptionHandler } from "../../../hooks/useExceptionHandler";
+import { PromptDnd } from "../prompt-card/PrompDnd";
function DocumentParser({
addPromptInstance,
@@ -200,6 +201,74 @@ function DocumentParser({
});
};
+ const moveItem = (startIndex, endIndex) => {
+ if (startIndex === endIndex) {
+ return;
+ }
+
+ // Clone details and prompts
+ const updatedPrompts = [...(details?.prompts || [])];
+
+ // Move the item within the updated prompts array
+ const [movedStep] = updatedPrompts.splice(startIndex, 1);
+ updatedPrompts.splice(endIndex, 0, movedStep);
+
+ // Modify the prompts order and update
+ const modifiedDetails = { ...details, prompts: updatedPrompts };
+ updateCustomTool({ details: modifiedDetails });
+
+ // Prepare the body for the POST request
+ const body = {
+ start_sequence_number: details.prompts[startIndex]?.sequence_number,
+ end_sequence_number: details.prompts[endIndex]?.sequence_number,
+ prompt_id: details.prompts[startIndex]?.prompt_id,
+ };
+
+ const requestOptions = {
+ method: "POST",
+ url: `/api/v1/unstract/${sessionDetails?.orgId}/prompt-studio/prompt/reorder`,
+ headers: {
+ "X-CSRFToken": sessionDetails?.csrfToken,
+ "Content-Type": "application/json",
+ },
+ data: body,
+ };
+
+ axiosPrivate(requestOptions)
+ .then((res) => {
+ const data = res?.data || [];
+
+ // Update sequence numbers based on the response
+ handleMoveItemSuccess(updatedPrompts, data);
+ })
+ .catch((err) => {
+ // Revert to the original prompts on error
+ updateCustomTool({
+ details: { ...details, prompts: details?.prompts },
+ });
+ setAlertDetails(handleException(err, "Failed to re-order the prompts"));
+ });
+ };
+
+ const handleMoveItemSuccess = (updatedPrompts, updatedSequenceNums) => {
+ const updatedPromptSequenceNum = updatedPrompts.map((promptItem) => {
+ const newPromptSeqNum = updatedSequenceNums.find(
+ (item) => item?.id === promptItem?.prompt_id
+ );
+ if (newPromptSeqNum) {
+ return {
+ ...promptItem,
+ sequence_number: newPromptSeqNum.sequence_number,
+ };
+ }
+ return promptItem;
+ });
+
+ updateCustomTool({
+ details: { ...details, prompts: updatedPromptSequenceNum },
+ });
+ };
+
if (!details?.prompts?.length) {
return (
<EmptyState
@@ -212,32 +281,24 @@ function DocumentParser({
return (
<div className="doc-parser-layout">
- {details?.prompts.map((item) => {
- return (
- <div key={item.prompt_id}>
- <div className="doc-parser-pad-top" />
- {item.prompt_type === promptType.prompt && (
- <PromptCard
- promptDetails={item}
+ <DndProvider backend={HTML5Backend}>
+ {details?.prompts.map((item, index) => {
+ return (
+ <div key={item.prompt_id}>
+ <div className="doc-parser-pad-top" />
+ <PromptDnd
+ item={item}
+ index={index}
handleChange={handleChange}
handleDelete={handleDelete}
updateStatus={updateStatus}
- updatePlaceHolder="Enter Prompt"
+ moveItem={moveItem}
/>
- )}
- {item.prompt_type === promptType.notes && (
- <NotesCard
- details={item}
- handleChange={handleChange}
- handleDelete={handleDelete}
- updateStatus={updateStatus}
- updatePlaceHolder="Enter Notes"
- />
- )}
- <div ref={bottomRef} className="doc-parser-pad-bottom" />
- </div>
- );
- })}
+ <div ref={bottomRef} className="doc-parser-pad-bottom" />
+ </div>
+ );
+ })}
+ </DndProvider>
</div>
);
}
diff --git a/frontend/src/components/custom-tools/notes-card/NotesCard.css b/frontend/src/components/custom-tools/notes-card/NotesCard.css
index be4693152..dadd723a7 100644
--- a/frontend/src/components/custom-tools/notes-card/NotesCard.css
+++ b/frontend/src/components/custom-tools/notes-card/NotesCard.css
@@ -6,7 +6,7 @@
}
.tool-ide-notes-card .ant-card-body {
- padding: 14px !important;
+ padding: 12px !important;
}
.tool-ide-notes-card .delete-icon {
diff --git a/frontend/src/components/custom-tools/notes-card/NotesCard.jsx b/frontend/src/components/custom-tools/notes-card/NotesCard.jsx
index 3e1076005..309ed28b5 100644
--- a/frontend/src/components/custom-tools/notes-card/NotesCard.jsx
+++ b/frontend/src/components/custom-tools/notes-card/NotesCard.jsx
@@ -4,7 +4,7 @@ import {
EditOutlined,
SyncOutlined,
} from "@ant-design/icons";
-import { Button, Card, Col, Row, Space, Tag, Tooltip } from "antd";
+import { Button, Card, Col, Collapse, Row, Space, Tag, Tooltip } from "antd";
import PropTypes from "prop-types";
import "./NotesCard.css";
import { useState } from "react";
@@ -12,6 +12,7 @@ import { useState } from "react";
import { EditableText } from "../editable-text/EditableText";
import { ConfirmModal } from "../../widgets/confirm-modal/ConfirmModal";
import { promptStudioUpdateStatus } from "../../../helpers/GetStaticData";
+import { ExpandCardBtn } from "../prompt-card/ExpandCardBtn";
function NotesCard({
details,
@@ -24,6 +25,7 @@ function NotesCard({
const [promptText, setPromptText] = useState("");
const [isEditingTitle, setIsEditingTitle] = useState(false);
const [isEditingNote, setIsEditingNote] = useState(false);
+ const [expandCard, setExpandCard] = useState(true);
const enableEdit = (event) => {
event.stopPropagation();
@@ -33,7 +35,11 @@ function NotesCard({
return (
<Card className="tool-ide-notes-card">
- <Space direction="vertical" className="width-100">
+ <Space
+ direction="vertical"
+ className="width-100"
+ size={expandCard ? 10 : 0}
+ >
<Row>
<Col span={18}>
<EditableText
@@ -71,6 +77,10 @@ function NotesCard({
)}
</>
)}
+ <ExpandCardBtn
+ expandCard={expandCard}
+ setExpandCard={setExpandCard}
+ />
<Tooltip title="Edit">
<Button
size="small"
@@ -93,17 +103,25 @@ function NotesCard({
</ConfirmModal>
</Col>
</Row>
- <EditableText
- isEditing={isEditingNote}
- setIsEditing={setIsEditingNote}
- text={promptText}
- setText={setPromptText}
- promptId={details?.prompt_id}
- defaultText={details?.prompt}
- handleChange={handleChange}
- isTextarea={true}
- placeHolder={updatePlaceHolder}
- />
+ <Collapse
+ className="prompt-card-collapse"
+ ghost
+ activeKey={expandCard && "1"}
+ >
+ <Collapse.Panel key={"1"}>
+ <EditableText
+ isEditing={isEditingNote}
+ setIsEditing={setIsEditingNote}
+ text={promptText}
+ setText={setPromptText}
+ promptId={details?.prompt_id}
+ defaultText={details?.prompt}
+ handleChange={handleChange}
+ isTextarea={true}
+ placeHolder={updatePlaceHolder}
+ />
+ </Collapse.Panel>
+ </Collapse>
</Space>
</Card>
);
diff --git a/frontend/src/components/custom-tools/prompt-card/ExpandCardBtn.jsx b/frontend/src/components/custom-tools/prompt-card/ExpandCardBtn.jsx
new file mode 100644
index 000000000..ac2abba6a
--- /dev/null
+++ b/frontend/src/components/custom-tools/prompt-card/ExpandCardBtn.jsx
@@ -0,0 +1,43 @@
+import { FullscreenExitOutlined, FullscreenOutlined } from "@ant-design/icons";
+import { Button, Tooltip } from "antd";
+import PropTypes from "prop-types";
+import { useEffect, useState } from "react";
+
+function ExpandCardBtn({ expandCard, setExpandCard }) {
+ const [icon, setIcon] = useState(null);
+ const [tooltip, setTooltip] = useState("");
+
+ useEffect(() => {
+ if (expandCard) {
+ setIcon(<FullscreenExitOutlined className="prompt-card-actions-head" />);
+ setTooltip("Expand");
+ } else {
+ setIcon(<FullscreenOutlined className="prompt-card-actions-head" />);
+ setTooltip("Collapse");
+ }
+ }, [expandCard]);
+
+ const handleClick = () => {
+ setExpandCard(!expandCard);
+ };
+
+ return (
+ <Tooltip title={tooltip}>
+ <Button
+ size="small"
+ type="text"
+ className="prompt-card-action-button"
+ onClick={handleClick}
+ >
+ {icon}
+ </Button>
+ </Tooltip>
+ );
+}
+
+ExpandCardBtn.propTypes = {
+ expandCard: PropTypes.bool.isRequired,
+ setExpandCard: PropTypes.func.isRequired,
+};
+
+export { ExpandCardBtn };
diff --git a/frontend/src/components/custom-tools/prompt-card/Header.jsx b/frontend/src/components/custom-tools/prompt-card/Header.jsx
new file mode 100644
index 000000000..35ac9d5aa
--- /dev/null
+++ b/frontend/src/components/custom-tools/prompt-card/Header.jsx
@@ -0,0 +1,185 @@
+import {
+ CheckCircleOutlined,
+ DeleteOutlined,
+ EditOutlined,
+ LoadingOutlined,
+ PlayCircleOutlined,
+ SyncOutlined,
+} from "@ant-design/icons";
+import { Button, Col, Row, Tag, Tooltip } from "antd";
+import PropTypes from "prop-types";
+
+import { promptStudioUpdateStatus } from "../../../helpers/GetStaticData";
+import { ConfirmModal } from "../../widgets/confirm-modal/ConfirmModal";
+import { EditableText } from "../editable-text/EditableText";
+import { useCustomToolStore } from "../../../store/custom-tool-store";
+import { ExpandCardBtn } from "./ExpandCardBtn";
+
+function Header({
+ promptDetails,
+ promptKey,
+ setPromptKey,
+ progressMsg,
+ handleRun,
+ handleChange,
+ handleDelete,
+ updateStatus,
+ updatePlaceHolder,
+ isCoverageLoading,
+ isEditingTitle,
+ setIsEditingTitle,
+ enableEdit,
+ expandCard,
+ setExpandCard,
+}) {
+ const {
+ selectedDoc,
+ disableLlmOrDocChange,
+ singlePassExtractMode,
+ isSinglePassExtractLoading,
+ indexDocs,
+ } = useCustomToolStore();
+
+ const handleRunBtnClick = () => {
+ setExpandCard(true);
+ handleRun();
+ };
+
+ return (
+ <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 || ""}>
+ <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={<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>
+ )}
+ </>
+ )}
+ <ExpandCardBtn expandCard={expandCard} setExpandCard={setExpandCard} />
+ <Tooltip title="Edit">
+ <Button
+ size="small"
+ type="text"
+ className="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="prompt-card-action-button"
+ onClick={handleRunBtnClick}
+ disabled={
+ (updateStatus?.promptId === promptDetails?.prompt_id &&
+ updateStatus?.status ===
+ promptStudioUpdateStatus.isUpdating) ||
+ disableLlmOrDocChange.includes(promptDetails?.prompt_id) ||
+ 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>
+ );
+}
+
+Header.propTypes = {
+ promptDetails: PropTypes.object.isRequired,
+ promptKey: PropTypes.text,
+ setPromptKey: PropTypes.func.isRequired,
+ progressMsg: PropTypes.object.isRequired,
+ handleRun: PropTypes.func.isRequired,
+ handleChange: PropTypes.func.isRequired,
+ handleDelete: PropTypes.func.isRequired,
+ updateStatus: PropTypes.object.isRequired,
+ updatePlaceHolder: PropTypes.string,
+ isCoverageLoading: PropTypes.bool.isRequired,
+ isEditingTitle: PropTypes.bool.isRequired,
+ setIsEditingTitle: PropTypes.func.isRequired,
+ enableEdit: PropTypes.func.isRequired,
+ expandCard: PropTypes.bool.isRequired,
+ setExpandCard: PropTypes.func.isRequired,
+};
+
+export { Header };
diff --git a/frontend/src/components/custom-tools/prompt-card/PrompDnd.jsx b/frontend/src/components/custom-tools/prompt-card/PrompDnd.jsx
new file mode 100644
index 000000000..d49f82e9d
--- /dev/null
+++ b/frontend/src/components/custom-tools/prompt-card/PrompDnd.jsx
@@ -0,0 +1,68 @@
+import PropTypes from "prop-types";
+import { useDrag, useDrop } from "react-dnd";
+import { useRef } from "react";
+
+import { NotesCard } from "../notes-card/NotesCard";
+import { PromptCard } from "./PromptCard";
+import { promptType } from "../../../helpers/GetStaticData";
+
+function PromptDnd({
+ item,
+ index,
+ handleChange,
+ handleDelete,
+ updateStatus,
+ moveItem,
+}) {
+ const ref = useRef(null);
+
+ const [, drop] = useDrop({
+ accept: "PROMPT_CARD",
+ drop: (draggedItem) => {
+ moveItem(/* Start Index*/ draggedItem?.index, /* Drop Index*/ index);
+ },
+ });
+
+ const [, drag] = useDrag({
+ type: "PROMPT_CARD",
+ item: { index },
+ collect: (monitor) => ({
+ isDragging: monitor.isDragging(),
+ }),
+ });
+ drag(drop(ref));
+
+ return (
+ <div ref={ref}>
+ {item.prompt_type === promptType.prompt && (
+ <PromptCard
+ promptDetails={item}
+ handleChange={handleChange}
+ handleDelete={handleDelete}
+ updateStatus={updateStatus}
+ updatePlaceHolder="Enter Prompt"
+ />
+ )}
+ {item.prompt_type === promptType.notes && (
+ <NotesCard
+ details={item}
+ handleChange={handleChange}
+ handleDelete={handleDelete}
+ updateStatus={updateStatus}
+ updatePlaceHolder="Enter Notes"
+ />
+ )}
+ </div>
+ );
+}
+
+PromptDnd.propTypes = {
+ item: PropTypes.object.isRequired,
+ index: PropTypes.number.isRequired,
+ handleChange: PropTypes.func.isRequired,
+ handleDelete: PropTypes.func.isRequired,
+ updateStatus: PropTypes.object.isRequired,
+ moveItem: PropTypes.func.isRequired,
+};
+
+export { PromptDnd };
diff --git a/frontend/src/components/custom-tools/prompt-card/PromptCard.css b/frontend/src/components/custom-tools/prompt-card/PromptCard.css
index 65509d557..a57d12fd8 100644
--- a/frontend/src/components/custom-tools/prompt-card/PromptCard.css
+++ b/frontend/src/components/custom-tools/prompt-card/PromptCard.css
@@ -12,6 +12,10 @@
padding: 12px;
}
+.prompt-card-div-body {
+ padding: 0px 12px 12px;
+}
+
.prompt-card-bg-col1 {
background-color: #eceff3;
}
@@ -98,3 +102,17 @@
.tag-max-width {
max-width: 150px;
}
+
+.prompt-card-collapse {
+ border-start-start-radius: 0px;
+ border-start-end-radius: 0px;
+}
+
+.prompt-card-collapse .ant-collapse-header {
+ display: none !important;
+ padding: 0 !important;
+}
+
+.prompt-card-collapse .ant-collapse-content-box {
+ padding: 0px !important;
+}
diff --git a/frontend/src/components/custom-tools/prompt-card/PromptCard.jsx b/frontend/src/components/custom-tools/prompt-card/PromptCard.jsx
index 97b8a44ac..2ef4a9645 100644
--- a/frontend/src/components/custom-tools/prompt-card/PromptCard.jsx
+++ b/frontend/src/components/custom-tools/prompt-card/PromptCard.jsx
@@ -1,35 +1,9 @@
-import {
- CheckCircleOutlined,
- DeleteOutlined,
- EditOutlined,
- LeftOutlined,
- LoadingOutlined,
- PlayCircleOutlined,
- RightOutlined,
- SearchOutlined,
- SyncOutlined,
-} from "@ant-design/icons";
-import {
- Button,
- Card,
- Col,
- Divider,
- Row,
- Select,
- Space,
- Spin,
- Tag,
- Tooltip,
- Typography,
-} from "antd";
import PropTypes from "prop-types";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useState } from "react";
import {
defaultTokenUsage,
- displayPromptResult,
generateUUID,
- promptStudioUpdateStatus,
} from "../../../helpers/GetStaticData";
import { useAxiosPrivate } from "../../../hooks/useAxiosPrivate";
import { useExceptionHandler } from "../../../hooks/useExceptionHandler";
@@ -37,19 +11,13 @@ import { useAlertStore } from "../../../store/alert-store";
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 { SpinnerLoader } from "../../widgets/spinner-loader/SpinnerLoader";
-import { EditableText } from "../editable-text/EditableText";
import { OutputForDocModal } from "../output-for-doc-modal/OutputForDocModal";
-import "./PromptCard.css";
-
-import { TokenUsage } from "../token-usage/TokenUsage";
import usePostHogEvents from "../../../hooks/usePostHogEvents";
import useTokenUsage from "../../../hooks/useTokenUsage";
import { useTokenUsageStore } from "../../../store/token-usage-store";
+import { PromptCardItems } from "./PromptCardItems";
+import "./PromptCard.css";
-const EvalBtn = null;
-const EvalMetrics = null;
const EvalModal = null;
const getEvalMetrics = (param1, param2) => {
return [];
@@ -65,12 +33,10 @@ function PromptCard({
const [enforceTypeList, setEnforceTypeList] = useState([]);
const [page, setPage] = useState(0);
const [isRunLoading, setIsRunLoading] = useState(false);
- const [openEval, setOpenEval] = useState(false);
const [promptKey, setPromptKey] = useState("");
const [promptText, setPromptText] = useState("");
- const [isEditingTitle, setIsEditingTitle] = useState(false);
- const [isEditingPrompt, setIsEditingPrompt] = useState(false);
const [selectedLlmProfileId, setSelectedLlmProfileId] = useState(null);
+ const [openEval, setOpenEval] = useState(false);
const [result, setResult] = useState({
promptOutputId: null,
output: "",
@@ -81,7 +47,6 @@ function PromptCard({
const [openOutputForDoc, setOpenOutputForDoc] = useState(false);
const [progressMsg, setProgressMsg] = useState({});
const [docOutputs, setDocOutputs] = useState({});
- const divRef = useRef(null);
const {
getDropdownItems,
llmProfiles,
@@ -91,7 +56,6 @@ function PromptCard({
details,
defaultLlmProfile,
disableLlmOrDocChange,
- indexDocs,
summarizeIndexStatus,
singlePassExtractMode,
isSinglePassExtractLoading,
@@ -105,6 +69,14 @@ function PromptCard({
const { tokenUsage, setTokenUsage } = useTokenUsageStore();
const { getTokenUsage } = useTokenUsage();
+ useEffect(() => {
+ const outputTypeData = getDropdownItems("output_type");
+ const dropdownList1 = Object.keys(outputTypeData).map((item) => {
+ return { value: outputTypeData[item] };
+ });
+ setEnforceTypeList(dropdownList1);
+ }, []);
+
useEffect(() => {
// Find the latest message that matches the criteria
const msg = [...messages]
@@ -128,14 +100,6 @@ function PromptCard({
});
}, [messages]);
- useEffect(() => {
- const outputTypeData = getDropdownItems("output_type");
- const dropdownList1 = Object.keys(outputTypeData).map((item) => {
- return { value: outputTypeData[item] };
- });
- setEnforceTypeList(dropdownList1);
- }, []);
-
useEffect(() => {
setSelectedLlmProfileId(promptDetails?.profile_manager || null);
}, [promptDetails]);
@@ -568,299 +532,33 @@ function PromptCard({
setCoverage(coverageValue);
};
- const enableEdit = (event) => {
- event.stopPropagation();
- setIsEditingTitle(true);
- setIsEditingPrompt(true);
- };
-
return (
<>
- <Card className="prompt-card">
- <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={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={<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">
- <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="prompt-card-action-button"
- onClick={handleRun}
- disabled={
- (updateStatus?.promptId === promptDetails?.prompt_id &&
- updateStatus?.status ===
- promptStudioUpdateStatus.isUpdating) ||
- disableLlmOrDocChange.includes(
- promptDetails?.prompt_id
- ) ||
- 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>
- <>
- <Divider className="prompt-card-divider" />
- <Space
- direction="vertical"
- className={`prompt-card-comp-layout ${
- !(isRunLoading || result?.output || result?.output === 0) &&
- "prompt-card-comp-layout-border"
- }`}
- >
- <div className="prompt-card-llm-profiles">
- <Space direction="horizontal">
- {EvalBtn && !singlePassExtractMode && (
- <EvalBtn
- btnText={promptDetails?.evaluate ? "On" : "Off"}
- promptId={promptDetails.prompt_id}
- setOpenEval={setOpenEval}
- />
- )}
- <Button
- size="small"
- type="link"
- className="display-flex-align-center prompt-card-action-button"
- onClick={() => setOpenOutputForDoc(true)}
- >
- <Space>
- {isCoverageLoading ? (
- <SpinnerLoader size="small" />
- ) : (
- <SearchOutlined className="font-size-12" />
- )}
- <Typography.Link className="font-size-12">
- Coverage: {coverage} of {listOfDocs?.length || 0} docs
- </Typography.Link>
- </Space>
- </Button>
- </Space>
- <Space>
- {!singlePassExtractMode && (
- <TokenUsage
- tokenUsageId={
- promptDetails?.prompt_id + "__" + selectedDoc?.document_id
- }
- />
- )}
- <Select
- className="prompt-card-select-type"
- size="small"
- placeholder="Enforce Type"
- optionFilterProp="children"
- options={enforceTypeList}
- value={promptDetails?.enforce_type || null}
- disabled={
- disableLlmOrDocChange.includes(promptDetails?.prompt_id) ||
- isSinglePassExtractLoading ||
- indexDocs.includes(selectedDoc?.document_id)
- }
- onChange={(value) => handleTypeChange(value)}
- />
- </Space>
- </div>
- <div className="prompt-card-llm-profiles">
- {!singlePassExtractMode && (
- <>
- {llmProfiles?.length > 0 &&
- promptDetails?.profile_manager?.length > 0 &&
- selectedLlmProfileId ? (
- <div>
- {llmProfiles
- .filter(
- (profile) =>
- profile.profile_id === selectedLlmProfileId
- )
- .map((profile, index) => (
- <div key={index}>
- <Tag>{profile.llm}</Tag>
- <Tag>{profile.vector_store}</Tag>
- <Tag>{profile.embedding_model}</Tag>
- <Tag>{profile.x2text}</Tag>
- <Tag>{`${profile.chunk_size}/${profile.chunk_overlap}/${profile.retrieval_strategy}/${profile.similarity_top_k}/${profile.section}`}</Tag>
- </div>
- ))}
- </div>
- ) : (
- <div>
- <Typography.Text className="font-size-12">
- No LLM Profile Selected
- </Typography.Text>
- </div>
- )}
- </>
- )}
- {!singlePassExtractMode && (
- <div className="display-flex-right prompt-card-paginate-div">
- <Button
- type="text"
- size="small"
- className="prompt-card-action-button"
- disabled={
- page <= 1 ||
- disableLlmOrDocChange.includes(
- promptDetails?.prompt_id
- ) ||
- isSinglePassExtractLoading ||
- indexDocs.includes(selectedDoc?.document_id)
- }
- onClick={handlePageLeft}
- >
- <LeftOutlined className="prompt-card-paginate" />
- </Button>
- <Button
- type="text"
- size="small"
- className="prompt-card-action-button"
- disabled={
- page >= llmProfiles?.length ||
- disableLlmOrDocChange.includes(
- promptDetails?.prompt_id
- ) ||
- isSinglePassExtractLoading ||
- indexDocs.includes(selectedDoc?.document_id)
- }
- onClick={handlePageRight}
- >
- <RightOutlined className="prompt-card-paginate" />
- </Button>
- </div>
- )}
- </div>
- {EvalMetrics && <EvalMetrics result={result} />}
- </Space>
- </>
- {(isRunLoading || result?.output || result?.output === 0) && (
- <>
- <Divider className="prompt-card-divider" />
- <div className="prompt-card-result prompt-card-div">
- {isRunLoading ? (
- <Spin indicator={<SpinnerLoader size="small" />} />
- ) : (
- <Typography.Paragraph className="prompt-card-res font-size-12">
- <div>{displayPromptResult(result?.output, true)}</div>
- </Typography.Paragraph>
- )}
- </div>
- </>
- )}
- </Card>
+ <PromptCardItems
+ promptDetails={promptDetails}
+ enforceTypeList={enforceTypeList}
+ isRunLoading={isRunLoading}
+ promptKey={promptKey}
+ setPromptKey={setPromptKey}
+ promptText={promptText}
+ setPromptText={setPromptText}
+ result={result}
+ coverage={coverage}
+ progressMsg={progressMsg}
+ handleRun={handleRun}
+ handleChange={handleChange}
+ handlePageLeft={handlePageLeft}
+ handlePageRight={handlePageRight}
+ handleTypeChange={handleTypeChange}
+ handleDelete={handleDelete}
+ updateStatus={updateStatus}
+ updatePlaceHolder={updatePlaceHolder}
+ isCoverageLoading={isCoverageLoading}
+ setOpenEval={setOpenEval}
+ setOpenOutputForDoc={setOpenOutputForDoc}
+ selectedLlmProfileId={selectedLlmProfileId}
+ page={page}
+ />
{EvalModal && !singlePassExtractMode && (
<EvalModal
open={openEval}
diff --git a/frontend/src/components/custom-tools/prompt-card/PromptCardItems.jsx b/frontend/src/components/custom-tools/prompt-card/PromptCardItems.jsx
new file mode 100644
index 000000000..a4888e67e
--- /dev/null
+++ b/frontend/src/components/custom-tools/prompt-card/PromptCardItems.jsx
@@ -0,0 +1,299 @@
+import PropTypes from "prop-types";
+import { LeftOutlined, RightOutlined, SearchOutlined } from "@ant-design/icons";
+import {
+ Button,
+ Card,
+ Collapse,
+ Divider,
+ Select,
+ Space,
+ Spin,
+ Tag,
+ Typography,
+} from "antd";
+import { useEffect, useRef, useState } from "react";
+
+import { displayPromptResult } from "../../../helpers/GetStaticData";
+import { SpinnerLoader } from "../../widgets/spinner-loader/SpinnerLoader";
+import { EditableText } from "../editable-text/EditableText";
+import { TokenUsage } from "../token-usage/TokenUsage";
+import { useCustomToolStore } from "../../../store/custom-tool-store";
+import { Header } from "./Header";
+
+const EvalBtn = null;
+const EvalMetrics = null;
+
+function PromptCardItems({
+ promptDetails,
+ enforceTypeList,
+ isRunLoading,
+ promptKey,
+ setPromptKey,
+ promptText,
+ setPromptText,
+ result,
+ coverage,
+ progressMsg,
+ handleRun,
+ handleChange,
+ handleDelete,
+ handlePageLeft,
+ handlePageRight,
+ handleTypeChange,
+ updateStatus,
+ updatePlaceHolder,
+ isCoverageLoading,
+ setOpenEval,
+ setOpenOutputForDoc,
+ selectedLlmProfileId,
+ page,
+}) {
+ const [isEditingPrompt, setIsEditingPrompt] = useState(false);
+ const [isEditingTitle, setIsEditingTitle] = useState(false);
+ const [expandCard, setExpandCard] = useState(true);
+ const divRef = useRef(null);
+ const {
+ llmProfiles,
+ selectedDoc,
+ listOfDocs,
+ disableLlmOrDocChange,
+ singlePassExtractMode,
+ isSinglePassExtractLoading,
+ indexDocs,
+ } = useCustomToolStore();
+
+ useEffect(() => {
+ setExpandCard(true);
+ }, [isSinglePassExtractLoading]);
+
+ const enableEdit = (event) => {
+ event.stopPropagation();
+ setExpandCard(true);
+ setIsEditingTitle(true);
+ setIsEditingPrompt(true);
+ };
+
+ return (
+ <Card className="prompt-card">
+ <div className="prompt-card-div prompt-card-bg-col1 prompt-card-rad">
+ <Space direction="vertical" className="width-100" ref={divRef}>
+ <Header
+ promptDetails={promptDetails}
+ promptKey={promptKey}
+ setPromptKey={setPromptKey}
+ progressMsg={progressMsg}
+ handleRun={handleRun}
+ handleChange={handleChange}
+ handleDelete={handleDelete}
+ updateStatus={updateStatus}
+ updatePlaceHolder={updatePlaceHolder}
+ isCoverageLoading={isCoverageLoading}
+ isEditingTitle={isEditingTitle}
+ setIsEditingTitle={setIsEditingTitle}
+ enableEdit={enableEdit}
+ expandCard={expandCard}
+ setExpandCard={setExpandCard}
+ />
+ </Space>
+ </div>
+ <Collapse
+ className="prompt-card-collapse prompt-card-bg-col1"
+ ghost
+ activeKey={expandCard && "1"}
+ >
+ <Collapse.Panel key={"1"} showArrow={false}>
+ <div className="prompt-card-div-body">
+ <EditableText
+ isEditing={isEditingPrompt}
+ setIsEditing={setIsEditingPrompt}
+ text={promptText}
+ setText={setPromptText}
+ promptId={promptDetails?.prompt_id}
+ defaultText={promptDetails.prompt}
+ handleChange={handleChange}
+ isTextarea={true}
+ placeHolder={updatePlaceHolder}
+ />
+ </div>
+ <>
+ <Divider className="prompt-card-divider" />
+ <Space
+ direction="vertical"
+ className={`prompt-card-comp-layout ${
+ !(isRunLoading || result?.output || result?.output === 0) &&
+ "prompt-card-comp-layout-border"
+ }`}
+ >
+ <div className="prompt-card-llm-profiles">
+ <Space direction="horizontal">
+ {EvalBtn && !singlePassExtractMode && (
+ <EvalBtn
+ btnText={promptDetails?.evaluate ? "On" : "Off"}
+ promptId={promptDetails.prompt_id}
+ setOpenEval={setOpenEval}
+ />
+ )}
+ <Button
+ size="small"
+ type="link"
+ className="display-flex-align-center prompt-card-action-button"
+ onClick={() => setOpenOutputForDoc(true)}
+ >
+ <Space>
+ {isCoverageLoading ? (
+ <SpinnerLoader size="small" />
+ ) : (
+ <SearchOutlined className="font-size-12" />
+ )}
+ <Typography.Link className="font-size-12">
+ Coverage: {coverage} of {listOfDocs?.length || 0} docs
+ </Typography.Link>
+ </Space>
+ </Button>
+ </Space>
+ <Space>
+ {!singlePassExtractMode && (
+ <TokenUsage
+ tokenUsageId={
+ promptDetails?.prompt_id +
+ "__" +
+ selectedDoc?.document_id
+ }
+ />
+ )}
+ <Select
+ className="prompt-card-select-type"
+ size="small"
+ placeholder="Enforce Type"
+ optionFilterProp="children"
+ options={enforceTypeList}
+ value={promptDetails?.enforce_type || null}
+ disabled={
+ disableLlmOrDocChange.includes(
+ promptDetails?.prompt_id
+ ) ||
+ isSinglePassExtractLoading ||
+ indexDocs.includes(selectedDoc?.document_id)
+ }
+ onChange={(value) => handleTypeChange(value)}
+ />
+ </Space>
+ </div>
+ <div className="prompt-card-llm-profiles">
+ {!singlePassExtractMode && (
+ <>
+ {llmProfiles?.length > 0 &&
+ promptDetails?.profile_manager?.length > 0 &&
+ selectedLlmProfileId ? (
+ <div>
+ {llmProfiles
+ .filter(
+ (profile) =>
+ profile.profile_id === selectedLlmProfileId
+ )
+ .map((profile, index) => (
+ <div key={profile?.profile_id}>
+ <Tag>{profile.llm}</Tag>
+ <Tag>{profile.vector_store}</Tag>
+ <Tag>{profile.embedding_model}</Tag>
+ <Tag>{profile.x2text}</Tag>
+ <Tag>{`${profile.chunk_size}/${profile.chunk_overlap}/${profile.retrieval_strategy}/${profile.similarity_top_k}/${profile.section}`}</Tag>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <div>
+ <Typography.Text className="font-size-12">
+ No LLM Profile Selected
+ </Typography.Text>
+ </div>
+ )}
+ </>
+ )}
+ {!singlePassExtractMode && (
+ <div className="display-flex-right prompt-card-paginate-div">
+ <Button
+ type="text"
+ size="small"
+ className="prompt-card-action-button"
+ disabled={
+ page <= 1 ||
+ disableLlmOrDocChange.includes(
+ promptDetails?.prompt_id
+ ) ||
+ isSinglePassExtractLoading ||
+ indexDocs.includes(selectedDoc?.document_id)
+ }
+ onClick={handlePageLeft}
+ >
+ <LeftOutlined className="prompt-card-paginate" />
+ </Button>
+ <Button
+ type="text"
+ size="small"
+ className="prompt-card-action-button"
+ disabled={
+ page >= llmProfiles?.length ||
+ disableLlmOrDocChange.includes(
+ promptDetails?.prompt_id
+ ) ||
+ isSinglePassExtractLoading ||
+ indexDocs.includes(selectedDoc?.document_id)
+ }
+ onClick={handlePageRight}
+ >
+ <RightOutlined className="prompt-card-paginate" />
+ </Button>
+ </div>
+ )}
+ </div>
+ {EvalMetrics && <EvalMetrics result={result} />}
+ </Space>
+ </>
+ {(isRunLoading || result?.output || result?.output === 0) && (
+ <>
+ <Divider className="prompt-card-divider" />
+ <div className="prompt-card-result prompt-card-div">
+ {isRunLoading ? (
+ <Spin indicator={<SpinnerLoader size="small" />} />
+ ) : (
+ <Typography.Paragraph className="prompt-card-res font-size-12">
+ <div>{displayPromptResult(result?.output, true)}</div>
+ </Typography.Paragraph>
+ )}
+ </div>
+ </>
+ )}
+ </Collapse.Panel>
+ </Collapse>
+ </Card>
+ );
+}
+
+PromptCardItems.propTypes = {
+ promptDetails: PropTypes.object.isRequired,
+ enforceTypeList: PropTypes.array,
+ isRunLoading: PropTypes.bool,
+ promptKey: PropTypes.text,
+ setPromptKey: PropTypes.func.isRequired,
+ promptText: PropTypes.text,
+ setPromptText: PropTypes.func.isRequired,
+ result: PropTypes.object.isRequired,
+ coverage: PropTypes.number.isRequired,
+ progressMsg: PropTypes.object.isRequired,
+ handleRun: PropTypes.func.isRequired,
+ handleChange: PropTypes.func.isRequired,
+ handlePageLeft: PropTypes.func.isRequired,
+ handlePageRight: PropTypes.func.isRequired,
+ handleTypeChange: PropTypes.func.isRequired,
+ handleDelete: PropTypes.func.isRequired,
+ updateStatus: PropTypes.object.isRequired,
+ updatePlaceHolder: PropTypes.string,
+ isCoverageLoading: PropTypes.bool.isRequired,
+ setOpenEval: PropTypes.func.isRequired,
+ setOpenOutputForDoc: PropTypes.func.isRequired,
+ selectedLlmProfileId: PropTypes.string,
+ page: PropTypes.number.isRequired,
+};
+
+export { PromptCardItems };