diff --git a/src/frontend/src/modals/apiModal/codeTabs/code-tabs.tsx b/src/frontend/src/modals/apiModal/codeTabs/code-tabs.tsx index a21310374..a0a491883 100644 --- a/src/frontend/src/modals/apiModal/codeTabs/code-tabs.tsx +++ b/src/frontend/src/modals/apiModal/codeTabs/code-tabs.tsx @@ -14,6 +14,7 @@ import { } from "react-syntax-highlighter/dist/cjs/styles/prism"; import { useShallow } from "zustand/react/shallow"; import { useDarkStore } from "../../../stores/darkStore"; +import { formatPayloadTweaks } from "../utils/filter-tweaks"; import { getNewCurlCode } from "../utils/get-curl-code"; import { getNewJsApiCode } from "../utils/get-js-api-code"; import { getNewPythonApiCode } from "../utils/get-python-api-code"; @@ -41,18 +42,30 @@ export default function APITabsComponent() { } const streaming = hasStreaming(nodes); const tweaks = useTweaksStore((state) => state.tweaks); + const activeTweaks = Object.values(tweaks).some( + (tweak) => Object.keys(tweak).length > 0, + ); + + const includeTopLevelInputValue = formatPayloadTweaks(tweaks); + const processedPayload: any = { + output_type: hasChatOutput ? "chat" : "text", + input_type: hasChatInput ? "chat" : "text", + }; + + if (includeTopLevelInputValue) { + processedPayload.input_value = input_value; + } + + if (activeTweaks && tweaks && Object.keys(tweaks).length > 0) { + processedPayload.tweaks = tweaks; + } + const codeOptions = { endpointName: endpointName || "", streaming: streaming, flowId: flowId || "", isAuthenticated: !autologin || false, - input_value: input_value, - input_type: hasChatInput ? "chat" : "text", - output_type: hasChatOutput ? "chat" : "text", - tweaksObject: tweaks, - activeTweaks: Object.values(tweaks).some( - (tweak) => Object.keys(tweak).length > 0, - ), + processedPayload: processedPayload, }; const tabsList: tabsArrayType = [ { diff --git a/src/frontend/src/modals/apiModal/utils/filter-tweaks.ts b/src/frontend/src/modals/apiModal/utils/filter-tweaks.ts new file mode 100644 index 000000000..300927b7b --- /dev/null +++ b/src/frontend/src/modals/apiModal/utils/filter-tweaks.ts @@ -0,0 +1,24 @@ +import { INPUT_TYPES } from "@/constants/constants"; + +export function formatPayloadTweaks(tweaksObject: any): boolean { + if (!tweaksObject || typeof tweaksObject !== "object") { + return true; + } + + const InputTypes = [...Array.from(INPUT_TYPES), "TextInput"]; + + const hasInputValueInTweaks = Object.keys(tweaksObject).some((key) => { + const isInputNode = Array.from(InputTypes).some((inputType) => + key.startsWith(inputType), + ); + + return ( + isInputNode && + tweaksObject[key] && + typeof tweaksObject[key] === "object" && + "input_value" in tweaksObject[key] + ); + }); + + return !hasInputValueInTweaks; +} diff --git a/src/frontend/src/modals/apiModal/utils/get-curl-code.tsx b/src/frontend/src/modals/apiModal/utils/get-curl-code.tsx index 0d93739de..5cc6dda3b 100644 --- a/src/frontend/src/modals/apiModal/utils/get-curl-code.tsx +++ b/src/frontend/src/modals/apiModal/utils/get-curl-code.tsx @@ -11,8 +11,6 @@ import { GetCodeType } from "@/types/tweaks"; * @param {string} options.endpointName - The name of the webhook endpoint. * @returns {string} The cURL command. */ - -// KEEP THIS FOR LFOSS export function getCurlWebhookCode({ flowId, isAuth, @@ -43,53 +41,39 @@ export function getCurlWebhookCode({ export function getNewCurlCode({ flowId, isAuthenticated, - input_value, - input_type, - output_type, - tweaksObject, - activeTweaks, endpointName, + processedPayload, }: { flowId: string; isAuthenticated: boolean; - input_value: string; - input_type: string; - output_type: string; - tweaksObject: any; - activeTweaks: boolean; endpointName: string; + processedPayload: any; }): string { const { protocol, host } = customGetHostProtocol(); const apiUrl = `${protocol}//${host}/api/v1/run/${endpointName || flowId}`; - const tweaksString = - tweaksObject && activeTweaks ? JSON.stringify(tweaksObject, null, 2) : "{}"; - - // Construct the payload - const payload = { - input_value: input_value, - output_type: output_type, - input_type: input_type, - ...(activeTweaks && tweaksObject - ? { tweaks: JSON.parse(tweaksString) } - : {}), - }; + const formattedJsonPayload = JSON.stringify(processedPayload, null, 2) + .split("\n") + .map((line, index) => (index === 0 ? line : " " + line)) + .join("\n\t\t"); return `${ isAuthenticated ? `# Get API key from environment variable if [ -z "$LANGFLOW_API_KEY" ]; then - echo "Error: LANGFLOW_API_KEY environment variable not found. Please set your API key in the environment variables." + echo "Error: LANGFLOW_API_KEY environment variable not found. Please set your API key in the environment variables." + exit 1 fi + ` : "" }curl --request POST \\ - --url '${apiUrl}?stream=false' \\ - --header 'Content-Type: application/json' \\${ - isAuthenticated - ? ` - --header "x-api-key: $LANGFLOW_API_KEY" \\` - : "" - } - --data '${JSON.stringify(payload, null, 2)}'`; + --url '${apiUrl}?stream=false' \\ + --header 'Content-Type: application/json' \\${ + isAuthenticated + ? ` + --header "x-api-key: $LANGFLOW_API_KEY" \\` + : "" + } + --data '${formattedJsonPayload}'`; } diff --git a/src/frontend/src/modals/apiModal/utils/get-js-api-code.tsx b/src/frontend/src/modals/apiModal/utils/get-js-api-code.tsx index f755dc893..110bed58d 100644 --- a/src/frontend/src/modals/apiModal/utils/get-js-api-code.tsx +++ b/src/frontend/src/modals/apiModal/utils/get-js-api-code.tsx @@ -6,37 +6,31 @@ import { customGetHostProtocol } from "@/customization/utils/custom-get-host-pro * @param {Object} params - The parameters for generating the API code * @param {string} params.flowId - The ID of the flow to run * @param {boolean} params.isAuthenticated - Whether authentication is required - * @param {string} params.input_value - The input value to send to the flow - * @param {string} params.input_type - The type of input (e.g. "text", "chat") - * @param {string} params.output_type - The type of output (e.g. "text", "chat") - * @param {Object} params.tweaksObject - Optional tweaks to customize flow behavior - * @param {boolean} params.activeTweaks - Whether tweaks should be included + * @param {string} params.endpointName - The endpoint name for the flow + * @param {Object} params.processedPayload - The pre-processed payload object * @returns {string} Generated JavaScript code as a string */ export function getNewJsApiCode({ flowId, isAuthenticated, - input_value, - input_type, - output_type, - tweaksObject, - activeTweaks, endpointName, + processedPayload, }: { flowId: string; isAuthenticated: boolean; - input_value: string; - input_type: string; - output_type: string; - tweaksObject: any; - activeTweaks: boolean; endpointName: string; + processedPayload: any; }): string { const { protocol, host } = customGetHostProtocol(); const apiUrl = `${protocol}//${host}/api/v1/run/${endpointName || flowId}`; - const tweaksString = - tweaksObject && activeTweaks ? JSON.stringify(tweaksObject, null, 2) : "{}"; + // Add session_id to payload + const payloadWithSession = { + ...processedPayload, + session_id: "user_1", // Optional: Use session tracking if needed + }; + + const payloadString = JSON.stringify(payloadWithSession, null, 4); return `${ isAuthenticated @@ -44,20 +38,10 @@ export function getNewJsApiCode({ if (!process.env.LANGFLOW_API_KEY) { throw new Error('LANGFLOW_API_KEY environment variable not found. Please set your API key in the environment variables.'); } + ` : "" - }const payload = { - "input_value": "${input_value}", - "output_type": "${output_type}", - "input_type": "${input_type}", - // Optional: Use session tracking if needed - "session_id": "user_1"${ - activeTweaks && tweaksObject - ? `, - "tweaks": ${tweaksString}` - : "" - } -}; + }const payload = ${payloadString}; const options = { method: 'POST', @@ -70,6 +54,5 @@ const options = { fetch('${apiUrl}', options) .then(response => response.json()) .then(response => console.log(response)) - .catch(err => console.error(err)); - `; + .catch(err => console.error(err));`; } diff --git a/src/frontend/src/modals/apiModal/utils/get-python-api-code.tsx b/src/frontend/src/modals/apiModal/utils/get-python-api-code.tsx index 46d3057d1..4580b0f09 100644 --- a/src/frontend/src/modals/apiModal/utils/get-python-api-code.tsx +++ b/src/frontend/src/modals/apiModal/utils/get-python-api-code.tsx @@ -3,56 +3,39 @@ import { customGetHostProtocol } from "@/customization/utils/custom-get-host-pro export function getNewPythonApiCode({ flowId, isAuthenticated, - input_value, - input_type, - output_type, - tweaksObject, - activeTweaks, endpointName, + processedPayload, }: { flowId: string; isAuthenticated: boolean; - input_value: string; - input_type: string; - output_type: string; - tweaksObject: any; - activeTweaks: boolean; endpointName: string; + processedPayload: any; }): string { const { protocol, host } = customGetHostProtocol(); const apiUrl = `${protocol}//${host}/api/v1/run/${endpointName || flowId}`; - const tweaksString = - tweaksObject && activeTweaks - ? JSON.stringify(tweaksObject, null, 4) - .replace(/true/g, "True") - .replace(/false/g, "False") - .replace(/null/g, "None") - : "{}"; + const payloadString = JSON.stringify(processedPayload, null, 4) + .replace(/true/g, "True") + .replace(/false/g, "False") + .replace(/null/g, "None"); return `import requests ${ isAuthenticated ? `import os + # API Configuration try: api_key = os.environ["LANGFLOW_API_KEY"] except KeyError: - raise ValueError("LANGFLOW_API_KEY environment variable not found. Please set your API key in the environment variables.")\n` + raise ValueError("LANGFLOW_API_KEY environment variable not found. Please set your API key in the environment variables.") +` : "" -}url = "${apiUrl}" # The complete API endpoint URL for this flow +} +url = "${apiUrl}" # The complete API endpoint URL for this flow # Request payload configuration -payload = { - "input_value": "${input_value}", # The input value to be processed by the flow - "output_type": "${output_type}", # Specifies the expected output format - "input_type": "${input_type}" # Specifies the input format${ - activeTweaks && tweaksObject - ? `, - "tweaks": ${tweaksString} # Custom tweaks to modify flow behavior` - : "" - } -} +payload = ${payloadString} # Request headers headers = { @@ -70,6 +53,5 @@ try: except requests.exceptions.RequestException as e: print(f"Error making API request: {e}") except ValueError as e: - print(f"Error parsing response: {e}") - `; + print(f"Error parsing response: {e}")`; }