diff --git a/src/app/components/ChatFileCard.js b/src/app/components/ChatFileCard.js index 6244342..b6e1c69 100644 --- a/src/app/components/ChatFileCard.js +++ b/src/app/components/ChatFileCard.js @@ -3,14 +3,15 @@ import EndpointSection from "./EndpointSection"; import ResponseSection from "./ResponseSection"; import CodeSection from "./CodeSection"; -const TEXT_ACCEPTED_FILE_TYPES = ".txt,.pdf,.doc,.docx,.rtf,.csv,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/rtf,text/plain,text/csv"; +const TEXT_ACCEPTED_FILE_TYPES = + ".txt,.pdf,.doc,.docx,.rtf,.csv,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/rtf,text/plain,text/csv"; const TEXT_ALLOWED_TYPES = [ - 'text/plain', - 'application/pdf', - 'application/msword', - 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', - 'application/rtf', - 'text/csv' + "text/plain", + "application/pdf", + "application/msword", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "application/rtf", + "text/csv", ]; export default function ChatFileCard() { @@ -41,16 +42,16 @@ export default function ChatFileCard() { setError(""); setChatFileLoading(true); const formData = new FormData(); - formData.append('host', host); - formData.append('flowId', flowId); - formData.append('fileComponentName', fileComponentName); - formData.append('input_value', input_value); - formData.append('file', file); - if (langflowApiKey) formData.append('langflowApiKey', langflowApiKey); - if (sessionId) formData.append('sessionId', sessionId); + formData.append("host", host); + formData.append("flowId", flowId); + formData.append("fileComponentName", fileComponentName); + formData.append("input_value", input_value); + formData.append("file", file); + if (langflowApiKey) formData.append("langflowApiKey", langflowApiKey); + if (sessionId) formData.append("sessionId", sessionId); try { - const res = await fetch('/api/chat-and-file', { - method: 'POST', + const res = await fetch("/api/chat-and-file", { + method: "POST", body: formData, }); const data = await res.json(); @@ -68,23 +69,33 @@ export default function ChatFileCard() { // Construct endpoints using host const safeHost = host || "http://127.0.0.1:7860"; const fileUploadEndpoint = `${safeHost.replace(/\/$/, "")}/api/v2/files/`; - const langflowRunEndpoint = flowId ? `${safeHost.replace(/\/$/, "")}/api/v1/run/${flowId}` : `${safeHost.replace(/\/$/, "")}/api/v1/run/`; + const langflowRunEndpoint = flowId + ? `${safeHost.replace(/\/$/, "")}/api/v1/run/${flowId}` + : `${safeHost.replace(/\/$/, "")}/api/v1/run/`; // Use actual uploaded file path if available, otherwise placeholder - const uploadedFilePath = uploadResponse?.langflowFileUploadResponse?.path || "/path/to/uploaded/file"; + const uploadedFilePath = + uploadResponse?.langflowFileUploadResponse?.path || + "/path/to/uploaded/file"; - const payloadPreview = JSON.stringify({ - input_value: input_value || '', - output_type: 'chat', - input_type: 'chat', - ...(sessionId ? { session_id: sessionId } : {}), - tweaks: fileComponentName ? { - [fileComponentName]: { - path: uploadedFilePath - } - } : undefined - }, null, 2); + const payloadPreview = JSON.stringify( + { + input_value: input_value || "", + output_type: "chat", + input_type: "chat", + ...(sessionId ? { session_id: sessionId } : {}), + tweaks: fileComponentName + ? { + [fileComponentName]: { + path: uploadedFilePath, + }, + } + : undefined, + }, + null, + 2 + ); - const fileName = file ? file.name : 'yourfile.txt'; + const fileName = file ? file.name : "yourfile.txt"; const nodeCode = `// Node 18+ example using global fetch, FormData, and Blob import fs from 'fs/promises'; @@ -93,7 +104,9 @@ import fs from 'fs/promises'; const fileBuffer = await fs.readFile('${fileName}'); const data = new FormData(); data.append('file', new Blob([fileBuffer]), '${fileName}'); -const headers = ${langflowApiKey ? `{ 'x-api-key': '${langflowApiKey}' }` : 'undefined'}; +const headers = ${ + langflowApiKey ? `{ 'x-api-key': '${langflowApiKey}' }` : "undefined" + }; // 2. Upload the file to Langflow const uploadRes = await fetch('${fileUploadEndpoint}', { @@ -106,23 +119,68 @@ const uploadedPath = uploadData.path; // 3. Call the Langflow run endpoint with the uploaded file path const payload = { - input_value: "${input_value || 'What is in this file?'}", + input_value: "${input_value || "What is in this file?"}", output_type: "chat", - input_type: "chat"${sessionId ? `,\n // Optional: Use session tracking if needed\n session_id: "${sessionId}"` : ''}, + input_type: "chat"${ + sessionId + ? `,\n // Optional: Use session tracking if needed\n session_id: "${sessionId}"` + : "" + }, tweaks: { - '${fileComponentName || 'File-Component-Name'}': { + '${fileComponentName || "File-Component-Name"}': { path: uploadedPath } } }; const runRes = await fetch('${langflowRunEndpoint}', { method: 'POST', - headers: { 'Content-Type': 'application/json'${langflowApiKey ? ", 'x-api-key': '" + langflowApiKey + "'" : ""} }, + headers: { 'Content-Type': 'application/json'${ + langflowApiKey ? ", 'x-api-key': '" + langflowApiKey + "'" : "" + } }, body: JSON.stringify(payload) }); const langflowData = await runRes.json(); // Output only the message console.log(langflowData.outputs?.[0]?.outputs?.[0]?.results?.message?.data?.text); +`; + + const nodeClientCode = `// Node.js example using @datastax/langflow-client +import fs from 'fs/promises'; +import { LangflowClient } from '@datastax/langflow-client'; + +// 1. Initialize the Langflow client +const client = new LangflowClient({ + baseUrl: '${safeHost}'${ + langflowApiKey + ? `, + apiKey: '${langflowApiKey}'` + : "" + } +}); +const flow = client.flow('${flowId || ""}'); + +// 2. Prepare the form data with the file to upload +const fileBuffer = await fs.readFile('${fileName}'); +const file = new Blob([fileBuffer]), '${fileName}'); + +// 3. Upload the file to Langflow +const uploadData = await client.files.upload(file); +const uploadedPath = uploadData.path; + +// 4. Call the Langflow run endpoint with the uploaded file path +const flowResult = await flow.run("${input_value || "What is in this file?"}", { + tweaks: { + '${fileComponentName || "Chat-Component-Name"}': { + path: uploadedPath + } + }${ + sessionId + ? `,\n // Optional: Use session tracking if needed\n session_id: "${sessionId}"` + : "" + } +}); +// Output only the message +console.log(flowResult.chatOutputText()); `; const pythonCode = `# Python example using requests @@ -138,7 +196,9 @@ files = [ ('file', ('${fileName}', open('${fileName}', 'rb'), 'application/octet-stream')) ] headers = { - 'Accept': 'application/json'${langflowApiKey ? ",\n 'x-api-key': '" + langflowApiKey + "'" : ""} + 'Accept': 'application/json'${ + langflowApiKey ? ",\n 'x-api-key': '" + langflowApiKey + "'" : "" + } } # 3. Upload the file to Langflow @@ -152,18 +212,24 @@ uploaded_path = uploaded_data.get('path') # 5. Call the Langflow run endpoint with the uploaded file path run_url = "${langflowRunEndpoint}" run_payload = { - "input_value": "${input_value || 'What is in this file?'}", + "input_value": "${input_value || "What is in this file?"}", "output_type": "chat", - "input_type": "chat"${sessionId ? `,\n # Optional: Use session tracking if needed\n "session_id": "${sessionId}"` : ''}, + "input_type": "chat"${ + sessionId + ? `,\n # Optional: Use session tracking if needed\n "session_id": "${sessionId}"` + : "" + }, "tweaks": { - "${fileComponentName || 'File-Component-Name'}": { + "${fileComponentName || "File-Component-Name"}": { "path": uploaded_path } } } run_headers = { 'Content-Type': 'application/json', - 'Accept': 'application/json'${langflowApiKey ? ",\n 'x-api-key': '" + langflowApiKey + "'" : ""} + 'Accept': 'application/json'${ + langflowApiKey ? ",\n 'x-api-key': '" + langflowApiKey + "'" : "" + } } run_response = requests.post(run_url, headers=run_headers, data=json.dumps(run_payload)) langflow_data = run_response.json() @@ -187,8 +253,12 @@ unset uploaded_path uploaded_path=$(curl -s -X POST \\ "${fileUploadEndpoint}" \\ -H "Accept: application/json" \\ - -F "file=@${fileName}"${langflowApiKey ? ` \\ - -H "x-api-key: ${langflowApiKey}"` : ''} \\ + -F "file=@${fileName}"${ + langflowApiKey + ? ` \\ + -H "x-api-key: ${langflowApiKey}"` + : "" + } \\ | jq -r '.path') # Verify that we got a valid path @@ -201,14 +271,20 @@ fi curl -s --request POST \\ --url "${langflowRunEndpoint}" \\ -H "Content-Type: application/json" \\ - -H "Accept: application/json"${langflowApiKey ? ` \\ - -H "x-api-key: ${langflowApiKey}"` : ''} \\ + -H "Accept: application/json"${ + langflowApiKey + ? ` \\ + -H "x-api-key: ${langflowApiKey}"` + : "" + } \\ -d '{ - "input_value": "${input_value ? input_value.replace(/'/g, "\\'") : 'What is in this file?'}", + "input_value": "${ + input_value ? input_value.replace(/'/g, "\\'") : "What is in this file?" + }", "output_type": "chat", - "input_type": "chat"${sessionId ? `,\n "session_id": "${sessionId}"` : ''}, + "input_type": "chat"${sessionId ? `,\n "session_id": "${sessionId}"` : ""}, "tweaks": { - "${fileComponentName || 'File-Component-Name'}": { + "${fileComponentName || "File-Component-Name"}": { "path": "'"$uploaded_path"'" } } @@ -221,8 +297,12 @@ curl -s --request POST \\
-

Chat Input & File Component (Text + File)

- +

+ Chat Input & File Component (Text + File) +

+ setHost(e.target.value)} /> - + setFlowId(e.target.value)} /> - + setFileComponentName(e.target.value)} /> - + setInputValue(e.target.value)} /> - + { const file = e.target.files[0]; if (file && !TEXT_ALLOWED_TYPES.includes(file.type)) { - setError('Invalid file type. Only text, PDF, Word, RTF, and CSV files are allowed.'); + setError( + "Invalid file type. Only text, PDF, Word, RTF, and CSV files are allowed." + ); setFile(null); - e.target.value = ''; + e.target.value = ""; } else { setFile(file); setError(""); } }} /> - + setSessionId(e.target.value)} /> - + setShowApiKey(v => !v)} + onClick={() => setShowApiKey((v) => !v)} > {showApiKey ? "Hide" : "Show"} API Key @@ -313,7 +416,7 @@ curl -s --request POST \\ className="mt-2 bg-[#2563eb] hover:bg-[#1d4ed8] transition-colors text-white font-semibold py-3 px-4 rounded-lg disabled:opacity-50 focus:outline-none focus:ring-2 focus:ring-[#2563eb] focus:ring-offset-2 focus:ring-offset-[#19213a]" disabled={chatFileLoading} > - {chatFileLoading ? () : "Submit"} + {chatFileLoading ? : "Submit"}
@@ -321,17 +424,29 @@ curl -s --request POST \\ - +
); -} \ No newline at end of file +} diff --git a/src/app/components/ChatImageCard.js b/src/app/components/ChatImageCard.js index 7da4b9e..1fce9f8 100644 --- a/src/app/components/ChatImageCard.js +++ b/src/app/components/ChatImageCard.js @@ -3,14 +3,15 @@ import EndpointSection from "./EndpointSection"; import ResponseSection from "./ResponseSection"; import CodeSection from "./CodeSection"; -const IMAGE_ACCEPTED_FILE_TYPES = ".jpg,.jpeg,.png,.gif,.bmp,.webp,image/jpeg,image/png,image/gif,image/bmp,image/webp"; +const IMAGE_ACCEPTED_FILE_TYPES = + ".jpg,.jpeg,.png,.gif,.bmp,.webp,image/jpeg,image/png,image/gif,image/bmp,image/webp"; const IMAGE_ALLOWED_TYPES = [ - 'image/jpeg', - 'image/png', - 'image/gif', - 'image/bmp', - 'image/webp', - 'image/jpg' + "image/jpeg", + "image/png", + "image/gif", + "image/bmp", + "image/webp", + "image/jpg", ]; export default function ChatImageCard() { @@ -40,15 +41,15 @@ export default function ChatImageCard() { setImageError(""); setImageLoading(true); const formData = new FormData(); - formData.append('host', host); - formData.append('flowId', flowId); - formData.append('fileComponentName', fileComponentName); - formData.append('input_value', input_value); - formData.append('file', imageFile); - if (langflowApiKey) formData.append('langflowApiKey', langflowApiKey); + formData.append("host", host); + formData.append("flowId", flowId); + formData.append("fileComponentName", fileComponentName); + formData.append("input_value", input_value); + formData.append("file", imageFile); + if (langflowApiKey) formData.append("langflowApiKey", langflowApiKey); try { - const res = await fetch('/api/chat-and-image', { - method: 'POST', + const res = await fetch("/api/chat-and-image", { + method: "POST", body: formData, }); const data = await res.json(); @@ -65,23 +66,38 @@ export default function ChatImageCard() { // Construct endpoints using host const safeHost = host || "http://127.0.0.1:7860"; - const fileUploadEndpoint = flowId ? `${safeHost.replace(/\/$/, "")}/api/v1/files/upload/${flowId}` : `${safeHost.replace(/\/$/, "")}/api/v1/files/upload/`; - const langflowRunEndpoint = flowId ? `${safeHost.replace(/\/$/, "")}/api/v1/run/${flowId}` : `${safeHost.replace(/\/$/, "")}/api/v1/run/`; + const fileUploadEndpoint = flowId + ? `${safeHost.replace(/\/$/, "")}/api/v1/files/upload/${flowId}` + : `${safeHost.replace(/\/$/, "")}/api/v1/files/upload/`; + const langflowRunEndpoint = flowId + ? `${safeHost.replace(/\/$/, "")}/api/v1/run/${flowId}` + : `${safeHost.replace(/\/$/, "")}/api/v1/run/`; // Use actual uploaded file path if available, otherwise placeholder - const uploadedFilePath = imageResponse?.file_path || imageResponse?.langflowFileUploadResponse?.file_path || imageResponse?.path || imageResponse?.langflowFileUploadResponse?.path || "/path/to/uploaded/image"; + const uploadedFilePath = + imageResponse?.file_path || + imageResponse?.langflowFileUploadResponse?.file_path || + imageResponse?.path || + imageResponse?.langflowFileUploadResponse?.path || + "/path/to/uploaded/image"; - const payloadPreview = JSON.stringify({ - input_value: input_value || '', - output_type: 'chat', - input_type: 'chat', - tweaks: fileComponentName ? { - [fileComponentName]: { - files: uploadedFilePath ? [uploadedFilePath] : [] - } - } : undefined - }, null, 2); + const payloadPreview = JSON.stringify( + { + input_value: input_value || "", + output_type: "chat", + input_type: "chat", + tweaks: fileComponentName + ? { + [fileComponentName]: { + files: uploadedFilePath ? [uploadedFilePath] : [], + }, + } + : undefined, + }, + null, + 2 + ); - const fileName = imageFile ? imageFile.name : 'yourimage.png'; + const fileName = imageFile ? imageFile.name : "yourimage.png"; const nodeCode = `// Node 18+ example using global fetch, FormData, and Blob import fs from 'fs/promises'; @@ -90,7 +106,9 @@ import fs from 'fs/promises'; const fileBuffer = await fs.readFile('${fileName}'); const data = new FormData(); data.append('file', new Blob([fileBuffer]), '${fileName}'); -const headers = ${langflowApiKey ? `{ 'x-api-key': '${langflowApiKey}' }` : 'undefined'}; +const headers = ${ + langflowApiKey ? `{ 'x-api-key': '${langflowApiKey}' }` : "undefined" + }; // 2. Upload the image to Langflow const uploadRes = await fetch('${fileUploadEndpoint}', { @@ -103,23 +121,62 @@ const uploadedPath = uploadData.file_path; // 3. Call the Langflow run endpoint with the uploaded file path const payload = { - input_value: "${input_value || 'What is in this image?'}", + input_value: "${input_value || "What is in this image?"}", output_type: "chat", input_type: "chat", tweaks: { - '${fileComponentName || 'File-Component-Name'}': { + '${fileComponentName || "File-Component-Name"}': { files: [uploadedPath] } } }; const runRes = await fetch('${langflowRunEndpoint}', { method: 'POST', - headers: { 'Content-Type': 'application/json'${langflowApiKey ? ", 'x-api-key': '" + langflowApiKey + "'" : ""} }, + headers: { 'Content-Type': 'application/json'${ + langflowApiKey ? ", 'x-api-key': '" + langflowApiKey + "'" : "" + } }, body: JSON.stringify(payload) }); const langflowData = await runRes.json(); // Output only the message console.log(langflowData.outputs?.[0]?.outputs?.[0]?.results?.message?.data?.text); +`; + + const nodeClientCode = `// Node.js example using @datastax/langflow-client +import fs from 'fs/promises'; +import { LangflowClient } from '@datastax/langflow-client'; + +// 1. Initialize the Langflow client +const client = new LangflowClient({ + baseUrl: '${safeHost}'${ + langflowApiKey + ? `, + apiKey: '${langflowApiKey}'` + : "" + } +}); +const flow = client.flow('${flowId || ""}'); + +// 2. Prepare the form data with the file to upload +const fileBuffer = await fs.readFile('${fileName}'); +const file = new Blob([fileBuffer]), '${fileName}'); + +// 3. Upload the image to Langflow +const uploadData = await flow.uploadFile(file); +const uploadedPath = uploadData.file_path; + +// 4. Call the Langflow run endpoint with the uploaded file path +const flowResult = await flow.run("${ + input_value || "What is in this image?" + }", { + tweaks: { + '${fileComponentName || "Chat-Component-Name"}': { + path: uploadedPath + } + } +}); +// Output only the message +console.log(flowResult.chatOutputText()); `; const pythonCode = `# Python example using requests @@ -135,7 +192,9 @@ files = [ ('file', ('${fileName}', open('${fileName}', 'rb'), 'application/octet-stream')) ] headers = { - 'Accept': 'application/json'${langflowApiKey ? ",\n 'x-api-key': '" + langflowApiKey + "'" : ""} + 'Accept': 'application/json'${ + langflowApiKey ? ",\n 'x-api-key': '" + langflowApiKey + "'" : "" + } } # 3. Upload the image to Langflow @@ -149,18 +208,20 @@ uploaded_path = uploaded_data.get('file_path') # 5. Call the Langflow run endpoint with the uploaded file path run_url = "${langflowRunEndpoint}" run_payload = { - "input_value": "${input_value || 'What is in this image?'}", + "input_value": "${input_value || "What is in this image?"}", "output_type": "chat", "input_type": "chat", "tweaks": { - "${fileComponentName || 'File-Component-Name'}": { + "${fileComponentName || "File-Component-Name"}": { "files": [uploaded_path] } } } run_headers = { 'Content-Type': 'application/json', - 'Accept': 'application/json'${langflowApiKey ? ",\n 'x-api-key': '" + langflowApiKey + "'" : ""} + 'Accept': 'application/json'${ + langflowApiKey ? ",\n 'x-api-key': '" + langflowApiKey + "'" : "" + } } run_response = requests.post(run_url, headers=run_headers, data=json.dumps(run_payload)) langflow_data = run_response.json() @@ -184,8 +245,12 @@ unset uploaded_path uploaded_path=$(curl -s -X POST \\ "${fileUploadEndpoint}" \\ -H "Accept: application/json" \\ - -F "file=@${fileName}"${langflowApiKey ? ` \\ - -H "x-api-key: ${langflowApiKey}"` : ''} \\ + -F "file=@${fileName}"${ + langflowApiKey + ? ` \\ + -H "x-api-key: ${langflowApiKey}"` + : "" + } \\ | jq -r '.file_path') # Verify that we got a valid path @@ -198,14 +263,20 @@ fi curl -s --request POST \\ --url "${langflowRunEndpoint}" \\ -H "Content-Type: application/json" \\ - -H "Accept: application/json"${langflowApiKey ? ` \\ - -H "x-api-key: ${langflowApiKey}"` : ''} \\ + -H "Accept: application/json"${ + langflowApiKey + ? ` \\ + -H "x-api-key: ${langflowApiKey}"` + : "" + } \\ -d '{ - "input_value": "${input_value ? input_value.replace(/'/g, "\\'") : 'What is in this image?'}", + "input_value": "${ + input_value ? input_value.replace(/'/g, "\\'") : "What is in this image?" + }", "output_type": "chat", "input_type": "chat", "tweaks": { - "${fileComponentName || 'File-Component-Name'}": { + "${fileComponentName || "File-Component-Name"}": { "files": ["'"$uploaded_path"'"] } } @@ -218,8 +289,12 @@ curl -s --request POST \\
-

Chat Input Using Files (Text + Image)

- +

+ Chat Input Using Files (Text + Image) +

+ setHost(e.target.value)} /> - + setFlowId(e.target.value)} /> - + setFileComponentName(e.target.value)} /> - + setInputValue(e.target.value)} /> - + { const file = e.target.files[0]; if (file && !IMAGE_ALLOWED_TYPES.includes(file.type)) { - setImageError('Invalid file type. Only image files (jpg, jpeg, png, gif, bmp, webp) are allowed.'); + setImageError( + "Invalid file type. Only image files (jpg, jpeg, png, gif, bmp, webp) are allowed." + ); setImageFile(null); - e.target.value = ''; + e.target.value = ""; } else { setImageFile(file); setImageError(""); } }} /> - + setShowApiKey(v => !v)} + onClick={() => setShowApiKey((v) => !v)} > {showApiKey ? "Hide" : "Show"} API Key - {imageError &&

{imageError}

} + {imageError && ( +

{imageError}

+ )}
@@ -308,17 +406,29 @@ curl -s --request POST \\ - +
); -} \ No newline at end of file +} diff --git a/src/app/components/FileUploadCard.js b/src/app/components/FileUploadCard.js index ef6bc86..55c1c1b 100644 --- a/src/app/components/FileUploadCard.js +++ b/src/app/components/FileUploadCard.js @@ -4,14 +4,15 @@ import EndpointSection from "./EndpointSection"; import ResponseSection from "./ResponseSection"; import CodeSection from "./CodeSection"; -const TEXT_ACCEPTED_FILE_TYPES = ".txt,.pdf,.doc,.docx,.rtf,.csv,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/rtf,text/plain,text/csv"; +const TEXT_ACCEPTED_FILE_TYPES = + ".txt,.pdf,.doc,.docx,.rtf,.csv,application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/rtf,text/plain,text/csv"; const TEXT_ALLOWED_TYPES = [ - 'text/plain', - 'application/pdf', - 'application/msword', - 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', - 'application/rtf', - 'text/csv' + "text/plain", + "application/pdf", + "application/msword", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "application/rtf", + "text/csv", ]; export default function FileUploadCard() { @@ -31,7 +32,9 @@ export default function FileUploadCard() { e.preventDefault(); setFileOnlyResponse(null); if (!host || !flowId || !fileComponentName) { - setFileOnlyError("Please provide Host, Flow ID, and File Component Name."); + setFileOnlyError( + "Please provide Host, Flow ID, and File Component Name." + ); return; } if (!fileOnly) { @@ -41,15 +44,15 @@ export default function FileUploadCard() { setFileOnlyError(""); setFileOnlyLoading(true); const formData = new FormData(); - formData.append('file', fileOnly); - formData.append('flowId', flowId); - formData.append('fileComponentName', fileComponentName); - formData.append('host', host); - if (langflowApiKey) formData.append('langflowApiKey', langflowApiKey); - if (sessionId) formData.append('sessionId', sessionId); + formData.append("file", fileOnly); + formData.append("flowId", flowId); + formData.append("fileComponentName", fileComponentName); + formData.append("host", host); + if (langflowApiKey) formData.append("langflowApiKey", langflowApiKey); + if (sessionId) formData.append("sessionId", sessionId); try { - const res = await fetch('/api/file-only', { - method: 'POST', + const res = await fetch("/api/file-only", { + method: "POST", body: formData, }); const data = await res.json(); @@ -67,23 +70,34 @@ export default function FileUploadCard() { // Construct endpoints using host const safeHost = host || "http://127.0.0.1:7860"; const fileUploadEndpoint = `${safeHost.replace(/\/$/, "")}/api/v2/files/`; - const langflowRunEndpoint = flowId ? `${safeHost.replace(/\/$/, "")}/api/v1/run/${flowId}` : `${safeHost.replace(/\/$/, "")}/api/v1/run/`; + const langflowRunEndpoint = flowId + ? `${safeHost.replace(/\/$/, "")}/api/v1/run/${flowId}` + : `${safeHost.replace(/\/$/, "")}/api/v1/run/`; // Use actual uploaded file path if available, otherwise placeholder - const uploadedFilePath = fileOnlyResponse?.path || fileOnlyResponse?.langflowFileUploadResponse?.path || "/path/to/uploaded/file"; + const uploadedFilePath = + fileOnlyResponse?.path || + fileOnlyResponse?.langflowFileUploadResponse?.path || + "/path/to/uploaded/file"; - const payloadPreview = JSON.stringify({ - input_value: 'Analyze this file', - output_type: 'chat', - input_type: 'text', - ...(sessionId ? { session_id: sessionId } : {}), - tweaks: fileComponentName ? { - [fileComponentName]: { - path: uploadedFilePath - } - } : undefined - }, null, 2); + const payloadPreview = JSON.stringify( + { + input_value: "Analyze this file", + output_type: "chat", + input_type: "text", + ...(sessionId ? { session_id: sessionId } : {}), + tweaks: fileComponentName + ? { + [fileComponentName]: { + path: uploadedFilePath, + }, + } + : undefined, + }, + null, + 2 + ); - const fileName = fileOnly ? fileOnly.name : 'yourfile.txt'; + const fileName = fileOnly ? fileOnly.name : "yourfile.txt"; const browserCode = `// 1. Get the file from the file picker const fileInput = document.getElementById("fileOnly"); @@ -95,7 +109,11 @@ const fileForm = new FormData(); fileForm.append('file', file); const uploadRes = await fetch('${fileUploadEndpoint}', { method: 'POST', - body: fileForm,${langflowApiKey ? "\n headers: { 'x-api-key': '" + langflowApiKey + "' }," : ""} + body: fileForm,${ + langflowApiKey + ? "\n headers: { 'x-api-key': '" + langflowApiKey + "' }," + : "" + } }); const uploadData = await uploadRes.json(); const uploadedPath = uploadData.file_path || uploadData.path; @@ -103,14 +121,16 @@ const uploadedPath = uploadData.file_path || uploadData.path; // 3. Call the Langflow run endpoint const payload = { tweaks: { - '${fileComponentName || 'File-Component-Name'}': { + '${fileComponentName || "File-Component-Name"}': { path: uploadedPath } } }; const runRes = await fetch('${langflowRunEndpoint}', { method: 'POST', - headers: { 'Content-Type': 'application/json'${langflowApiKey ? ", 'x-api-key': '" + langflowApiKey + "'" : ""} }, + headers: { 'Content-Type': 'application/json'${ + langflowApiKey ? ", 'x-api-key': '" + langflowApiKey + "'" : "" + } }, body: JSON.stringify(payload) }); const langflowData = await runRes.json(); @@ -125,7 +145,9 @@ import fs from 'fs/promises'; const fileBuffer = await fs.readFile('${fileName}'); const data = new FormData(); data.append('file', new Blob([fileBuffer]), '${fileName}'); -const headers = ${langflowApiKey ? `{ 'x-api-key': '${langflowApiKey}' }` : 'undefined'}; +const headers = ${ + langflowApiKey ? `{ 'x-api-key': '${langflowApiKey}' }` : "undefined" + }; // 2. Upload the file to Langflow const uploadRes = await fetch('${fileUploadEndpoint}', { @@ -140,21 +162,66 @@ const uploadedPath = uploadData.path; const payload = { input_value: "Analyze this file", output_type: "chat", - input_type: "text"${sessionId ? `,\n // Optional: Use session tracking if needed\n session_id: "${sessionId}"` : ''}, + input_type: "text"${ + sessionId + ? `,\n // Optional: Use session tracking if needed\n session_id: "${sessionId}"` + : "" + }, tweaks: { - '${fileComponentName || 'File-Component-Name'}': { + '${fileComponentName || "File-Component-Name"}': { path: uploadedPath } } }; const runRes = await fetch('${langflowRunEndpoint}', { method: 'POST', - headers: { 'Content-Type': 'application/json'${langflowApiKey ? ", 'x-api-key': '" + langflowApiKey + "'" : ""} }, + headers: { 'Content-Type': 'application/json'${ + langflowApiKey ? ", 'x-api-key': '" + langflowApiKey + "'" : "" + } }, body: JSON.stringify(payload) }); const langflowData = await runRes.json(); // Output only the message console.log(langflowData.outputs?.[0]?.outputs?.[0]?.results?.message?.data?.text); +`; + + const nodeClientCode = `// Node.js example using @datastax/langflow-client +import fs from 'fs/promises'; +import { LangflowClient } from '@datastax/langflow-client'; + +// 1. Initialize the Langflow client +const client = new LangflowClient({ + baseUrl: '${safeHost}'${ + langflowApiKey + ? `, + apiKey: '${langflowApiKey}'` + : "" + } +}); +const flow = client.flow('${flowId || ""}'); + +// 2. Prepare the form data with the file to upload +const fileBuffer = await fs.readFile('${fileName}'); +const file = new Blob([fileBuffer]), '${fileName}'); + +// 3. Upload the file to Langflow +const uploadData = await client.files.upload(file); +const uploadedPath = uploadData.path; + +// 4. Call the Langflow run endpoint with the uploaded file path +const flowResult = await flow.run("Analyze this file", { + tweaks: { + '${fileComponentName || "File-Component-Name"}': { + path: uploadedPath + } + }${ + sessionId + ? `,\n // Optional: Use session tracking if needed\n session_id: "${sessionId}"` + : "" + } +}); +// Output only the message +console.log(flowResult.chatOutputText()); `; const pythonCode = `# Python example using requests @@ -170,7 +237,9 @@ files = [ ('file', ('${fileName}', open('${fileName}', 'rb'), 'application/octet-stream')) ] headers = { - 'Accept': 'application/json'${langflowApiKey ? ",\n 'x-api-key': '" + langflowApiKey + "'" : ""} + 'Accept': 'application/json'${ + langflowApiKey ? ",\n 'x-api-key': '" + langflowApiKey + "'" : "" + } } # 3. Upload the file to Langflow @@ -186,16 +255,22 @@ run_url = "${langflowRunEndpoint}" run_payload = { "input_value": "Analyze this file", "output_type": "chat", - "input_type": "text"${sessionId ? `,\n # Optional: Use session tracking if needed\n "session_id": "${sessionId}"` : ''}, + "input_type": "text"${ + sessionId + ? `,\n # Optional: Use session tracking if needed\n "session_id": "${sessionId}"` + : "" + }, "tweaks": { - "${fileComponentName || 'File-Component-Name'}": { + "${fileComponentName || "File-Component-Name"}": { "path": uploaded_path } } } run_headers = { 'Content-Type': 'application/json', - 'Accept': 'application/json'${langflowApiKey ? ",\n 'x-api-key': '" + langflowApiKey + "'" : ""} + 'Accept': 'application/json'${ + langflowApiKey ? ",\n 'x-api-key': '" + langflowApiKey + "'" : "" + } } run_response = requests.post(run_url, headers=run_headers, data=json.dumps(run_payload)) langflow_data = run_response.json() @@ -219,8 +294,12 @@ unset uploaded_path uploaded_path=$(curl -s -X POST \\ "${fileUploadEndpoint}" \\ -H "Accept: application/json" \\ - -F "file=@${fileName}"${langflowApiKey ? ` \\ - -H "x-api-key: ${langflowApiKey}"` : ''} \\ + -F "file=@${fileName}"${ + langflowApiKey + ? ` \\ + -H "x-api-key: ${langflowApiKey}"` + : "" + } \\ | jq -r '.path') # Verify that we got a valid path @@ -233,14 +312,18 @@ fi curl -s --request POST \\ --url "${langflowRunEndpoint}" \\ -H "Content-Type: application/json" \\ - -H "Accept: application/json"${langflowApiKey ? ` \\ - -H "x-api-key: ${langflowApiKey}"` : ''} \\ + -H "Accept: application/json"${ + langflowApiKey + ? ` \\ + -H "x-api-key: ${langflowApiKey}"` + : "" + } \\ -d '{ "input_value": "Analyze this file", "output_type": "chat", - "input_type": "text"${sessionId ? `,\n "session_id": "${sessionId}"` : ''}, + "input_type": "text"${sessionId ? `,\n "session_id": "${sessionId}"` : ""}, "tweaks": { - "${fileComponentName || 'File-Component-Name'}": { + "${fileComponentName || "File-Component-Name"}": { "path": "'"$uploaded_path"'" } } @@ -253,37 +336,56 @@ curl -s --request POST \\
- +
); -} \ No newline at end of file +} diff --git a/src/app/components/HelloWorldCard.js b/src/app/components/HelloWorldCard.js index 8b5816e..40b72eb 100644 --- a/src/app/components/HelloWorldCard.js +++ b/src/app/components/HelloWorldCard.js @@ -24,14 +24,14 @@ export default function HelloWorldCard() { setError(""); setLoading(true); const formData = new FormData(); - formData.append('host', host); - formData.append('flowId', flowId); - formData.append('input_value', input_value); - if (langflowApiKey) formData.append('langflowApiKey', langflowApiKey); - if (sessionId) formData.append('sessionId', sessionId); + formData.append("host", host); + formData.append("flowId", flowId); + formData.append("input_value", input_value); + if (langflowApiKey) formData.append("langflowApiKey", langflowApiKey); + if (sessionId) formData.append("sessionId", sessionId); try { - const res = await fetch('/api/hello-world', { - method: 'POST', + const res = await fetch("/api/hello-world", { + method: "POST", body: formData, }); const data = await res.json(); @@ -47,26 +47,75 @@ export default function HelloWorldCard() { }; const safeHost = host || "http://127.0.0.1:7860"; - const langflowRunEndpoint = flowId ? `${safeHost.replace(/\/$/, "")}/api/v1/run/${flowId}` : `${safeHost.replace(/\/$/, "")}/api/v1/run/`; - const payloadPreview = JSON.stringify({ - input_value: input_value || '', - output_type: 'chat', - input_type: 'chat', - ...(sessionId ? { session_id: sessionId } : {}) - }, null, 2); + const langflowRunEndpoint = flowId + ? `${safeHost.replace(/\/$/, "")}/api/v1/run/${flowId}` + : `${safeHost.replace(/\/$/, "")}/api/v1/run/`; + const payloadPreview = JSON.stringify( + { + input_value: input_value || "", + output_type: "chat", + input_type: "chat", + ...(sessionId ? { session_id: sessionId } : {}), + }, + null, + 2 + ); const sessionIdForExample = sessionId || "user_1"; - const nodeCode = `// Node 18+ example using global fetch\nconst payload = {\n input_value: \"${input_value || ''}\",\n output_type: \"chat\",\n input_type: \"chat\"${sessionId ? `,\n // Optional: Use session tracking if needed\n session_id: \"${sessionId}\"` : ''}\n};\n\nconst options = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'${langflowApiKey ? ",\n 'x-api-key': '" + langflowApiKey + "'" : ""}\n },\n body: JSON.stringify(payload)\n};\n\nfetch('${langflowRunEndpoint}', options)\n .then(response => response.json())\n .then(data => {\n // Print only the message\n const msg = data?.outputs?.[0]?.outputs?.[0]?.results?.message?.data?.text;\n if (msg) {\n console.log(msg);\n } else {\n console.error('No message found in response:', data);\n }\n })\n .catch(err => console.error(err));\n`; - const pythonCode = `# Python example using requests\nimport requests\nimport json\n\nurl = \"${langflowRunEndpoint}\"\npayload = {\n \"input_value\": \"${input_value || ''}\",\n \"output_type\": \"chat\",\n \"input_type\": \"chat\"${sessionId ? `,\n # Optional: Use session tracking if needed\n \"session_id\": \"${sessionId}\"` : ''}\n}\nheaders = {\n 'Content-Type': 'application/json'${langflowApiKey ? ",\n 'x-api-key': '" + langflowApiKey + "'" : ""}\n}\nres = requests.post(url, headers=headers, data=json.dumps(payload))\ndata = res.json()\n# Print only the message\ntry:\n msg = data['outputs'][0]['outputs'][0]['results']['message']['data']['text']\n print(msg)\nexcept (KeyError, IndexError, TypeError):\n print('No message found in response:', data)\n`; - const curlCode = `curl -s -X POST \\\n '${langflowRunEndpoint}' \\\n -H 'Content-Type: application/json'${langflowApiKey ? ` \\\n -H 'x-api-key: ${langflowApiKey}'` : ''} \\\n -d '{\n "input_value": "${input_value || ''}",\n "output_type": "chat",\n "input_type": "chat"${sessionId ? `,\n "session_id": "${sessionId}"` : ''}\n }' | jq -r '.outputs[0].outputs[0].results.message.data.text'\n`; + const nodeCode = `// Node 18+ example using global fetch\nconst payload = {\n input_value: \"${ + input_value || "" + }\",\n output_type: \"chat\",\n input_type: \"chat\"${ + sessionId + ? `,\n // Optional: Use session tracking if needed\n session_id: \"${sessionId}\"` + : "" + }\n};\n\nconst options = {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'${ + langflowApiKey ? ",\n 'x-api-key': '" + langflowApiKey + "'" : "" + }\n },\n body: JSON.stringify(payload)\n};\n\nfetch('${langflowRunEndpoint}', options)\n .then(response => response.json())\n .then(data => {\n // Print only the message\n const msg = data?.outputs?.[0]?.outputs?.[0]?.results?.message?.data?.text;\n if (msg) {\n console.log(msg);\n } else {\n console.error('No message found in response:', data);\n }\n })\n .catch(err => console.error(err));\n`; + const nodeClientCode = `// Node.js example using @datastax/langflow-client\nimport { LangflowClient } from '@datastax/langflow-client';\n\nconst client = new LangflowClient({ + baseUrl: '${safeHost}'${ + langflowApiKey + ? `, + apiKey: '${langflowApiKey}'` + : "" + } +}); +const flow = client.flow("${ + flowId || "" + }");\n\nconst result = await flow.run(\"${input_value || ""}\"${ + sessionId + ? `, {\n // Optional: Use session tracking if needed\n session_id: \"${sessionId}\"\n}` + : "" + });\n +console.log(result.chatOutputText());`; + + const pythonCode = `# Python example using requests\nimport requests\nimport json\n\nurl = \"${langflowRunEndpoint}\"\npayload = {\n \"input_value\": \"${ + input_value || "" + }\",\n \"output_type\": \"chat\",\n \"input_type\": \"chat\"${ + sessionId + ? `,\n # Optional: Use session tracking if needed\n \"session_id\": \"${sessionId}\"` + : "" + }\n}\nheaders = {\n 'Content-Type': 'application/json'${ + langflowApiKey ? ",\n 'x-api-key': '" + langflowApiKey + "'" : "" + }\n}\nres = requests.post(url, headers=headers, data=json.dumps(payload))\ndata = res.json()\n# Print only the message\ntry:\n msg = data['outputs'][0]['outputs'][0]['results']['message']['data']['text']\n print(msg)\nexcept (KeyError, IndexError, TypeError):\n print('No message found in response:', data)\n`; + const curlCode = `curl -s -X POST \\\n '${langflowRunEndpoint}' \\\n -H 'Content-Type: application/json'${ + langflowApiKey ? ` \\\n -H 'x-api-key: ${langflowApiKey}'` : "" + } \\\n -d '{\n "input_value": "${ + input_value || "" + }",\n "output_type": "chat",\n "input_type": "chat"${ + sessionId ? `,\n "session_id": "${sessionId}"` : "" + }\n }' | jq -r '.outputs[0].outputs[0].results.message.data.text'\n`; return (
-

Hello World Chat (Text Only)

- +

+ Hello World Chat (Text Only) +

+ setHost(e.target.value)} /> - + setFlowId(e.target.value)} /> - + setInputValue(e.target.value)} /> - + setSessionId(e.target.value)} /> - + setShowApiKey(v => !v)} + onClick={() => setShowApiKey((v) => !v)} > {showApiKey ? "Hide" : "Show"} API Key @@ -128,24 +191,36 @@ export default function HelloWorldCard() { className="mt-2 bg-[#2563eb] hover:bg-[#1d4ed8] transition-colors text-white font-semibold py-3 px-4 rounded-lg disabled:opacity-50 focus:outline-none focus:ring-2 focus:ring-[#2563eb] focus:ring-offset-2 focus:ring-offset-[#19213a]" disabled={loading} > - {loading ? () : "Send"} + {loading ? : "Send"}
- +
); -} \ No newline at end of file +}