Skip to content

fix: enhance API snippet generation with file upload support and consistent authentication#9018

Merged
edwinjosechittilappilly merged 26 commits into
mainfrom
fix/api-snippet-generation
Jul 17, 2025
Merged

fix: enhance API snippet generation with file upload support and consistent authentication#9018
edwinjosechittilappilly merged 26 commits into
mainfrom
fix/api-snippet-generation

Conversation

@namastex888
Copy link
Copy Markdown
Contributor

@namastex888 namastex888 commented Jul 11, 2025

🎯 Summary

This PR enhances the API snippet generation feature to properly handle file uploads and ensures consistent authentication across all code snippets. It addresses several bugs and inconsistencies in the generated API code.

🐛 Problems Fixed

  1. Hardcoded session ID

    • ❌ Before: JavaScript had hardcoded session_id: "user_1", Python/cURL had none
    • ✅ After: All snippets generate proper UUID session IDs dynamically
  2. Inconsistent API key handling

    • ❌ Before: Conditional API key based on auto-login (but ignored after July 9th changes)
    • ✅ After: API key always required, removing unused isAuth parameter
  3. No file upload support

    • ❌ Before: File components in flows were ignored in API snippets
    • ✅ After: Multi-step upload process for all file component types

✨ New Features

1. Multi-Step File Upload Support

When flows contain file components (ChatInput with files, File, or VideoFile), the API modal now generates:

  • Step 1: Upload file(s) commands with individual copy buttons
  • Step 2: Execute flow with uploaded file paths
  • Supports multiple files in a single flow
  • Uses appropriate API versions (v1 for ChatInput, v2 for File/VideoFile)

2. Language-Specific File Upload Implementation

  • Python: Uses requests.post() with files={"file": f} for multipart uploads
  • JavaScript: Native Node.js http module with custom createFormData() helper for multipart/form-data
  • cURL: Direct -F "file=@filename" flag for both Unix and PowerShell variants

Each implementation properly handles the response to extract file paths (file_path from v1, path from v2) and injects them into the flow execution payload.

3. Improved Code Organization

  • Clean separation between upload and execution steps
  • Platform-specific code (Unix vs PowerShell for cURL)
  • Consistent structure across all three languages

🔧 Technical Implementation

New File: detect-file-tweaks.ts (117 lines)

Helper functions to detect and handle file-related tweaks:

  • hasFileTweaks() - Detects any file components
  • getAllChatInputNodeIds() - Gets nodes using v1 upload API
  • getAllFileNodeIds() - Gets nodes using v2 upload API
  • getNonFileTypeTweaks() - Filters out file tweaks for final payload

Updated Files

  1. code-tabs.tsx - Removed unused isAuth parameter, added multi-step UI rendering
  2. get-curl-code.tsx - Added file upload logic with step markers
  3. get-js-api-code.tsx - Native Node.js implementation with form data handling
  4. get-python-api-code.tsx - Python requests with multipart file uploads

📋 Testing

  • ✅ 20 comprehensive unit tests added
  • ✅ Tests cover all file detection scenarios
  • ✅ Tests verify code generation for all languages
  • ✅ All tests passing

🎨 UI/UX Changes

Single-Step Display (No Files)

[Python ▼] [JavaScript] [cURL]     [Copy]
┌─────────────────────────────────────────┐
│ import requests                         │
│ payload = { ... }                       │
│ requests.post(url, json=payload)        │
└─────────────────────────────────────────┘

Multi-Step Display (With Files)

[Python ▼] [JavaScript] [cURL]

Step 1: Upload your files              [Copy]
┌─────────────────────────────────────────┐
│ with open("document.pdf", "rb") as f:   │
│     response = requests.post(...)       │
└─────────────────────────────────────────┘

Step 2: Execute flow with uploaded files [Copy]
┌─────────────────────────────────────────┐
│ payload = { "tweaks": {...} }           │
│ requests.post(url, json=payload)        │
└─────────────────────────────────────────┘

📝 Code Quality Improvements

  • Added JSDoc comments to all functions
  • Consistent error handling across generators
  • Removed code duplication where possible
  • Type-safe TypeScript implementation

⚠️ Important Notes

  • This PR only affects the frontend code generation
  • No changes to backend API behavior
  • Backward compatible - existing flows work unchanged
  • Follows security requirements from commit ef41c71

Testing Instructions

  1. Create a flow with File/ChatInput components
  2. Open API modal (Share → API access)
  3. Verify multi-step code generation
  4. Test copy buttons work independently
  5. Verify non-file flows still show single-step code

Files Changed: 6 files (+604, -289)

Summary by CodeRabbit

  • New Features

    • Added step-aware code display and copy functionality in API code tabs, allowing users to copy segmented code steps individually when available.
    • Enhanced API code generation for Python, JavaScript, and cURL to support multi-step workflows, including file upload steps before executing the main API call.
    • Improved cURL, Python, and JavaScript code snippets to dynamically handle file uploads, with step markers and clear separation between upload and execution steps.
  • Bug Fixes

    • Ensured consistent inclusion of API keys and session IDs in all generated code snippets.
  • Tests

    • Introduced comprehensive tests for API snippet generation utilities, validating file tweak detection and multi-language code generation, including file upload logic.

namastex888 and others added 7 commits July 11, 2025 00:53
Add proper two-step file upload support for API code generation:
- Detect file tweaks in ChatInput (string), File/VideoFile (path/file_path)
- Generate step-based cURL commands with separate copy buttons
- Fix ChatInput to use correct /api/v1/run endpoint with tweaks structure
- Update JavaScript and Python generators with proper endpoints and payloads
- Support dynamic node IDs and processedPayload values
- Implement step parsing UI for cURL with proper formatting

Co-Authored-By: Automagik Genie <genie@namastex.ai>
Replace browser-based FormData approach with native Node.js http module
- Use built-in fs, http, and path modules instead of browser APIs
- Manually construct multipart/form-data payloads
- Add proper error handling and HTTP request helpers
- Support both ChatInput and File/VideoFile upload scenarios
- Maintain authentication header support

Co-Authored-By: Automagik Genie <genie@namastex.ai>
…URL snippets

File/VideoFile components were missing the required payload fields when
generating cURL commands, causing flows to fail execution. Added the missing
fields to match the working pattern used in Chat Input components.

Co-Authored-By: Automagik Genie <genie@namastex.ai>
…cript File component snippets

File/VideoFile components were missing the required payload fields in Python
and JavaScript generators, matching the fix applied to cURL snippets.

Co-Authored-By: Automagik Genie <genie@namastex.ai>
File components require the 'path' field from v2 upload response as an array,
not 'file_id'. Updated all three generators:
- Changed file_id to file_path variable extraction
- Changed "file_id": value to "path": [value] in tweaks
- Updated placeholder text for consistency

This fixes the "No files to process" error in File components.

Co-Authored-By: Automagik Genie <genie@namastex.ai>
- Fixed UI parsing to handle multiple file components correctly
- Consolidated upload steps into single step with multiple commands
- All file components (ChatInput, File, VideoFile) now work additively
- Simplified UI to show only 2 steps: uploads and execution
- Improved scrolling for better debugging experience
- Removed debug console.log statements
…istent authentication

- Add multi-step file upload handling for ChatInput, File, and VideoFile components
- Implement automatic session ID generation using UUIDs across all snippets
- Ensure API key is always required in generated code (Python, JavaScript, cURL)
- Remove unused isAuth parameter from code generation logic
- Add comprehensive unit tests for file detection and code generation
- Support both Unix/Linux and PowerShell platforms for cURL commands
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 11, 2025

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This update introduces multi-step file upload support to the API code generation utilities and the API code tab UI. It adds logic to detect file-related tweaks, generates stepwise code for Python, JavaScript, and cURL that first uploads files and then executes the main API call, and updates the UI to display and allow copying of these segmented code steps.

Changes

File(s) Change Summary
src/frontend/src/modals/apiModal/utils/detect-file-tweaks.ts New utility module to detect file-related tweaks, extract node IDs, and filter non-file tweaks.
src/frontend/src/modals/apiModal/utils/get-curl-code.tsx Enhanced getNewCurlCode to generate multi-step cURL commands for file uploads followed by the main API call, using new file detection utilities and step markers.
src/frontend/src/modals/apiModal/utils/get-js-api-code.tsx Enhanced getNewJsApiCode to generate multi-step Node.js code for file uploads and main API call, using multipart form data and dynamic tweaks modification.
src/frontend/src/modals/apiModal/utils/get-python-api-code.tsx Enhanced getNewPythonApiCode to generate multi-step Python code for file uploads and main API call, handling both v1 and v2 file upload APIs and dynamic tweaks.
src/frontend/src/modals/apiModal/utils/tests/api-snippet-generation.test.ts New test suite covering file tweak detection functions and multi-language API code generation, including scenarios with and without file uploads, and platform-specific cURL code.
src/frontend/src/modals/apiModal/codeTabs/code-tabs.tsx Updated code tab UI to detect step markers in generated code, display segmented steps with individual copy buttons, and manage copy state per step.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant CodeTabUI
    participant CodeGenUtil
    participant FileUploadAPI
    participant MainAPI

    User->>CodeTabUI: Selects API code tab
    CodeTabUI->>CodeGenUtil: Request code for flow (with payload)
    CodeGenUtil->>CodeGenUtil: Detect file tweaks in payload
    alt No file tweaks
        CodeGenUtil->>CodeTabUI: Return single-step code
    else File tweaks present
        CodeGenUtil->>CodeTabUI: Return multi-step code (step markers)
        User->>CodeTabUI: Clicks "Copy Step 1"
        CodeTabUI->>User: Copy file upload step to clipboard
        User->>CodeTabUI: Clicks "Copy Step 2"
        CodeTabUI->>User: Copy main API call step to clipboard
    end
Loading

Suggested labels

enhancement, size:XL, lgtm

Suggested reviewers

  • lucaseduoli
  • ogabrielluiz
✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/api-snippet-generation

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. bug Something isn't working enhancement New feature or request javascript Pull requests that update Javascript code labels Jul 11, 2025
@github-actions github-actions Bot added bug Something isn't working and removed enhancement New feature or request bug Something isn't working labels Jul 11, 2025
@namastex888 namastex888 requested a review from Cristhianzl July 11, 2025 17:54
@github-actions github-actions Bot added bug Something isn't working and removed bug Something isn't working labels Jul 11, 2025
@namastex888 namastex888 requested a review from ogabrielluiz July 11, 2025 17:58
@namastex888 namastex888 removed the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jul 11, 2025
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (3)
src/frontend/src/modals/apiModal/codeTabs/code-tabs.tsx (2)

38-38: Consider extracting the copy feedback timeout as a constant.

The 2-second timeout is hardcoded in multiple places. Consider extracting it for maintainability.

Add a constant at the top of the component:

+const COPY_FEEDBACK_TIMEOUT_MS = 2000;
+
 export default function APITabsComponent() {

Then use it in the timeouts:

-          }, 2000);
+          }, COPY_FEEDBACK_TIMEOUT_MS);

Also applies to: 118-140


209-331: Consider extracting step rendering into separate components for better maintainability.

The current implementation has deeply nested conditionals and duplicated code. Consider refactoring for clarity.

Extract the step rendering logic into separate components:

const StepCodeBlock = ({ 
  step, 
  stepNumber, 
  title, 
  code, 
  language, 
  dark, 
  showLineNumbers = true,
  onCopy,
  isCopied 
}: StepCodeBlockProps) => (
  <div className={stepNumber === 2 ? "flex flex-1 flex-col overflow-hidden" : ""}>
    <h4 className="mb-2 text-sm font-medium">{title}</h4>
    <div className="relative flex h-full w-full">
      <Button
        variant="ghost"
        size="icon"
        onClick={onCopy}
        data-testid={`btn-copy-step${stepNumber}`}
        className="!hover:bg-foreground group absolute right-4 top-2 z-10 select-none"
      >
        {isCopied ? (
          <IconComponent name="Check" className="h-5 w-5 text-muted-foreground" />
        ) : (
          <IconComponent name="Copy" className="!h-5 !w-5 text-muted-foreground" />
        )}
      </Button>
      <SyntaxHighlighter
        showLineNumbers={showLineNumbers}
        wrapLongLines={true}
        language={language}
        style={dark ? oneDark : oneLight}
        className="!mt-0 h-full w-full overflow-scroll !rounded-b-md border border-border text-left !custom-scroll"
      >
        {code}
      </SyntaxHighlighter>
    </div>
  </div>
);

This would simplify the main render logic and reduce duplication.

src/frontend/src/modals/apiModal/utils/get-js-api-code.tsx (1)

92-92: Clarify placeholder filenames with comments.

The generated code uses placeholder filenames that users need to replace with actual file paths. Consider adding comments to make this clearer.

Update the generated code to include clarifying comments:

-        const { payload: chatPayload${index + 1}, boundary: chatBoundary${index + 1} } = createFormData('your_image_${index + 1}.jpg');
+        const { payload: chatPayload${index + 1}, boundary: chatBoundary${index + 1} } = createFormData('your_image_${index + 1}.jpg'); // Replace with your actual file path
-        const { payload: filePayload${index + 1}, boundary: fileBoundary${index + 1} } = createFormData('your_file_${index + 1}.pdf');
+        const { payload: filePayload${index + 1}, boundary: fileBoundary${index + 1} } = createFormData('your_file_${index + 1}.pdf'); // Replace with your actual file path

Also applies to: 124-124

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f8b7be6 and c15d25a.

📒 Files selected for processing (6)
  • src/frontend/src/modals/apiModal/codeTabs/code-tabs.tsx (3 hunks)
  • src/frontend/src/modals/apiModal/utils/__tests__/api-snippet-generation.test.ts (1 hunks)
  • src/frontend/src/modals/apiModal/utils/detect-file-tweaks.ts (1 hunks)
  • src/frontend/src/modals/apiModal/utils/get-curl-code.tsx (4 hunks)
  • src/frontend/src/modals/apiModal/utils/get-js-api-code.tsx (2 hunks)
  • src/frontend/src/modals/apiModal/utils/get-python-api-code.tsx (3 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
src/frontend/**/*.{ts,tsx}

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .cursor/rules/frontend_development.mdc
src/frontend/**/*.{ts,tsx,js,jsx,css,scss}

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .cursor/rules/frontend_development.mdc
src/frontend/src/**/__tests__/**/*.test.{ts,tsx}

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .cursor/rules/frontend_development.mdc
src/frontend/src/**/__tests__/**/*.{test,spec}.{ts,tsx}

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .cursor/rules/frontend_development.mdc
{src/backend/tests/**/*.py,src/frontend/**/*.test.{ts,tsx,js,jsx},src/frontend/**/*.spec.{ts,tsx,js,jsx},tests/**/*.py}

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .cursor/rules/testing.mdc
src/frontend/**/*.@(test|spec).{ts,tsx,js,jsx}

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • .cursor/rules/testing.mdc
🧠 Learnings (5)
src/frontend/src/modals/apiModal/utils/__tests__/api-snippet-generation.test.ts (11)
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to src/frontend/**/*.@(test|spec).{ts,tsx,js,jsx} : Frontend tests should be well-documented with clear descriptions of test purpose and expected behavior.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to {src/backend/tests/**/*.py,src/frontend/**/*.test.{ts,tsx,js,jsx},src/frontend/**/*.spec.{ts,tsx,js,jsx},tests/**/*.py} : Complex test setups should be commented, and mock usage should be documented within the test code.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to {src/backend/tests/**/*.py,src/frontend/**/*.test.{ts,tsx,js,jsx},src/frontend/**/*.spec.{ts,tsx,js,jsx},tests/**/*.py} : Create comprehensive unit tests for all new components.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to src/frontend/**/*.@(test|spec).{ts,tsx,js,jsx} : Frontend tests should mock external dependencies and APIs appropriately.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to src/frontend/**/*.@(test|spec).{ts,tsx,js,jsx} : Frontend tests should validate input/output behavior and component state changes.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to {src/backend/tests/**/*.py,src/frontend/**/*.test.{ts,tsx,js,jsx},src/frontend/**/*.spec.{ts,tsx,js,jsx},tests/**/*.py} : Validate input/output behavior in tests.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to {src/backend/tests/**/*.py,src/frontend/**/*.test.{ts,tsx,js,jsx},src/frontend/**/*.spec.{ts,tsx,js,jsx},tests/**/*.py} : Mock external dependencies appropriately in tests.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to src/frontend/**/*.@(test|spec).{ts,tsx,js,jsx} : Frontend tests should cover both sync and async code paths, including error handling and edge cases.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to {src/backend/tests/**/*.md,tests/**/*.md} : If unit tests are incomplete, create a Markdown file with manual testing steps in the same directory as the unit tests, using the same filename as the component but with a '.md' extension.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to {src/backend/tests/**/*.py,src/frontend/**/*.test.{ts,tsx,js,jsx},src/frontend/**/*.spec.{ts,tsx,js,jsx},tests/**/*.py} : Expected behaviors should be explicitly stated in test docstrings or comments.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to {src/backend/tests/**/*.py,src/frontend/**/*.test.{ts,tsx,js,jsx},src/frontend/**/*.spec.{ts,tsx,js,jsx},tests/**/*.py} : Test both sync and async code paths in components.
src/frontend/src/modals/apiModal/codeTabs/code-tabs.tsx (4)
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/frontend_development.mdc:0-0
Timestamp: 2025-06-30T14:40:29.510Z
Learning: Applies to src/frontend/src/{components,hooks}/**/*.{ts,tsx} : Implement dark mode support in components and hooks where needed.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/frontend_development.mdc:0-0
Timestamp: 2025-06-30T14:40:29.510Z
Learning: Applies to src/frontend/**/*.{ts,tsx} : Use React 18 with TypeScript for all UI components and frontend logic.
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/frontend_development.mdc:0-0
Timestamp: 2025-06-23T12:46:42.048Z
Learning: Use Zustand for state management in React components within the frontend; stores should expose both state and setter functions, and be imported via hooks (e.g., useMyStore).
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/frontend_development.mdc:0-0
Timestamp: 2025-06-23T12:46:42.048Z
Learning: Custom React Flow node types should be implemented as memoized components, using Handle components for connection points and supporting optional icons and labels.
src/frontend/src/modals/apiModal/utils/get-python-api-code.tsx (1)
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-06-30T14:41:58.849Z
Learning: Applies to {src/backend/tests/**/*.py,tests/**/*.py} : Use predefined JSON flows and utility functions for flow testing (e.g., 'create_flow', 'build_flow', 'get_build_events', 'consume_and_assert_stream').
src/frontend/src/modals/apiModal/utils/detect-file-tweaks.ts (1)
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/frontend_development.mdc:0-0
Timestamp: 2025-06-30T14:40:29.510Z
Learning: Applies to src/frontend/src/{components,hooks}/**/*.{ts,tsx} : Implement dark mode support in components and hooks where needed.
src/frontend/src/modals/apiModal/utils/get-js-api-code.tsx (1)
Learnt from: ogabrielluiz
PR: langflow-ai/langflow#0
File: :0-0
Timestamp: 2025-06-26T19:43:18.260Z
Learning: In langflow custom components, the `module_name` parameter is now propagated through template building functions to add module metadata and code hashes to frontend nodes for better component tracking and debugging.
🧬 Code Graph Analysis (1)
src/frontend/src/modals/apiModal/utils/get-curl-code.tsx (1)
src/frontend/src/modals/apiModal/utils/detect-file-tweaks.ts (5)
  • hasFileTweaks (2-18)
  • hasChatInputFiles (21-29)
  • getAllChatInputNodeIds (61-72)
  • getAllFileNodeIds (75-92)
  • getNonFileTypeTweaks (95-117)
🪛 Gitleaks (8.26.0)
src/frontend/src/modals/apiModal/utils/get-curl-code.tsx

143-146: Discovered a potential authorization token provided in a curl command header, which could compromise the curl accessed resource.

(curl-auth-header)


164-167: Discovered a potential authorization token provided in a curl command header, which could compromise the curl accessed resource.

(curl-auth-header)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: autofix
🔇 Additional comments (11)
src/frontend/src/modals/apiModal/utils/detect-file-tweaks.ts (3)

1-18: LGTM! Well-structured file detection utility.

The function correctly identifies all file-related fields with proper type checking and early returns for performance.


20-29: LGTM! Clean functional implementation.

Good use of Array.some() for a concise and readable check.


31-117: LGTM! Consistent and robust implementation across all utility functions.

All functions follow a consistent pattern with proper type checking and edge case handling. The separation of concerns between different file types (ChatInput vs File/VideoFile) is well-designed.

src/frontend/src/modals/apiModal/codeTabs/code-tabs.tsx (1)

142-156: LGTM! Clean step parsing implementation.

The regex-based parsing correctly extracts step markers and handles both multi-step and single-step code.

src/frontend/src/modals/apiModal/utils/__tests__/api-snippet-generation.test.ts (1)

1-275: Excellent test coverage! Well-structured and comprehensive test suite.

The tests cover all utility functions and code generation scenarios with clear descriptions and good edge case coverage. The organization using describe blocks makes the test suite easy to navigate.

src/frontend/src/modals/apiModal/utils/get-python-api-code.tsx (2)

1-68: LGTM! Clean separation of file and non-file upload logic.

The function properly detects file uploads and delegates to appropriate code generation paths.


70-131: LGTM! Comprehensive file upload handling for different component types.

The code correctly handles both ChatInput (v1 API) and File/VideoFile (v2 API) uploads with appropriate path transformations.

src/frontend/src/modals/apiModal/utils/get-curl-code.tsx (3)

1-67: LGTM! Well-documented function with proper platform detection.

The function signature and platform detection logic are clear and comprehensive.


73-116: LGTM! Platform-specific implementations are correct.

Good handling of session ID generation differences between Unix and PowerShell.


195-236: LGTM! Well-structured multi-step output with clear markers.

The step markers enable proper UI parsing and the platform-specific formatting is maintained. The API key placeholders are appropriate for example code.

src/frontend/src/modals/apiModal/utils/get-js-api-code.tsx (1)

190-252: Well-structured async code with proper error handling.

The generated Node.js code has excellent structure with:

  • Proper helper functions for multipart form data and HTTP requests
  • Comprehensive error handling with try-catch
  • Correct Content-Length calculations for both Buffer and JSON payloads
  • Clear step-by-step execution flow

Comment thread src/frontend/src/modals/apiModal/utils/get-python-api-code.tsx
Comment thread src/frontend/src/modals/apiModal/utils/get-curl-code.tsx
Comment thread src/frontend/src/modals/apiModal/utils/get-js-api-code.tsx Outdated
Comment thread src/frontend/src/modals/apiModal/utils/get-js-api-code.tsx Outdated
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jul 11, 2025
@github-actions github-actions Bot added bug Something isn't working and removed bug Something isn't working labels Jul 11, 2025
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jul 17, 2025

Tip

For best results, initiate chat on the files or code changes.

A summary of the changes CodeRabbit can apply:

  • Correct syntax errors and improve the cURL code generation in get-curl-code.tsx by fixing template literals, removing duplicate variables, adding clear Postman usage instructions when the API key is excluded, and ensuring consistent formatting, thereby enhancing the includeApiKey feature already present in the code-tabs component.

  • Enhance the cURL code generation file (src/frontend/src/modals/apiModal/utils/get-curl-code.tsx) by fixing syntax errors, removing duplicate declarations, and adding clear, detailed Postman usage instructions with an optional API key toggle to improve user guidance and compatibility.

  • Enhance API snippet generators by adding Postman-specific guidance comments about removing or replacing API keys in cURL, Python, and JavaScript code, and update corresponding tests to verify inclusion of these usage tips and API key handling.

  • ✅ Create PR with these edits
  • 📌 Create commit in current branch
  • 📋 Get copyable edits

@ogabrielluiz
Copy link
Copy Markdown
Contributor

Quick observation while testing. "session_id": "$(uuidgen || cat /proc/sys/kernel/random/uuid)" in curl is not working as expected it is not giving a random uuid.

The python code works but idfeally we need to have a better way to show case the api key example how we show it on mcp json, may be a similar methodology.

Curl script works in terminal, but when tried with postman often it gives error:

{
    "detail": [
        {
            "type": "bool_parsing",
            "loc": [
                "query",
                "stream"
            ],
            "msg": "Input should be a valid boolean, unable to interpret input",
            "input": "false "
        }
    ]
}

Yeah. I was questioning this as well. I'll probably remove it

- Replace dynamic session_id generation with a placeholder "YOUR_SESSION_ID_HERE" for both Unix and PowerShell environments.
- Update tests to reflect the change, ensuring they check for the new session_id placeholder instead of UUID generation commands.
- Enhance clarity in generated curl commands and maintain consistency across different platforms.
@github-actions github-actions Bot added bug Something isn't working and removed bug Something isn't working labels Jul 17, 2025
@github-actions github-actions Bot added bug Something isn't working and removed bug Something isn't working labels Jul 17, 2025
Copy link
Copy Markdown
Collaborator

@edwinjosechittilappilly edwinjosechittilappilly left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@github-actions github-actions Bot added the lgtm This PR has been approved by a maintainer label Jul 17, 2025
…y and maintainability

🔧 (frontend): refactor codeTabs component to add support for auto login feature
🔧 (frontend): refactor api-snippet-generation test to include tests for API key authentication
🔧 (frontend): refactor get-curl-code, get-js-api-code, and get-python-api-code to conditionally include API key based on shouldDisplayApiKey parameter
@github-actions github-actions Bot added bug Something isn't working and removed bug Something isn't working labels Jul 17, 2025
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Jul 17, 2025

Frontend Unit Test Coverage Report

Coverage Summary

Lines Statements Branches Functions
Coverage: 82%
81.44% (373/458) 64.82% (223/344) 67.69% (44/65)

Unit Test Results

Tests Skipped Failures Errors Time
72 0 💤 0 ❌ 0 🔥 2.914s ⏱️

@edwinjosechittilappilly edwinjosechittilappilly added this pull request to the merge queue Jul 17, 2025
@edwinjosechittilappilly edwinjosechittilappilly removed this pull request from the merge queue due to a manual request Jul 17, 2025
@github-actions github-actions Bot added bug Something isn't working and removed bug Something isn't working labels Jul 17, 2025
@edwinjosechittilappilly edwinjosechittilappilly added this pull request to the merge queue Jul 17, 2025
Merged via the queue into main with commit d9f3ced Jul 17, 2025
55 checks passed
@edwinjosechittilappilly edwinjosechittilappilly deleted the fix/api-snippet-generation branch July 17, 2025 23:47
@mendonk mendonk added the feature New features and enhancements label Jul 23, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working community Pull Request from an external contributor feature New features and enhancements javascript Pull requests that update Javascript code lgtm This PR has been approved by a maintainer size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants