Run prettier. Wip

This commit is contained in:
Ian Arawjo 2024-03-02 10:16:30 -05:00
parent 6f231a5f79
commit a26f6d068c
11 changed files with 98 additions and 50 deletions

View File

@ -1,4 +1,10 @@
import React, { useState, useEffect, useCallback, useRef, KeyboardEventHandler } from "react";
import React, {
useState,
useEffect,
useCallback,
useRef,
KeyboardEventHandler,
} from "react";
import { Skeleton, Text } from "@mantine/core";
import useStore from "./store";
import NodeLabel from "./NodeLabelComponent";
@ -27,9 +33,9 @@ const stripWrappingQuotes = (str: string) => {
interface ItemsNodeProps {
data: {
title?: string,
text?: string,
fields?: string[],
title?: string;
text?: string;
fields?: string[];
};
id: string;
}
@ -80,12 +86,15 @@ const ItemsNode: React.FC<ItemsNodeProps> = ({ data, id }) => {
[id, pingOutputNodes, setDataPropsForNode],
);
const handleKeyDown: KeyboardEventHandler<HTMLTextAreaElement> = useCallback((event: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (event.key === "Enter" && data.text && data.text.trim().length > 0) {
setIsEditing(false);
setCsvInput(null);
}
}, []);
const handleKeyDown: KeyboardEventHandler<HTMLTextAreaElement> = useCallback(
(event: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (event.key === "Enter" && data.text && data.text.trim().length > 0) {
setIsEditing(false);
setCsvInput(null);
}
},
[],
);
// handling Div Click
const handleDivOnClick = useCallback(() => {

View File

@ -33,7 +33,7 @@ export interface NodeLabelProps {
interface DeleteConfirmProps {
title: string;
message: string;
onConfirm: undefined | (() => void)
onConfirm: undefined | (() => void);
}
export const NodeLabel: React.FC<NodeLabelProps> = ({
@ -59,17 +59,20 @@ export const NodeLabel: React.FC<NodeLabelProps> = ({
// For 'delete node' confirmation popup
const deleteConfirmModal = useRef<AreYouSureModalHandles>(null);
const [deleteConfirmProps, setDeleteConfirmProps] = useState<DeleteConfirmProps>({
title: "Delete node",
message: "Are you sure?",
onConfirm: undefined,
});
const [deleteConfirmProps, setDeleteConfirmProps] =
useState<DeleteConfirmProps>({
title: "Delete node",
message: "Are you sure?",
onConfirm: undefined,
});
const stopButton = useMemo(
() => (
<button
className="AmitSahoo45-button-3 nodrag"
style={{ padding: "0px 10px 0px 9px" }}
onClick={() => {if (handleStopClick) handleStopClick(nodeId);}}
onClick={() => {
if (handleStopClick) handleStopClick(nodeId);
}}
>
&#9724;
</button>

View File

@ -6,7 +6,6 @@ import {
Dict,
StandardizedLLMResponse,
EvaluationScore,
PromptVarType,
} from "./backend/typing";
// Lazy load the response toolbars
@ -68,7 +67,7 @@ export interface ResponseGroupProps {
responseBoxesWrapperClass: string;
displayStyle: string;
defaultState: boolean;
};
}
export const ResponseGroup: React.FC<ResponseGroupProps> = ({
header,

View File

@ -44,7 +44,6 @@ export const extractBracketedSubstrings = (text: string) => {
return capture_groups;
};
export interface TemplateHooksProps {
vars: string[];
nodeId: string;
@ -137,10 +136,12 @@ export default function TemplateHooks({
if (
!(
e.target !== nodeId ||
(typeof e.targetHandle === "string" && (vars.includes(e.targetHandle) ||
(ignoreHandles && Array.isArray(ignoreHandles) &&
ignoreHandles.includes(e.targetHandle)))
))
(typeof e.targetHandle === "string" &&
(vars.includes(e.targetHandle) ||
(ignoreHandles &&
Array.isArray(ignoreHandles) &&
ignoreHandles.includes(e.targetHandle))))
)
)
deleted_edges.push(e);
});

View File

@ -33,12 +33,12 @@ const delButtonId = "del-";
const visibleButtonId = "eye-";
interface TextFieldsNodeData {
vars?: string[],
title?: string,
text?: string,
fields?: Dict<string>,
fields_visibility?: Dict<boolean>,
refresh?: boolean,
vars?: string[];
title?: string;
text?: string;
fields?: Dict<string>;
fields_visibility?: Dict<boolean>;
refresh?: boolean;
}
interface TextFieldsNodeProps {
data: TextFieldsNodeData;
@ -53,7 +53,9 @@ const TextFieldsNode: React.FC<TextFieldsNodeProps> = ({ data, id }) => {
const aiFeaturesProvider = useStore((state) => state.aiFeaturesProvider);
const flags = useStore((state) => state.flags);
const [textfieldsValues, setTextfieldsValues] = useState<Dict<string>>(data.fields ?? {});
const [textfieldsValues, setTextfieldsValues] = useState<Dict<string>>(
data.fields ?? {},
);
const [fieldVisibility, setFieldVisibility] = useState<Dict<boolean>>(
data.fields_visibility || {},
);
@ -102,7 +104,9 @@ const TextFieldsNode: React.FC<TextFieldsNodeProps> = ({ data, id }) => {
// Update the data for this text field's id.
const new_fields = { ...textfieldsValues };
const new_vis = { ...fieldVisibility };
const item_id = (event.target as HTMLButtonElement).id.substring(delButtonId.length);
const item_id = (event.target as HTMLButtonElement).id.substring(
delButtonId.length,
);
delete new_fields[item_id];
delete new_vis[item_id];
// if the new_data is empty, initialize it with one empty field
@ -171,7 +175,9 @@ const TextFieldsNode: React.FC<TextFieldsNodeProps> = ({ data, id }) => {
let all_found_vars = new Set<string>();
const new_field_ids = Object.keys(new_data.fields ?? {});
new_field_ids.forEach((fid: string) => {
const found_vars = extractBracketedSubstrings((new_data.fields as Dict<string>)[fid]);
const found_vars = extractBracketedSubstrings(
(new_data.fields as Dict<string>)[fid],
);
if (found_vars && found_vars.length > 0) {
all_found_vars = union(all_found_vars, new Set(found_vars));
}
@ -263,7 +269,11 @@ const TextFieldsNode: React.FC<TextFieldsNodeProps> = ({ data, id }) => {
}, [refresh]);
// Handle keydown events for the text fields
const handleTextAreaKeyDown = (event: React.KeyboardEvent<HTMLTextAreaElement>, placeholder: string, fieldIdx: string) => {
const handleTextAreaKeyDown = (
event: React.KeyboardEvent<HTMLTextAreaElement>,
placeholder: string,
fieldIdx: string,
) => {
// Insert the AI suggested text if:
// (1) the user presses the Tab key
// (2) the user has not typed anything in the textarea
@ -438,7 +448,12 @@ const TextFieldsNode: React.FC<TextFieldsNodeProps> = ({ data, id }) => {
className="grouped-handle"
style={{ top: "50%" }}
/>
<TemplateHooks vars={templateVars} nodeId={id} startY={hooksY} position={Position.Left} />
<TemplateHooks
vars={templateVars}
nodeId={id}
startY={hooksY}
position={Position.Left}
/>
<div className="add-text-field-btn">
<button onClick={handleAddField}>+</button>
</div>

View File

@ -243,7 +243,8 @@ function filterVarsByLLM(vars: PromptVarType, llm_key: string): Dict {
typeof v === "string" ||
v?.llm === undefined ||
typeof v.llm === "string" ||
v.llm.key === llm_key);
v.llm.key === llm_key,
);
});
return _vars;
}

View File

@ -87,7 +87,8 @@ export class PromptPipeline {
} = result;
// Check for selective failure
if (!query && response instanceof LLMResponseError) return response; // yield the LLMResponseException
if (!query && response instanceof LLMResponseError)
return response; // yield the LLMResponseException
else if (response === undefined) return new LLMResponseError("Unknown");
// Each prompt has a history of what was filled in from its base template.
@ -128,7 +129,7 @@ export class PromptPipeline {
if (past_resp_obj_cache_idx !== undefined && past_resp_obj_cache_idx > -1)
cached_responses[resp_obj.prompt][past_resp_obj_cache_idx] = resp_obj;
else cached_responses[resp_obj.prompt].push(resp_obj);
this._cache_responses(cached_responses);
// console.log(` - collected response from ${llm} for prompt: ${resp_obj['prompt']}`);

View File

@ -129,7 +129,7 @@ export interface RawLLMResponseObject extends BaseLLMResponseObject {
tokens?: Dict<number>;
}
export type EvaluationScore = (boolean | number | string);
export type EvaluationScore = boolean | number | string;
export type EvaluationResults = {
items: EvaluationScore[];
dtype:
@ -154,7 +154,9 @@ export interface StandardizedLLMResponse extends BaseLLMResponseObject {
tokens?: Dict<number>;
}
export type LLMResponsesByVarDict = Dict<(BaseLLMResponseObject | StandardizedLLMResponse)[]>;
export type LLMResponsesByVarDict = Dict<
(BaseLLMResponseObject | StandardizedLLMResponse)[]
>;
/** A standard async function interface for calling an LLM. */
export interface LLMAPICall {

View File

@ -1681,13 +1681,15 @@ export const getLLMsInPulledInputData = (pulled_data: Dict) => {
return Object.values(found_llms);
};
export const stripLLMDetailsFromResponses = (resps: (StandardizedLLMResponse | BaseLLMResponseObject)[]) =>
export const stripLLMDetailsFromResponses = (
resps: (StandardizedLLMResponse | BaseLLMResponseObject)[],
) =>
resps.map((r) => ({
...r,
llm: typeof r?.llm === "string" ? r?.llm : r?.llm?.name ?? "undefined",
}));
// NOTE: The typing is purposefully general since we are trying to cast to an expected format.
// NOTE: The typing is purposefully general since we are trying to cast to an expected format.
export const toStandardResponseFormat = (r: Dict) => {
const resp_obj: StandardizedLLMResponse = {
vars: r?.fill_history ?? {},
@ -1718,7 +1720,14 @@ export const tagMetadataWithLLM = (input_data: LLMResponsesByVarDict) => {
const new_data: LLMResponsesByVarDict = {};
Object.entries(input_data).forEach(([varname, resp_objs]) => {
new_data[varname] = resp_objs.map((r) => {
if (!r || typeof r === "string" || !r?.llm || typeof r.llm === "string" || !r.llm.key) return r;
if (
!r ||
typeof r === "string" ||
!r?.llm ||
typeof r.llm === "string" ||
!r.llm.key
)
return r;
const r_copy = JSON.parse(JSON.stringify(r));
r_copy.metavars.__LLM_key = r.llm.key;
return r_copy;
@ -1746,7 +1755,10 @@ export const removeLLMTagFromMetadata = (metavars: Dict) => {
return mcopy;
};
export const truncStr = (s: string | undefined, maxLen: number): string | undefined => {
export const truncStr = (
s: string | undefined,
maxLen: number,
): string | undefined => {
if (s === undefined) return s;
if (s.length > maxLen)
// Cut the name short if it's long
@ -1754,7 +1766,10 @@ export const truncStr = (s: string | undefined, maxLen: number): string | undefi
else return s;
};
export const groupResponsesBy = (responses: StandardizedLLMResponse[], keyFunc: ((item: StandardizedLLMResponse) => string | null | undefined)) => {
export const groupResponsesBy = (
responses: StandardizedLLMResponse[],
keyFunc: (item: StandardizedLLMResponse) => string | null | undefined,
) => {
const responses_by_key: Dict = {};
const unspecified_group: Dict[] = [];
responses.forEach((item) => {
@ -1821,7 +1836,7 @@ export function sampleRandomElements(arr: any[], num_sample: number): any[] {
export const getVarsAndMetavars = (input_data: Dict) => {
// Find all vars and metavars in the input data (if any):
// NOTE: The typing is purposefully general for some backwards compatibility concenrs.
// NOTE: The typing is purposefully general for some backwards compatibility concenrs.
const varnames = new Set();
const metavars = new Set();
@ -1913,12 +1928,14 @@ export function repairCachedResponses(
/**
* Generates a function that can be called to debounce another function,
* inside a React component. Note that it requires passing (and capturing) a React ref using useRef.
* inside a React component. Note that it requires passing (and capturing) a React ref using useRef.
* The ref is used so that when the function is called multiple times; it will 'debounce' --cancel any pending call.
* @param ref An empty React ref from useRef
* @returns A debounce function of signature (func: Func, delay: number), taking an arbitrary function and delay in milliseconds
*/
export const genDebounceFunc = (ref: React.MutableRefObject<null | NodeJS.Timeout>) => {
export const genDebounceFunc = (
ref: React.MutableRefObject<null | NodeJS.Timeout>,
) => {
return (func: Func, delay: number) => {
return (...args: any[]) => {
if (ref?.current) {

View File

@ -16,7 +16,7 @@ import {
APP_IS_RUNNING_LOCALLY,
} from "./backend/utils";
import { DuplicateVariableNameError } from "./backend/errors";
import { Dict, LLMSpec, TemplateVarInfo, Dict } from "./backend/typing";
import { Dict, LLMSpec, TemplateVarInfo } from "./backend/typing";
// Initial project settings
const initialAPIKeys = {};

View File

@ -6,7 +6,7 @@
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": false,
"strict": true,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": true,
"module": "esnext",