Merge branch 'zustand/io/migration' of github.com:logspace-ai/langflow into zustand/io/migration

This commit is contained in:
cristhianzl 2024-01-31 17:44:57 -03:00
commit b42c34cdb1
7 changed files with 33 additions and 41 deletions

View file

@ -171,19 +171,23 @@ async def check_langflow_version(component: StoreComponentCreate):
) )
def format_elapsed_time(elapsed_time) -> str: def format_elapsed_time(elapsed_time: float) -> str:
# Format elapsed time to human readable format coming from """Format elapsed time to a human-readable format coming from perf_counter().
# perf_counter()
# If the elapsed time is less than 1 second, return ms - Less than 1 second: returns milliseconds
# If the elapsed time is less than 1 minute, return seconds rounded to 2 decimals - Less than 1 minute: returns seconds rounded to 2 decimals
time_str = "" - 1 minute or more: returns minutes and seconds
"""
if elapsed_time < 1: if elapsed_time < 1:
elapsed_time = int(round(elapsed_time * 1000)) milliseconds = int(round(elapsed_time * 1000))
time_str = f"{elapsed_time} ms" return f"{milliseconds} ms"
elif elapsed_time < 60: elif elapsed_time < 60:
elapsed_time = round(elapsed_time, 2) seconds = round(elapsed_time, 2)
time_str = f"{elapsed_time} seconds" unit = "second" if seconds == 1 else "seconds"
return f"{seconds} {unit}"
else: else:
elapsed_time = round(elapsed_time / 60, 2) minutes = int(elapsed_time // 60)
time_str = f"{elapsed_time} minutes" seconds = round(elapsed_time % 60, 2)
return time_str minutes_unit = "minute" if minutes == 1 else "minutes"
seconds_unit = "second" if seconds == 1 else "seconds"
return f"{minutes} {minutes_unit}, {seconds} {seconds_unit}"

View file

@ -287,6 +287,8 @@ async def build_vertex(
cache = chat_service.get_cache(flow_id) cache = chat_service.get_cache(flow_id)
graph = cache.get("result") graph = cache.get("result")
result_dict = {} result_dict = {}
duration = ""
start_time = time.perf_counter()
if tweaks: if tweaks:
graph = process_tweaks_on_graph(graph, tweaks) graph = process_tweaks_on_graph(graph, tweaks)
if not isinstance(graph, Graph): if not isinstance(graph, Graph):
@ -303,7 +305,8 @@ async def build_vertex(
# to the frontend # to the frontend
vertex.set_artifacts() vertex.set_artifacts()
artifacts = vertex.artifacts artifacts = vertex.artifacts
result_dict = ResultDict(results=result_dict, artifacts=artifacts) duration = format_elapsed_time(time.perf_counter() - start_time)
result_dict = ResultDict(results=result_dict, artifacts=artifacts, duration=duration)
except Exception as exc: except Exception as exc:
params = str(exc) params = str(exc)
valid = False valid = False

View file

@ -221,9 +221,11 @@ class VerticesOrderResponse(BaseModel):
class ResultDict(BaseModel): class ResultDict(BaseModel):
"""Outputs of the vertex build process."""
results: Optional[Any] = Field(default_factory=dict) results: Optional[Any] = Field(default_factory=dict)
artifacts: Optional[Any] = Field(default_factory=dict) artifacts: Optional[Any] = Field(default_factory=dict)
"""Outputs of the vertex build process.""" duration: Optional[float] = None
class VertexBuildResponse(BaseModel): class VertexBuildResponse(BaseModel):

View file

@ -877,7 +877,7 @@ export async function getFlowPool({
}: { }: {
flowId: string; flowId: string;
nodeId?: string; nodeId?: string;
}): Promise<AxiosResponse<FlowPoolType>> { }): Promise<AxiosResponse<{ vertex_builds: FlowPoolType }>> {
const config = {}; const config = {};
config["params"] = { flow_id: flowId }; config["params"] = { flow_id: flowId };
if (nodeId) { if (nodeId) {

View file

@ -56,7 +56,6 @@ const EditNodeModal = forwardRef(
) => { ) => {
const [myData, setMyData] = useState(data); const [myData, setMyData] = useState(data);
const setPending = useFlowStore((state) => state.setPending);
const edges = useFlowStore((state) => state.edges); const edges = useFlowStore((state) => state.edges);
const setNode = useFlowStore((state) => state.setNode); const setNode = useFlowStore((state) => state.setNode);
@ -546,7 +545,6 @@ const EditNodeModal = forwardRef(
node: myData.node, node: myData.node,
}, },
})); }));
setPending(true);
setOpen(false); setOpen(false);
}} }}
type="submit" type="submit"

View file

@ -69,7 +69,6 @@ export default function Page({
const takeSnapshot = useFlowsManagerStore((state) => state.takeSnapshot); const takeSnapshot = useFlowsManagerStore((state) => state.takeSnapshot);
const paste = useFlowStore((state) => state.paste); const paste = useFlowStore((state) => state.paste);
const resetFlow = useFlowStore((state) => state.resetFlow); const resetFlow = useFlowStore((state) => state.resetFlow);
const setFlowPool = useFlowStore((state) => state.setFlowPool);
const lastCopiedSelection = useFlowStore( const lastCopiedSelection = useFlowStore(
(state) => state.lastCopiedSelection (state) => state.lastCopiedSelection
); );
@ -80,7 +79,6 @@ export default function Page({
const currentFlowId = useFlowsManagerStore((state) => state.currentFlowId); const currentFlowId = useFlowsManagerStore((state) => state.currentFlowId);
const setErrorData = useAlertStore((state) => state.setErrorData); const setErrorData = useAlertStore((state) => state.setErrorData);
const [selectionMenuVisible, setSelectionMenuVisible] = useState(false); const [selectionMenuVisible, setSelectionMenuVisible] = useState(false);
const [loading, setLoading] = useState(true);
const edgeUpdateSuccessful = useRef(true); const edgeUpdateSuccessful = useRef(true);
const position = useRef({ x: 0, y: 0 }); const position = useRef({ x: 0, y: 0 });
@ -164,12 +162,8 @@ export default function Page({
edges: flow?.data?.edges ?? [], edges: flow?.data?.edges ?? [],
viewport: flow?.data?.viewport ?? { zoom: 1, x: 0, y: 0 }, viewport: flow?.data?.viewport ?? { zoom: 1, x: 0, y: 0 },
}); });
// getFlowPool({flowId: currentFlowId}).then((flowPool) => {
// setFlowPool(flowPool.data)
// setLoading(false)
// })
} }
}, [currentFlowId, reactFlowInstance, setLoading, setFlowPool]); }, [currentFlowId, reactFlowInstance]);
useEffect(() => { useEffect(() => {
return () => { return () => {

View file

@ -11,7 +11,7 @@ import {
} from "reactflow"; } from "reactflow";
import { create } from "zustand"; import { create } from "zustand";
import { INPUT_TYPES, OUTPUT_TYPES } from "../constants/constants"; import { INPUT_TYPES, OUTPUT_TYPES } from "../constants/constants";
import { updateFlowInDatabase } from "../controllers/API"; import { getFlowPool, updateFlowInDatabase } from "../controllers/API";
import { import {
NodeDataType, NodeDataType,
NodeType, NodeType,
@ -38,7 +38,7 @@ const useFlowStore = create<FlowStoreType>((set, get) => ({
nodes: [], nodes: [],
edges: [], edges: [],
isBuilding: false, isBuilding: false,
isPending: false, isPending: true,
hasIO: false, hasIO: false,
reactFlowInstance: null, reactFlowInstance: null,
lastCopiedSelection: null, lastCopiedSelection: null,
@ -49,19 +49,12 @@ const useFlowStore = create<FlowStoreType>((set, get) => ({
set({ flowPool }); set({ flowPool });
}, },
addDataToFlowPool: (data: any, nodeId: string) => { addDataToFlowPool: (data: any, nodeId: string) => {
const currentFlow = useFlowsManagerStore.getState().currentFlow;
let newFlowPool = cloneDeep({ ...get().flowPool }); let newFlowPool = cloneDeep({ ...get().flowPool });
if (!newFlowPool[nodeId]) newFlowPool[nodeId] = [data]; if (!newFlowPool[nodeId]) newFlowPool[nodeId] = [data];
else { else {
newFlowPool[nodeId].push(data); newFlowPool[nodeId].push(data);
} }
get().setFlowPool(newFlowPool); get().setFlowPool(newFlowPool);
if (currentFlow) {
window.sessionStorage.setItem(
`${currentFlow!.id}`,
JSON.stringify(newFlowPool)
);
}
}, },
CleanFlowPool: () => { CleanFlowPool: () => {
get().setFlowPool({}); get().setFlowPool({});
@ -71,12 +64,6 @@ const useFlowStore = create<FlowStoreType>((set, get) => ({
}, },
resetFlow: ({ nodes, edges, viewport }) => { resetFlow: ({ nodes, edges, viewport }) => {
const currentFlow = useFlowsManagerStore.getState().currentFlow; const currentFlow = useFlowsManagerStore.getState().currentFlow;
let flowPool = {};
if (currentFlow) {
flowPool = JSON.parse(
window.sessionStorage.getItem(`${currentFlow!.id}`) ?? "{}"
);
}
let newEdges = cleanEdges(nodes, edges); let newEdges = cleanEdges(nodes, edges);
const { inputs, outputs } = getInputsAndOutputs(nodes); const { inputs, outputs } = getInputsAndOutputs(nodes);
set({ set({
@ -86,9 +73,13 @@ const useFlowStore = create<FlowStoreType>((set, get) => ({
inputs, inputs,
outputs, outputs,
hasIO: inputs.length > 0 || outputs.length > 0, hasIO: inputs.length > 0 || outputs.length > 0,
flowPool,
}); });
get().reactFlowInstance!.setViewport(viewport); get().reactFlowInstance!.setViewport(viewport);
if (currentFlow) {
getFlowPool({ flowId: currentFlow.id }).then((flowPool) => {
set({ flowPool: flowPool.data.vertex_builds });
});
}
}, },
setIsBuilding: (isBuilding) => { setIsBuilding: (isBuilding) => {
set({ isBuilding }); set({ isBuilding });