-
Notifications
You must be signed in to change notification settings - Fork 8.2k
feat: Add functionality to expand compact flow format #10785
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
|
Important Review skippedAuto incremental reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the WalkthroughThis change introduces a new API endpoint (POST /flows/expand/) that expands compact AI-generated flow representations into full Langflow-compatible flows. It includes a new processing module with data models, utility functions for node and edge expansion, and comprehensive unit/integration tests. Changes
Sequence DiagramsequenceDiagram
participant Client
participant API as API Endpoint<br/>/flows/expand/
participant Auth as Authentication
participant Cache as Component Cache
participant Expand as expand_compact_flow
participant Response
Client->>API: POST compact_data
API->>Auth: get_current_active_user
Auth-->>API: authenticated user
API->>Cache: get_and_cache_all_types_dict
alt Cache needs load
Cache-->>Cache: load all component types
end
Cache-->>API: all_types_dict
API->>Expand: expand_compact_flow(compact_data, all_types_dict)
Expand->>Expand: _get_flat_components (flatten templates)
Expand->>Expand: _expand_node (for each node)<br/>merge values & templates
Expand->>Expand: _expand_edge (for each edge)<br/>encode handles
alt Success
Expand-->>API: expanded flow dict
API-->>Response: 200 OK {nodes, edges}
else ValueError (invalid component)
Expand-->>API: ValueError
API-->>Response: 400 Bad Request
else Other Error
API-->>Response: 500 Internal Server Error
end
Response-->>Client: response
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Pre-merge checks and finishing touchesImportant Pre-merge checks failedPlease resolve all errors before merging. Addressing warnings is optional. ❌ Failed checks (1 error, 3 warnings)
✅ Passed checks (3 passed)
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. Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🧹 Nitpick comments (1)
src/backend/tests/unit/test_expand_flow.py (1)
554-565: Consider strengthening the success test assertion.The test accepts both
200 OKand400 Bad Requestas valid outcomes, which weakens the test's ability to catch regressions. Consider either:
- Mocking
component_cache.all_types_dictwithSAMPLE_COMPONENTSto ensure deterministic behavior- Adding a docstring explaining why both statuses are acceptable
Example approach with mocking:
@pytest.mark.asyncio async def test_expand_flow_endpoint_success(self, client: AsyncClient, logged_in_headers, monkeypatch): """Test successful flow expansion with mocked components.""" from lfx.interface.components import component_cache monkeypatch.setattr(component_cache, "all_types_dict", SAMPLE_COMPONENTS) compact_data = { "nodes": [{"id": "1", "type": "ChatInput"}], "edges": [], } response = await client.post("api/v1/flows/expand/", json=compact_data, headers=logged_in_headers) assert response.status_code == status.HTTP_200_OK
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
src/backend/base/langflow/api/v1/flows.py(2 hunks)src/backend/base/langflow/processing/expand_flow.py(1 hunks)src/backend/tests/unit/test_expand_flow.py(1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
src/backend/**/*.py
📄 CodeRabbit inference engine (.cursor/rules/backend_development.mdc)
src/backend/**/*.py: Use FastAPI async patterns withawaitfor async operations in component execution methods
Useasyncio.create_task()for background tasks and implement proper cleanup with try/except forasyncio.CancelledError
Usequeue.put_nowait()for non-blocking queue operations andasyncio.wait_for()with timeouts for controlled get operations
Files:
src/backend/base/langflow/api/v1/flows.pysrc/backend/tests/unit/test_expand_flow.pysrc/backend/base/langflow/processing/expand_flow.py
src/backend/base/langflow/api/**/*.py
📄 CodeRabbit inference engine (.cursor/rules/backend_development.mdc)
Backend API endpoints should be organized by version (v1/, v2/) under
src/backend/base/langflow/api/with specific modules for features (chat.py, flows.py, users.py, etc.)
Files:
src/backend/base/langflow/api/v1/flows.py
src/backend/tests/**/*.py
📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)
src/backend/tests/**/*.py: Place backend unit tests insrc/backend/tests/directory, component tests insrc/backend/tests/unit/components/organized by component subdirectory, and integration tests accessible viamake integration_tests
Use same filename as component with appropriate test prefix/suffix (e.g.,my_component.py→test_my_component.py)
Use theclientfixture (FastAPI Test Client) defined insrc/backend/tests/conftest.pyfor API tests; it provides an asynchttpx.AsyncClientwith automatic in-memory SQLite database and mocked environment variables. Skip client creation by marking test with@pytest.mark.noclient
Inherit from the correctComponentTestBasefamily class located insrc/backend/tests/base.pybased on API access needs:ComponentTestBase(no API),ComponentTestBaseWithClient(needs API), orComponentTestBaseWithoutClient(pure logic). Provide three required fixtures:component_class,default_kwargs, andfile_names_mapping
Create comprehensive unit tests for all new backend components. If unit tests are incomplete, create a corresponding Markdown file documenting manual testing steps and expected outcomes
Test both sync and async code paths, mock external dependencies appropriately, test error handling and edge cases, validate input/output behavior, and test component initialization and configuration
Use@pytest.mark.asynciodecorator for async component tests and ensure async methods are properly awaited
Test background tasks usingasyncio.create_task()and verify completion withasyncio.wait_for()with appropriate timeout constraints
Test queue operations using non-blockingqueue.put_nowait()andasyncio.wait_for(queue.get(), timeout=...)to verify queue processing without blocking
Use@pytest.mark.no_blockbustermarker to skip the blockbuster plugin in specific tests
For database tests that may fail in batch runs, run them sequentially usinguv run pytest src/backend/tests/unit/test_database.pyr...
Files:
src/backend/tests/unit/test_expand_flow.py
**/{test_*.py,*.test.ts,*.test.tsx}
📄 CodeRabbit inference engine (Custom checks)
Check that test files follow the project's naming conventions (test_*.py for backend, *.test.ts for frontend)
Files:
src/backend/tests/unit/test_expand_flow.py
**/test_*.py
📄 CodeRabbit inference engine (Custom checks)
**/test_*.py: Backend tests should follow pytest structure with proper test_*.py naming
For async functions, ensure proper async testing patterns are used with pytest for backend
Files:
src/backend/tests/unit/test_expand_flow.py
🧠 Learnings (13)
📓 Common learnings
Learnt from: ogabrielluiz
Repo: langflow-ai/langflow PR: 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.
📚 Learning: 2025-11-24T19:46:09.104Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/backend_development.mdc:0-0
Timestamp: 2025-11-24T19:46:09.104Z
Learning: Applies to src/backend/base/langflow/api/**/*.py : Backend API endpoints should be organized by version (v1/, v2/) under `src/backend/base/langflow/api/` with specific modules for features (chat.py, flows.py, users.py, etc.)
Applied to files:
src/backend/base/langflow/api/v1/flows.py
📚 Learning: 2025-11-24T19:47:28.997Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-24T19:47:28.997Z
Learning: Applies to src/backend/tests/**/*.py : Test component versioning and backward compatibility using `file_names_mapping` fixture with `VersionComponentMapping` objects mapping component files across Langflow versions
Applied to files:
src/backend/tests/unit/test_expand_flow.py
📚 Learning: 2025-11-24T19:47:28.997Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-24T19:47:28.997Z
Learning: Applies to src/backend/tests/**/*.py : Use predefined JSON flows and utility functions from `tests.unit.build_utils` (create_flow, build_flow, get_build_events, consume_and_assert_stream) for flow execution testing
Applied to files:
src/backend/tests/unit/test_expand_flow.py
📚 Learning: 2025-11-24T19:47:28.997Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-24T19:47:28.997Z
Learning: Applies to src/backend/tests/**/*.py : Create comprehensive unit tests for all new backend components. If unit tests are incomplete, create a corresponding Markdown file documenting manual testing steps and expected outcomes
Applied to files:
src/backend/tests/unit/test_expand_flow.py
📚 Learning: 2025-11-24T19:47:28.997Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-24T19:47:28.997Z
Learning: Applies to src/backend/tests/**/*.py : Test Langflow REST API endpoints using the `client` fixture with appropriate HTTP methods (GET, POST, etc.), headers (logged_in_headers), and payload validation
Applied to files:
src/backend/tests/unit/test_expand_flow.py
📚 Learning: 2025-11-24T19:47:28.997Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-24T19:47:28.997Z
Learning: Applies to src/backend/tests/**/*.py : Test both sync and async code paths, mock external dependencies appropriately, test error handling and edge cases, validate input/output behavior, and test component initialization and configuration
Applied to files:
src/backend/tests/unit/test_expand_flow.py
📚 Learning: 2025-11-24T19:47:28.997Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-24T19:47:28.997Z
Learning: Applies to src/backend/tests/**/*.py : Test component build config updates by calling `to_frontend_node()` to get the node template, then calling `update_build_config()` to apply configuration changes
Applied to files:
src/backend/tests/unit/test_expand_flow.py
📚 Learning: 2025-11-24T19:47:28.997Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-11-24T19:47:28.997Z
Learning: Applies to src/backend/tests/**/*.py : Test Langflow's `Message` objects using `langflow.schema.message.Message` and validate text, sender, sender_name, session_id, files, and properties attributes
Applied to files:
src/backend/tests/unit/test_expand_flow.py
📚 Learning: 2025-11-24T19:46:09.104Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/backend_development.mdc:0-0
Timestamp: 2025-11-24T19:46:09.104Z
Learning: Applies to src/backend/base/langflow/components/**/*.py : Add new components to the appropriate subdirectory under `src/backend/base/langflow/components/` (agents/, data/, embeddings/, input_output/, models/, processing/, prompts/, tools/, or vectorstores/)
Applied to files:
src/backend/tests/unit/test_expand_flow.pysrc/backend/base/langflow/processing/expand_flow.py
📚 Learning: 2025-11-24T19:46:09.104Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/backend_development.mdc:0-0
Timestamp: 2025-11-24T19:46:09.104Z
Learning: Applies to tests/unit/**/*.py : Database and flow integration tests should use helper functions from `tests.unit.build_utils` such as `create_flow`, `build_flow`, and `get_build_events`
Applied to files:
src/backend/tests/unit/test_expand_flow.py
📚 Learning: 2025-11-24T19:46:09.104Z
Learnt from: CR
Repo: langflow-ai/langflow PR: 0
File: .cursor/rules/backend_development.mdc:0-0
Timestamp: 2025-11-24T19:46:09.104Z
Learning: Applies to src/backend/base/langflow/components/**/__init__.py : Update `__init__.py` with alphabetically sorted imports when adding new components
Applied to files:
src/backend/tests/unit/test_expand_flow.pysrc/backend/base/langflow/processing/expand_flow.py
📚 Learning: 2025-06-26T19:43:18.260Z
Learnt from: ogabrielluiz
Repo: langflow-ai/langflow PR: 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.
Applied to files:
src/backend/base/langflow/processing/expand_flow.py
🧬 Code graph analysis (2)
src/backend/tests/unit/test_expand_flow.py (1)
src/backend/base/langflow/processing/expand_flow.py (6)
CompactEdge(26-32)CompactNode(15-23)_expand_edge(154-235)_expand_node(52-111)_get_flat_components(42-49)expand_compact_flow(238-283)
src/backend/base/langflow/processing/expand_flow.py (1)
src/lfx/src/lfx/utils/util.py (1)
escape_json_dump(617-618)
⏰ 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). (18)
- GitHub Check: Lint Backend / Run Mypy (3.13)
- GitHub Check: Run Backend Tests / LFX Tests - Python 3.10
- GitHub Check: Lint Backend / Run Mypy (3.11)
- GitHub Check: Lint Backend / Run Mypy (3.10)
- GitHub Check: Lint Backend / Run Mypy (3.12)
- GitHub Check: Test Docker Images / Test docker images
- GitHub Check: Run Frontend Tests / Determine Test Suites and Shard Distribution
- GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 5
- GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 3
- GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 2
- GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 4
- GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 1
- GitHub Check: Run Backend Tests / Integration Tests - Python 3.10
- GitHub Check: Test Starter Templates
- GitHub Check: Update Component Index
- GitHub Check: Run Ruff Check and Format
- GitHub Check: Update Starter Projects
- GitHub Check: Optimize new Python code in this PR
🔇 Additional comments (6)
src/backend/base/langflow/api/v1/flows.py (1)
592-637: LGTM! New endpoint follows established patterns.The endpoint correctly:
- Requires authentication via
Depends(get_current_active_user)- Handles cache initialization defensively
- Returns appropriate HTTP status codes (400 for ValueError, 500 for other exceptions)
One minor observation: the endpoint returns a raw
dictwithout aresponse_model. This is acceptable for flexibility with AI-generated flows, but consider adding a response model if schema validation becomes important.src/backend/base/langflow/processing/expand_flow.py (5)
15-24: LGTM! Clean Pydantic models for compact flow representation.The
CompactNodemodel is well-designed with sensible defaults and clear documentation of theeditedflag's contract.
93-101: Verify consistency in value assignment for non-dict template fields.When
template[field_name]is not a dict (line 97-98), the code assignsfield_valuedirectly, but when the field doesn't exist (line 100-101), it wraps it as{"value": field_value}. This inconsistency could cause issues if downstream code expects all template fields to have a consistent structure.Is this intentional? If template fields should always be dicts with a
valuekey, consider:if field_name in template: if isinstance(template[field_name], dict): template[field_name]["value"] = field_value else: - template[field_name] = field_value + template[field_name] = {"value": field_value} else: # Add as new field if not in template template[field_name] = {"value": field_value}
180-190: Good defensive fallback tobase_classeswhen output not found.The logic correctly handles cases where the output name doesn't match any defined outputs by falling back to
base_classes. This is a reasonable design choice for AI-generated flows that might use non-standard output names.
114-122: Good reuse of existingescape_json_dumputility.Using the existing utility from
lfx.utils.utilmaintains consistency with other parts of the codebase that generate handle strings.
238-283: LGTM! Clean orchestration of the expansion process.The function follows a clear flow:
- Parse and validate input with Pydantic
- Flatten component lookup
- Expand nodes first (required for edge references)
- Expand edges
- Return the full structure
The docstring with example input is helpful for understanding the expected format.
Codecov Report❌ Patch coverage is
❌ Your project check has failed because the head coverage (40.04%) is below the target coverage (60.00%). You can increase the head coverage or adjust the target coverage. Additional details and impacted files@@ Coverage Diff @@
## main #10785 +/- ##
==========================================
+ Coverage 32.39% 32.48% +0.09%
==========================================
Files 1368 1369 +1
Lines 63414 63516 +102
Branches 9373 9373
==========================================
+ Hits 20541 20633 +92
- Misses 41840 41850 +10
Partials 1033 1033
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
…code-pre-built-component`) (#10786) Co-authored-by: codeflash-ai[bot] <148906541+codeflash-ai[bot]@users.noreply.github.com>
|
This PR is now faster! 🚀 @ogabrielluiz accepted my optimizations from: |
|
This PR is now faster! 🚀 codeflash-ai[bot] accepted my code suggestion above. |
Introduce an endpoint to expand a compact flow format into a full flow format, along with unit tests to ensure the functionality works as intended. This enhancement allows for better integration with AI-generated flows.
Summary by CodeRabbit
New Features
Tests
✏️ Tip: You can customize this high-level summary in your review settings.