Skip to content

Pr 9735#10265

Closed
HimavarshaVS wants to merge 16 commits into
mainfrom
pr-9735
Closed

Pr 9735#10265
HimavarshaVS wants to merge 16 commits into
mainfrom
pr-9735

Conversation

@HimavarshaVS
Copy link
Copy Markdown
Collaborator

@HimavarshaVS HimavarshaVS commented Oct 14, 2025

@coderabbitai

Summary by CodeRabbit

  • New Features
    • Added CometAPI component to use OpenAI-compatible models with model discovery, selection, and parameters (API key, temperature, max tokens, seed, JSON mode). Supports outputting a model or response and works with existing flows. COMETAPI_KEY env var supported.
  • UI
    • Added CometAPI icon and sidebar entry in Bundles.
  • Documentation
    • Introduced CometAPI bundle page with setup steps, parameter reference, and related links.
  • Tests
    • Added comprehensive unit and integration tests for CometAPI component and constants.

tensornull and others added 15 commits September 7, 2025 13:11
- Updated sidebars to include CometAPI bundle.
- Enhanced compatibility modules to support CometAPI constants.
- Implemented lazy loading for CometAPI icons in the frontend.
- Added CometAPI to the list of sidebar bundles in styleUtils.
- Introduced CometAPI documentation page detailing usage and parameters.
- Created CometAPI icon components for consistent UI representation.
- Defined CometAPI model constants for available models.
- Developed CometAPI component for language model integration with input handling.
- Implemented model fetching logic from CometAPI API.
Co-authored-by: April I. Murphy <36110273+aimurphy@users.noreply.github.com>
Co-authored-by: April I. Murphy <36110273+aimurphy@users.noreply.github.com>
Co-authored-by: April I. Murphy <36110273+aimurphy@users.noreply.github.com>
Co-authored-by: April I. Murphy <36110273+aimurphy@users.noreply.github.com>
Co-authored-by: April I. Murphy <36110273+aimurphy@users.noreply.github.com>
Co-authored-by: April I. Murphy <36110273+aimurphy@users.noreply.github.com>
Co-authored-by: April I. Murphy <36110273+aimurphy@users.noreply.github.com>
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Oct 14, 2025

Walkthrough

Adds a new CometAPI bundle: component implementation, constants, lazy import, environment variable, docs, sidebar entry, frontend icon and sidebar mapping, plus extensive unit and integration tests. Also adds a backward-compatibility import mapping for constants and updates lazy icon imports.

Changes

Cohort / File(s) Summary
Documentation
docs/docs/Components/bundles-cometapi.mdx, docs/sidebars.js
New MDX page for CometAPI bundle and sidebar entry updated from composio to cometapi.
Backend compatibility mapping
src/backend/base/langflow/__init__.py
Adds forward-import alias for langflow.base.models.cometapi_constants to lfx.base.models.cometapi_constants.
LFX CometAPI component
src/lfx/src/lfx/components/cometapi/__init__.py, src/lfx/src/lfx/components/cometapi/cometapi.py
Introduces CometAPIComponent with model fetching, dynamic config updates, and model construction (including JSON mode). Lazy-loads component via __getattr__.
Constants for fallback models
src/lfx/src/lfx/base/models/cometapi_constants.py
Adds COMETAPI_MODELS and alias MODEL_NAMES for default/fallback model identifiers.
Settings/env support
src/lfx/src/lfx/services/settings/constants.py
Adds COMETAPI_KEY to environment variable retrieval list.
Frontend icon and UI mapping
src/frontend/src/icons/CometAPI/cometapi.jsx, src/frontend/src/icons/CometAPI/index.tsx, src/frontend/src/icons/lazyIconImports.ts, src/frontend/src/utils/styleUtils.ts
Adds CometAPI SVG icon, forwardRef wrapper, lazy icon import mapping, and sidebar bundle entry with icon wiring.
Unit tests
src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py, src/backend/tests/unit/components/bundles/cometapi/test_cometapi_constants.py, src/backend/tests/unit/components/bundles/cometapi/__init__.py
Tests component behavior, model fetching, JSON mode, error handling, inputs, and constants list validity.
Integration tests
src/backend/tests/integration/components/bundles/cometapi/test_cometapi_integration.py, src/backend/tests/integration/components/bundles/cometapi/__init__.py
Integration-style tests with mocked requests/OpenAI, config updates, fallbacks, optional real-API checks.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant UI as UI (Flow Builder)
  participant Comp as CometAPIComponent
  participant API as CometAPI REST
  participant Const as MODEL_NAMES (fallback)

  User->>UI: Open CometAPI bundle config
  UI->>Comp: update_build_config(field=model_name)
  alt Has API key
    Comp->>API: GET /v1/models (Authorization)
    alt 200 OK with JSON
      API-->>Comp: List of models
      Comp-->>UI: Populate dropdown with fetched models
    else Error/invalid JSON
      API--x Comp: Error
      Comp->>Const: Read fallback list
      Comp-->>UI: Populate dropdown with fallback models + status error
    end
  else No API key
    Comp->>Const: Read fallback list
    Comp-->>UI: Populate dropdown with fallback models
  end
Loading
sequenceDiagram
  autonumber
  actor User
  participant Flow as Flow Runtime
  participant Comp as CometAPIComponent
  participant LLM as ChatOpenAI (OpenAI-compatible)

  User->>Flow: Run node
  Flow->>Comp: build_model()
  Comp->>LLM: new ChatOpenAI({base_url, api_key, model, temperature, max_tokens, seed, streaming, model_kwargs})
  alt JSON mode enabled
    Comp->>LLM: bind({response_format: {"type":"json_object"}})
    LLM-->>Comp: Bound model
  else JSON mode disabled
    LLM-->>Comp: Model instance
  end
  Comp-->>Flow: Return LanguageModel
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

enhancement, javascript, size:L, lgtm

Suggested reviewers

  • edwinjosechittilappilly
  • Cristhianzl
  • ogabrielluiz

Pre-merge checks and finishing touches

❌ Failed checks (1 error, 3 warnings)
Check name Status Explanation Resolution
Test Coverage For New Implementations ❌ Error The PR adds a new CometAPI icon component, lazy import mapping, and sidebar bundle entry in the frontend but no corresponding frontend tests reference or validate the new CometAPI functionality, and existing backend tests cover the backend changes. This means new frontend code lacks test coverage. Add frontend unit tests for the new SvgCometAPI and CometAPIIcon components and include assertions that the lazyIconsMapping and SIDEBAR_BUNDLES entries for CometAPI are correctly loaded and rendered.
Title Check ⚠️ Warning The title “Pr 9735” is generic and fails to summarize any of the significant changes introduced in this pull request, such as the addition of the CometAPIComponent, its documentation, tests, constants, and frontend icon integration. Please update the pull request title to a concise, descriptive sentence—for example, “Add CometAPI bundle component with documentation, tests, constants, and icon support”—so that it clearly reflects the primary changes.
Test Quality And Coverage ⚠️ Warning
Excessive Mock Usage Warning ⚠️ Warning
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 83.72% which is sufficient. The required threshold is 80.00%.
Test File Naming And Structure ✅ Passed All backend tests in this PR are correctly named with the test_ prefix and placed under the appropriate unit and integration directories. The integration tests reside under tests/integration and use descriptive method names that clearly indicate their purpose. Pytest fixtures handle setup cleanly, and the test suite includes both positive and negative scenarios, including error and fallback cases. No frontend tests were introduced in this PR.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch pr-9735

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@sonarqubecloud
Copy link
Copy Markdown

@github-actions
Copy link
Copy Markdown
Contributor

Frontend Unit Test Coverage Report

Coverage Summary

Lines Statements Branches Functions
Coverage: 11%
10.94% (2890/26415) 4.56% (926/20272) 6.49% (372/5725)

Unit Test Results

Tests Skipped Failures Errors Time
1200 0 💤 0 ❌ 0 🔥 13.863s ⏱️

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Oct 14, 2025

Build successful! ✅
Deploying docs draft.
Deploy successful! View draft

@codecov
Copy link
Copy Markdown

codecov Bot commented Oct 14, 2025

Codecov Report

❌ Patch coverage is 0% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 24.14%. Comparing base (42c7e08) to head (c8136f7).
⚠️ Report is 117 commits behind head on main.

Files with missing lines Patch % Lines
src/frontend/src/icons/CometAPI/index.tsx 0.00% 4 Missing ⚠️
src/frontend/src/icons/lazyIconImports.ts 0.00% 1 Missing ⚠️

❌ Your patch status has failed because the patch coverage (0.00%) is below the target coverage (40.00%). You can increase the patch coverage or adjust the target coverage.
❌ Your project status has failed because the head coverage (47.08%) is below the target coverage (55.00%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main   #10265      +/-   ##
==========================================
- Coverage   24.15%   24.14%   -0.02%     
==========================================
  Files        1088     1090       +2     
  Lines       40083    40106      +23     
  Branches     5546     5550       +4     
==========================================
  Hits         9682     9682              
- Misses      30230    30253      +23     
  Partials      171      171              
Flag Coverage Δ
frontend 10.09% <0.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
src/frontend/src/utils/styleUtils.ts 49.12% <ø> (ø)
src/frontend/src/icons/lazyIconImports.ts 0.68% <0.00%> (-0.01%) ⬇️
src/frontend/src/icons/CometAPI/index.tsx 0.00% <0.00%> (ø)

... and 8 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

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 (12)
src/backend/tests/unit/components/bundles/cometapi/test_cometapi_constants.py (1)

35-40: Consider aligning the parametrized test with specific models.

The parametrized test at line 36 includes "grok-3" which is not present in the expected_models list at line 26. Consider whether:

  1. "grok-3" should be added to expected_models if it's a critical model
  2. The parametrized test should only include models from expected_models for consistency

This helps maintain consistency between the two test approaches and clarifies which models are considered essential.

src/backend/base/langflow/__init__.py (1)

60-115: Add explicit mapping for langflow.components.cometapi for import parity.

Without a direct map, from langflow.components.cometapi import CometAPIComponent may fail. Add a module mapping entry to ensure full backward compatibility.

         "langflow.components.helpers.store_message": "lfx.components.helpers.store_message",
+        # CometAPI component package
+        "langflow.components.cometapi": "lfx.components.cometapi",
src/frontend/src/icons/CometAPI/cometapi.jsx (1)

1-31: Use TypeScript for icons and type the isDark prop.

Frontend guidelines require React + TypeScript. Convert to TSX and add a typed props interface.

-const SvgCometAPI = ({ isDark = false, ...props }) => (
+import type { SVGProps } from "react";
+type Props = SVGProps<SVGSVGElement> & { isDark?: boolean };
+const SvgCometAPI = ({ isDark = false, ...props }: Props) => (

Optional: extend isDark color handling to all paths for consistent dark-mode contrast.
Run: make format_frontend && make lint

src/lfx/src/lfx/components/cometapi/__init__.py (1)

17-28: Guard against __spec__ being None in some import contexts.

Accessing __spec__.parent can fail if __spec__ is None. Fallback to __package__.

-    try:
-        result = import_mod(attr_name, _dynamic_imports[attr_name], __spec__.parent)
+    try:
+        parent = (__spec__.parent if __spec__ is not None else __package__)  # type: ignore[union-attr]
+        result = import_mod(attr_name, _dynamic_imports[attr_name], parent)
src/lfx/src/lfx/components/cometapi/cometapi.py (2)

31-88: Remove or use the app_name input.

app_name is not used in requests or model construction. Either pass it via headers/params where applicable or remove it to avoid user confusion.


90-100: De-duplicate base URL and consider a module-level constant.

Avoid repeating the CometAPI base URL in two places.

+# Module-level
+BASE_URL = "https://api.cometapi.com/v1"
@@
-        base_url = "https://api.cometapi.com/v1"
-        url = f"{base_url}/models"
+        url = f"{BASE_URL}/models"
@@
-                base_url="https://api.cometapi.com/v1",
+                base_url=BASE_URL,

Also applies to: 149-158

src/backend/tests/integration/components/bundles/cometapi/test_cometapi_integration.py (4)

51-52: Patch where used: patch requests at module import site

Patch the requests.get used inside the component module to avoid cross-test interference.

Apply this diff:

-    @patch("requests.get")
+    @patch("lfx.components.cometapi.cometapi.requests.get")

135-136: Same here: patch requests.get at import site

Align with best practice; patch the symbol where it’s imported.

Apply this diff:

-    @patch("requests.get")
+    @patch("lfx.components.cometapi.cometapi.requests.get")

102-104: Correct the comment: streaming defaults to False

streaming is set via bool(self.stream), so default is False, not None.

Apply this diff:

-        # streaming defaults to None when not explicitly set
-        assert kwargs.get("streaming") in (None, False)
+        # streaming defaults to False when not explicitly set
+        assert kwargs.get("streaming") in (False, None)

159-164: Strengthen assertions to cover placeholder/current value behavior

The component preserves placeholder and ensures current value stays in options. Add checks.

Apply this diff:

         # Verify config was updated
         assert "model_name" in updated_config
         model_config = updated_config["model_name"]
         assert "gpt-4o-mini" in model_config["options"]
         assert "claude-3-5-haiku-latest" in model_config["options"]
+        # Placeholder preserved
+        assert model_config["placeholder"] == "Select a model"
+        # Current value remains visible even if not fetched
+        assert "current-model" in model_config["options"]
src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py (2)

124-126: Patch requests.get where imported

Patch the module import site to avoid global requests.get interception.

Apply this diff:

-    @patch("requests.get")
+    @patch("lfx.components.cometapi.cometapi.requests.get")

145-147: Same here: patch at import site

Keep patching consistent and localized.

Apply this diff:

-    @patch("requests.get")
+    @patch("lfx.components.cometapi.cometapi.requests.get")
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c27c047 and c8136f7.

⛔ Files ignored due to path filters (1)
  • src/frontend/src/icons/CometAPI/cometapi.svg is excluded by !**/*.svg
📒 Files selected for processing (16)
  • docs/docs/Components/bundles-cometapi.mdx (1 hunks)
  • docs/sidebars.js (1 hunks)
  • src/backend/base/langflow/__init__.py (1 hunks)
  • src/backend/tests/integration/components/bundles/cometapi/__init__.py (1 hunks)
  • src/backend/tests/integration/components/bundles/cometapi/test_cometapi_integration.py (1 hunks)
  • src/backend/tests/unit/components/bundles/cometapi/__init__.py (1 hunks)
  • src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py (1 hunks)
  • src/backend/tests/unit/components/bundles/cometapi/test_cometapi_constants.py (1 hunks)
  • src/frontend/src/icons/CometAPI/cometapi.jsx (1 hunks)
  • src/frontend/src/icons/CometAPI/index.tsx (1 hunks)
  • src/frontend/src/icons/lazyIconImports.ts (1 hunks)
  • src/frontend/src/utils/styleUtils.ts (1 hunks)
  • src/lfx/src/lfx/base/models/cometapi_constants.py (1 hunks)
  • src/lfx/src/lfx/components/cometapi/__init__.py (1 hunks)
  • src/lfx/src/lfx/components/cometapi/cometapi.py (1 hunks)
  • src/lfx/src/lfx/services/settings/constants.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (17)
docs/sidebars.js

📄 CodeRabbit inference engine (.cursor/rules/docs_development.mdc)

Keep sidebars.js updated to include new/changed docs sections and items using Docusaurus category structure

Files:

  • docs/sidebars.js
src/frontend/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/frontend_development.mdc)

src/frontend/src/**/*.{ts,tsx,js,jsx}: All frontend TypeScript and JavaScript code should be located under src/frontend/src/ and organized into components, pages, icons, stores, types, utils, hooks, services, and assets directories as per the specified directory layout.
Use React 18 with TypeScript for all UI components in the frontend.
Format all TypeScript and JavaScript code using the make format_frontend command.
Lint all TypeScript and JavaScript code using the make lint command.

Files:

  • src/frontend/src/icons/CometAPI/index.tsx
  • src/frontend/src/icons/lazyIconImports.ts
  • src/frontend/src/icons/CometAPI/cometapi.jsx
  • src/frontend/src/utils/styleUtils.ts
src/frontend/src/icons/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/frontend_development.mdc)

Use Lucide React for icons in the frontend.

Files:

  • src/frontend/src/icons/CometAPI/index.tsx
  • src/frontend/src/icons/lazyIconImports.ts
  • src/frontend/src/icons/CometAPI/cometapi.jsx
src/frontend/src/icons/*/*.@(js|jsx|ts|tsx)

📄 CodeRabbit inference engine (.cursor/rules/icons.mdc)

Create a new directory for your icon in src/frontend/src/icons/YourIconName/ and add your SVG as a React component (e.g., YourIconName.jsx). The SVG component must use the isDark prop to support both light and dark mode.

Files:

  • src/frontend/src/icons/CometAPI/index.tsx
  • src/frontend/src/icons/CometAPI/cometapi.jsx
src/frontend/src/icons/*/index.tsx

📄 CodeRabbit inference engine (.cursor/rules/icons.mdc)

Create an index.tsx in your icon directory that exports your icon using forwardRef and passes the isDark prop.

Files:

  • src/frontend/src/icons/CometAPI/index.tsx
{src/backend/**/*.py,tests/**/*.py,Makefile}

📄 CodeRabbit inference engine (.cursor/rules/backend_development.mdc)

{src/backend/**/*.py,tests/**/*.py,Makefile}: Run make format_backend to format Python code before linting or committing changes
Run make lint to perform linting checks on backend Python code

Files:

  • src/backend/tests/integration/components/bundles/cometapi/__init__.py
  • src/backend/tests/unit/components/bundles/cometapi/__init__.py
  • src/backend/base/langflow/__init__.py
  • src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py
  • src/backend/tests/unit/components/bundles/cometapi/test_cometapi_constants.py
  • src/backend/tests/integration/components/bundles/cometapi/test_cometapi_integration.py
src/backend/tests/**/*.py

📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)

src/backend/tests/**/*.py: Unit tests for backend code must be located in the 'src/backend/tests/' directory, with component tests organized by component subdirectory under 'src/backend/tests/unit/components/'.
Test files should use the same filename as the component under test, with an appropriate test prefix or suffix (e.g., 'my_component.py' → 'test_my_component.py').
Use the 'client' fixture (an async httpx.AsyncClient) for API tests in backend Python tests, as defined in 'src/backend/tests/conftest.py'.
When writing component tests, inherit from the appropriate base class in 'src/backend/tests/base.py' (ComponentTestBase, ComponentTestBaseWithClient, or ComponentTestBaseWithoutClient) and provide the required fixtures: 'component_class', 'default_kwargs', and 'file_names_mapping'.
Each test in backend Python test files should have a clear docstring explaining its purpose, and complex setups or mocks should be well-commented.
Test both sync and async code paths in backend Python tests, using '@pytest.mark.asyncio' for async tests.
Mock external dependencies appropriately in backend Python tests to isolate unit tests from external services.
Test error handling and edge cases in backend Python tests, including using 'pytest.raises' and asserting error messages.
Validate input/output behavior and test component initialization and configuration in backend Python tests.
Use the 'no_blockbuster' pytest marker to skip the blockbuster plugin in tests when necessary.
Be aware of ContextVar propagation in async tests; test both direct event loop execution and 'asyncio.to_thread' scenarios to ensure proper context isolation.
Test error handling by mocking internal functions using monkeypatch in backend Python tests.
Test resource cleanup in backend Python tests by using fixtures that ensure proper initialization and cleanup of resources.
Test timeout and performance constraints in backend Python tests using 'asyncio.wait_for' and timing assertions.
Test Langflow's Messag...

Files:

  • src/backend/tests/integration/components/bundles/cometapi/__init__.py
  • src/backend/tests/unit/components/bundles/cometapi/__init__.py
  • src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py
  • src/backend/tests/unit/components/bundles/cometapi/test_cometapi_constants.py
  • src/backend/tests/integration/components/bundles/cometapi/test_cometapi_integration.py
src/backend/**/components/**/*.py

📄 CodeRabbit inference engine (.cursor/rules/icons.mdc)

In your Python component class, set the icon attribute to a string matching the frontend icon mapping exactly (case-sensitive).

Files:

  • src/backend/tests/integration/components/bundles/cometapi/__init__.py
  • src/backend/tests/unit/components/bundles/cometapi/__init__.py
  • src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py
  • src/backend/tests/unit/components/bundles/cometapi/test_cometapi_constants.py
  • src/backend/tests/integration/components/bundles/cometapi/test_cometapi_integration.py
src/frontend/src/icons/lazyIconImports.ts

📄 CodeRabbit inference engine (.cursor/rules/icons.mdc)

Add your icon to the lazyIconsMapping object in src/frontend/src/icons/lazyIconImports.ts with a key that matches the backend icon string exactly.

Files:

  • src/frontend/src/icons/lazyIconImports.ts
src/backend/tests/unit/components/**/*.py

📄 CodeRabbit inference engine (.cursor/rules/backend_development.mdc)

src/backend/tests/unit/components/**/*.py: Mirror the component directory structure for unit tests in src/backend/tests/unit/components/
Use ComponentTestBaseWithClient or ComponentTestBaseWithoutClient as base classes for component unit tests
Provide file_names_mapping for backward compatibility in component tests
Create comprehensive unit tests for all new components

Files:

  • src/backend/tests/unit/components/bundles/cometapi/__init__.py
  • src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py
  • src/backend/tests/unit/components/bundles/cometapi/test_cometapi_constants.py
src/backend/tests/unit/**/*.py

📄 CodeRabbit inference engine (.cursor/rules/backend_development.mdc)

Test component integration within flows using create_flow, build_flow, and get_build_events utilities

Files:

  • src/backend/tests/unit/components/bundles/cometapi/__init__.py
  • src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py
  • src/backend/tests/unit/components/bundles/cometapi/test_cometapi_constants.py
src/frontend/src/utils/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/frontend_development.mdc)

All utility functions should be placed in the utils directory.

Files:

  • src/frontend/src/utils/styleUtils.ts
docs/**/*.{md,mdx}

📄 CodeRabbit inference engine (.cursor/rules/docs_development.mdc)

docs/**/*.{md,mdx}: All Markdown/MDX pages must start with front matter including at least title and description; include sidebar_position for docs pages when applicable
Code blocks must specify a language and may include a title (```lang title="…")
Use sentence case for headings and keep paragraphs short and scannable
Write in second person, present tense, with a professional but approachable tone
Use inline code with backticks for code terms; use bold for UI elements and italics for emphasis; keep lists in parallel structure
Ensure internal links are functional and navigation works (update cross-references as needed)
Verify all code examples in docs and blog actually run as shown
Use correct terminology capitalization: Langflow, Component, Flow, API, JSON
Reference images with absolute paths under /img/... and provide descriptive alt text

Files:

  • docs/docs/Components/bundles-cometapi.mdx
docs/docs/**/*.{md,mdx}

📄 CodeRabbit inference engine (.cursor/rules/docs_development.mdc)

Use Docusaurus admonitions (:::+tip|warning|danger) instead of custom callouts in docs pages

Files:

  • docs/docs/Components/bundles-cometapi.mdx
src/backend/**/*component*.py

📄 CodeRabbit inference engine (.cursor/rules/icons.mdc)

In your Python component class, set the icon attribute to a string matching the frontend icon mapping exactly (case-sensitive).

Files:

  • src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py
**/@(test_*.py|*.test.@(ts|tsx))

📄 CodeRabbit inference engine (coderabbit-custom-pre-merge-checks-unique-id-file-non-traceable-F7F2B60C-1728-4C9A-8889-4F2235E186CA.txt)

**/@(test_*.py|*.test.@(ts|tsx)): Check if tests have too many mock objects that obscure what's actually being tested
Warn when mocks are used instead of testing real behavior and interactions
Suggest using real objects or test doubles when mocks become excessive
Ensure mocks are used appropriately for external dependencies, not core logic
Recommend integration tests when unit tests become overly mocked
Test files should have descriptive test function names explaining what is tested
Tests should be organized logically with proper setup and teardown
Include edge cases and error conditions for comprehensive coverage
Verify tests cover both positive and negative scenarios where appropriate
Tests should cover the main functionality being implemented
Ensure tests are not just smoke tests but actually validate behavior
For API endpoints, verify both success and error response testing

Files:

  • src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py
  • src/backend/tests/unit/components/bundles/cometapi/test_cometapi_constants.py
  • src/backend/tests/integration/components/bundles/cometapi/test_cometapi_integration.py
**/test_*.py

📄 CodeRabbit inference engine (coderabbit-custom-pre-merge-checks-unique-id-file-non-traceable-F7F2B60C-1728-4C9A-8889-4F2235E186CA.txt)

**/test_*.py: Check that backend test files follow naming convention: test_.py
Backend tests should be named test_
.py and follow proper pytest structure
For async Python code, ensure proper async testing patterns (pytest) are used
Backend tests should follow pytest conventions; frontend tests should use Playwright

Files:

  • src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py
  • src/backend/tests/unit/components/bundles/cometapi/test_cometapi_constants.py
  • src/backend/tests/integration/components/bundles/cometapi/test_cometapi_integration.py
🧠 Learnings (9)
📚 Learning: 2025-06-23T12:46:52.420Z
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/icons.mdc:0-0
Timestamp: 2025-06-23T12:46:52.420Z
Learning: Export custom icon components in React using React.forwardRef to ensure proper ref forwarding and compatibility with parent components.

Applied to files:

  • src/frontend/src/icons/CometAPI/index.tsx
📚 Learning: 2025-06-16T11:14:04.200Z
Learnt from: dolfim-ibm
PR: langflow-ai/langflow#8394
File: src/frontend/src/icons/Docling/index.tsx:4-6
Timestamp: 2025-06-16T11:14:04.200Z
Learning: The Langflow codebase consistently uses `React.PropsWithChildren<{}>` as the prop type for all icon components using forwardRef, rather than `React.SVGProps<SVGSVGElement>`. This is an established pattern across hundreds of icon files in src/frontend/src/icons/.

Applied to files:

  • src/frontend/src/icons/CometAPI/index.tsx
📚 Learning: 2025-07-28T15:56:47.865Z
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/icons.mdc:0-0
Timestamp: 2025-07-28T15:56:47.865Z
Learning: Applies to src/frontend/src/icons/*/index.tsx : Create an `index.tsx` in your icon directory that exports your icon using `forwardRef` and passes the `isDark` prop.

Applied to files:

  • src/frontend/src/icons/CometAPI/index.tsx
📚 Learning: 2025-07-28T15:56:47.865Z
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/icons.mdc:0-0
Timestamp: 2025-07-28T15:56:47.865Z
Learning: Applies to src/frontend/src/icons/lazyIconImports.ts : Add your icon to the `lazyIconsMapping` object in `src/frontend/src/icons/lazyIconImports.ts` with a key that matches the backend icon string exactly.

Applied to files:

  • src/frontend/src/icons/lazyIconImports.ts
📚 Learning: 2025-07-28T15:56:47.865Z
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/icons.mdc:0-0
Timestamp: 2025-07-28T15:56:47.865Z
Learning: Applies to src/frontend/src/icons/*/*.@(js|jsx|ts|tsx) : Create a new directory for your icon in `src/frontend/src/icons/YourIconName/` and add your SVG as a React component (e.g., `YourIconName.jsx`). The SVG component must use the `isDark` prop to support both light and dark mode.

Applied to files:

  • src/frontend/src/icons/CometAPI/cometapi.jsx
📚 Learning: 2025-06-23T12:46:52.420Z
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/icons.mdc:0-0
Timestamp: 2025-06-23T12:46:52.420Z
Learning: Custom SVG icon components in React should always support both light and dark mode by accepting an 'isdark' prop and adjusting colors accordingly.

Applied to files:

  • src/frontend/src/icons/CometAPI/cometapi.jsx
📚 Learning: 2025-08-05T22:51:27.961Z
Learnt from: edwinjosechittilappilly
PR: langflow-ai/langflow#0
File: :0-0
Timestamp: 2025-08-05T22:51:27.961Z
Learning: The TestComposioComponentAuth test in src/backend/tests/unit/components/bundles/composio/test_base_composio.py demonstrates proper integration testing patterns for external API components, including real API calls with mocking for OAuth completion, comprehensive resource cleanup, and proper environment variable handling with pytest.skip() fallbacks.

Applied to files:

  • src/backend/tests/unit/components/bundles/cometapi/__init__.py
  • src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py
  • src/backend/tests/integration/components/bundles/cometapi/test_cometapi_integration.py
📚 Learning: 2025-07-21T14:16:14.125Z
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/testing.mdc:0-0
Timestamp: 2025-07-21T14:16:14.125Z
Learning: Applies to src/backend/tests/**/*.py : Test backward compatibility across Langflow versions in backend Python tests by mapping component files to supported versions using 'VersionComponentMapping'.

Applied to files:

  • src/backend/base/langflow/__init__.py
📚 Learning: 2025-07-18T18:25:54.486Z
Learnt from: CR
PR: langflow-ai/langflow#0
File: .cursor/rules/backend_development.mdc:0-0
Timestamp: 2025-07-18T18:25:54.486Z
Learning: Applies to src/backend/tests/unit/components/**/*.py : Create comprehensive unit tests for all new components

Applied to files:

  • src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py
🧬 Code graph analysis (5)
src/frontend/src/icons/CometAPI/index.tsx (1)
src/frontend/src/icons/CometAPI/cometapi.jsx (1)
  • SvgCometAPI (1-29)
src/lfx/src/lfx/components/cometapi/__init__.py (1)
src/lfx/src/lfx/components/cometapi/cometapi.py (1)
  • CometAPIComponent (23-166)
src/lfx/src/lfx/components/cometapi/cometapi.py (3)
src/lfx/src/lfx/base/models/model.py (1)
  • LCModelComponent (25-375)
src/lfx/src/lfx/inputs/inputs.py (7)
  • BoolInput (423-435)
  • DictInput (459-471)
  • DropdownInput (474-499)
  • IntInput (353-385)
  • SecretStrInput (295-350)
  • SliderInput (651-652)
  • StrInput (126-182)
src/lfx/src/lfx/custom/custom_component/component.py (1)
  • get_base_inputs (167-170)
src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py (2)
src/lfx/src/lfx/components/cometapi/cometapi.py (3)
  • CometAPIComponent (23-166)
  • build_model (134-166)
  • get_models (90-113)
src/lfx/src/lfx/custom/custom_component/component.py (1)
  • set_attributes (1024-1045)
src/backend/tests/integration/components/bundles/cometapi/test_cometapi_integration.py (1)
src/lfx/src/lfx/components/cometapi/cometapi.py (4)
  • CometAPIComponent (23-166)
  • get_models (90-113)
  • build_model (134-166)
  • update_build_config (116-132)
🪛 GitHub Actions: Ruff Style Check
src/backend/tests/integration/components/bundles/cometapi/test_cometapi_integration.py

[error] 152-152: Ruff: Unused method argument: mock_api_key (ARG002).


[error] 1-1: Command failed during: uv run --only-dev ruff check --output-format=github .

🪛 GitHub Check: Ruff Style Check (3.13)
src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py

[failure] 99-99: Ruff (F841)
src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py:99:9: F841 Local variable model is assigned to but never used

src/backend/tests/integration/components/bundles/cometapi/test_cometapi_integration.py

[failure] 152-152: Ruff (ARG002)
src/backend/tests/integration/components/bundles/cometapi/test_cometapi_integration.py:152:63: ARG002 Unused method argument: mock_api_key

⏰ 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). (16)
  • GitHub Check: Lint Backend / Run Mypy (3.11)
  • GitHub Check: Lint Backend / Run Mypy (3.13)
  • GitHub Check: Test Docs Build / Test Docs Build
  • GitHub Check: Lint Backend / Run Mypy (3.10)
  • GitHub Check: Lint Backend / Run Mypy (3.12)
  • GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 4
  • GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 3
  • GitHub Check: Run Frontend Unit Tests / Frontend Jest Unit Tests
  • GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 1
  • GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 5
  • GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 2
  • GitHub Check: Run Backend Tests / Integration Tests - Python 3.10
  • GitHub Check: Run Frontend Tests / Determine Test Suites and Shard Distribution
  • GitHub Check: Test Starter Templates
  • GitHub Check: build-and-deploy
  • GitHub Check: Optimize new Python code in this PR
🔇 Additional comments (9)
src/backend/tests/unit/components/bundles/cometapi/__init__.py (1)

1-1: LGTM!

The package initializer follows the standard Python package structure and aligns with the test organization guidelines.

src/backend/tests/integration/components/bundles/cometapi/__init__.py (1)

1-1: LGTM!

The package initializer follows the standard Python package structure for integration tests.

src/frontend/src/utils/styleUtils.ts (1)

267-267: LGTM!

The CometAPI bundle entry follows the established pattern and is correctly positioned in alphabetical order. The icon string "CometAPI" matches the lazy icon mapping added in lazyIconImports.ts.

docs/sidebars.js (1)

303-303: LGTM!

The sidebar entry is correctly positioned in alphabetical order within the Bundles category and follows the Docusaurus documentation structure conventions.

src/lfx/src/lfx/services/settings/constants.py (1)

34-34: LGTM!

The addition of COMETAPI_KEY to the environment variables list is consistent with the pattern used for other API keys in the project.

src/frontend/src/icons/CometAPI/index.tsx (1)

1-10: LGTM!

The icon component implementation follows the established Langflow pattern:

  • Uses React.forwardRef for proper ref forwarding
  • Uses React.PropsWithChildren<{}> as the prop type, consistent with other icon components in the codebase
  • Properly spreads props to forward isDark and other attributes to the underlying SVG component

Based on learnings.

src/backend/tests/unit/components/bundles/cometapi/test_cometapi_constants.py (1)

8-33: LGTM!

The test suite is comprehensive and well-structured, covering:

  • Non-empty validation
  • Alias verification using identity check (appropriate for ensuring same object reference)
  • Type validation for all models
  • Presence of specific expected models
  • Duplicate detection

The tests follow pytest best practices and provide good coverage for the constants module.

src/frontend/src/icons/lazyIconImports.ts (1)

91-92: LGTM!

The lazy icon import mapping follows the established pattern and is correctly positioned in alphabetical order. The key "CometAPI" is case-sensitive and should match the backend component's icon attribute exactly.

As per coding guidelines.

src/lfx/src/lfx/base/models/cometapi_constants.py (1)

10-53: Verify CometAPI model list and enforce immutability

Run

curl -H "Authorization: Bearer $COMETAPI_KEY" https://api.cometapi.com/v1/models

to fetch the current model IDs and sync COMETAPI_MODELS. To prevent accidental mutation, redefine it as an immutable tuple:

-from typing import Final
+from typing import Final, Tuple

-COMETAPI_MODELS: Final[list[str]] = [
+COMETAPI_MODELS: Final[Tuple[str, ...]] = (
     "gpt-5-chat-latest",
     …,
     "qwen3-coder-plus-2025-07-22",
-]
+)

Comment on lines +1 to +5
---
title: CometAPI
slug: /bundles-cometapi
description: Use CometAPI models in Langflow to generate text or output a Language Model for downstream Components.
---
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

Fix doc accuracy (front matter, parameters) to match the component.

  • Add sidebar position in front matter.
  • Correct temperature range/default to 0–2, default 0.7.
  • Remove output_parser row (not an input for CometAPIComponent).
  • Align field label wording with UI (“CometAPI Key”).
 --- 
 title: CometAPI
 slug: /bundles-cometapi
 description: Use CometAPI models in Langflow to generate text or output a Language Model for downstream Components.
+sidebar_position: 35
 ---
@@
-| max_tokens | Integer | Input parameter. The maximum number of tokens to generate. Set to 0 for unlimited tokens. |
-| temperature | Float | Input parameter. Controls randomness in the output. Range: [0.0, 1.0]. Default: 0.1. |
+| max_tokens | Integer | Input parameter. The maximum number of tokens to generate. Set to 0 for unlimited tokens. |
+| temperature | Float | Input parameter. Controls randomness in the output. Range: [0.0, 2.0]. Default: 0.7. |
@@
-| output_parser | OutputParser | Input parameter. The parser to use to parse the output of the model (advanced). |
@@
-4. Enter your API key in the **CometAPI API Key** field.
+4. Enter your API key in the **CometAPI Key** field.

Run this to validate internal links exist:

Also applies to: 37-45, 51-52


🏁 Script executed:

#!/bin/bash
set -euo pipefail
echo "Checking docs slugs/anchors referenced..."
rg -nC1 'slug:\s*/components-bundle-components' docs || echo "Missing: /components-bundle-components"
rg -nC1 'slug:\s*/data-types' docs || echo "Missing: /data-types"
rg -nC1 'slug:\s*/components-models' docs || echo "Missing: /components-models"
# Spot references to anchors in data-types page
rg -nC2 -g 'docs/**' '##\s*Message|#\s*Message|\(Message\)' || true
rg -nC2 -g 'docs/**' '##\s*LanguageModel|#\s*LanguageModel|\(LanguageModel\)' || true

Length of output: 16095


🏁 Script executed:

#!/bin/bash
set -euo pipefail
echo "Front matter of docs/docs/Components/bundles-cometapi.mdx:"
head -n20 docs/docs/Components/bundles-cometapi.mdx

Length of output: 930


🏁 Script executed:

#!/bin/bash
set -euo pipefail
echo "Finding CometAPI component implementation..."
file=$(fd -g cometapi.py | head -n1)
echo "Inspecting $file:"
sed -n '1,200p' "$file"

Length of output: 6132


Fix CometAPI docs front matter and parameters

  • Add sidebar_position: 35 to front matter
  • Update temperature range to [0.0, 2.0], default 0.7
  • Remove the output_parser input row
  • Use CometAPI Key for the API key field label
🤖 Prompt for AI Agents
In docs/docs/Components/bundles-cometapi.mdx around lines 1 to 5, update the
front matter and parameter docs: add sidebar_position: 35 to the YAML front
matter; change the temperature parameter documentation to reflect range [0.0,
2.0] with default 0.7; remove the input row documenting output_parser entirely;
and update the API key field label to read "CometAPI Key" (ensure the visible
label and any internal key name used for display reflect this change).

Comment on lines +152 to +158
def test_update_build_config_integration(self, component, mock_api_key):
"""Test update_build_config integration."""
build_config = {"model_name": {"value": "current-model", "placeholder": "Select a model"}}

with patch.object(component, "get_models", return_value=["gpt-4o-mini", "claude-3-5-haiku-latest"]):
updated_config = component.update_build_config(build_config, "new-key", "api_key")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Fix Ruff ARG002: remove unused fixture parameter

mock_api_key is unused and fails Ruff. Drop it from the signature.

Apply this diff:

-    def test_update_build_config_integration(self, component, mock_api_key):
+    def test_update_build_config_integration(self, component):
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def test_update_build_config_integration(self, component, mock_api_key):
"""Test update_build_config integration."""
build_config = {"model_name": {"value": "current-model", "placeholder": "Select a model"}}
with patch.object(component, "get_models", return_value=["gpt-4o-mini", "claude-3-5-haiku-latest"]):
updated_config = component.update_build_config(build_config, "new-key", "api_key")
def test_update_build_config_integration(self, component):
"""Test update_build_config integration."""
build_config = {"model_name": {"value": "current-model", "placeholder": "Select a model"}}
with patch.object(component, "get_models", return_value=["gpt-4o-mini", "claude-3-5-haiku-latest"]):
updated_config = component.update_build_config(build_config, "new-key", "api_key")
🧰 Tools
🪛 GitHub Actions: Ruff Style Check

[error] 152-152: Ruff: Unused method argument: mock_api_key (ARG002).

🪛 GitHub Check: Ruff Style Check (3.13)

[failure] 152-152: Ruff (ARG002)
src/backend/tests/integration/components/bundles/cometapi/test_cometapi_integration.py:152:63: ARG002 Unused method argument: mock_api_key

🤖 Prompt for AI Agents
In
src/backend/tests/integration/components/bundles/cometapi/test_cometapi_integration.py
around lines 152 to 158, the test function test_update_build_config_integration
accepts an unused fixture parameter mock_api_key which triggers Ruff ARG002;
remove mock_api_key from the function signature so it reads def
test_update_build_config_integration(self, component): and save the file (no
other changes required unless the fixture is referenced elsewhere in the
function).

Comment on lines +96 to +103
component = component_class()
component.set_attributes(default_kwargs)
component.stream = True
model = component.build_model()

_args, kwargs = mock_chat_openai.call_args
assert kwargs["streaming"] is True

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Fix Ruff F841: remove unused local variable

model is assigned but not used. Either assert on it or drop the assignment.

Apply this diff:

-        model = component.build_model()
+        component.build_model()
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
component = component_class()
component.set_attributes(default_kwargs)
component.stream = True
model = component.build_model()
_args, kwargs = mock_chat_openai.call_args
assert kwargs["streaming"] is True
component = component_class()
component.set_attributes(default_kwargs)
component.stream = True
component.build_model()
_args, kwargs = mock_chat_openai.call_args
assert kwargs["streaming"] is True
🧰 Tools
🪛 GitHub Check: Ruff Style Check (3.13)

[failure] 99-99: Ruff (F841)
src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py:99:9: F841 Local variable model is assigned to but never used

🤖 Prompt for AI Agents
In src/backend/tests/unit/components/bundles/cometapi/test_cometapi_component.py
around lines 96 to 103, the test assigns model = component.build_model() but
never uses model which triggers Ruff F841; either remove the unused assignment
or assert something about the returned model. Update the test by either deleting
the line "model = component.build_model()" if not needed, or replace it with an
assertion that validates the built model (for example assert model is not None
or assert attributes on model) and keep the rest of the assertions unchanged.

Comment on lines +101 to +113
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
# Safely parse JSON; fallback to defaults on failure
try:
model_list = response.json()
except (json.JSONDecodeError, ValueError) as e:
self.status = f"Error decoding models response: {e}"
return MODEL_NAMES
return [model["id"] for model in model_list.get("data", [])]
except requests.RequestException as e:
self.status = f"Error fetching models: {e}"
return MODEL_NAMES
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Harden JSON parsing: handle both dict-with-data and top-level lists.

Current code raises if the API returns a list. Support both shapes and guard missing keys.

-            # Safely parse JSON; fallback to defaults on failure
-            try:
-                model_list = response.json()
-            except (json.JSONDecodeError, ValueError) as e:
-                self.status = f"Error decoding models response: {e}"
-                return MODEL_NAMES
-            return [model["id"] for model in model_list.get("data", [])]
+            # Safely parse JSON; fallback to defaults on failure
+            try:
+                payload = response.json()
+            except (json.JSONDecodeError, ValueError) as e:
+                self.status = f"Error decoding models response: {e}"
+                return MODEL_NAMES
+            # Accept either {"data": [...]} or a top-level list
+            items = payload.get("data", []) if isinstance(payload, dict) else (payload if isinstance(payload, list) else [])
+            ids = [m.get("id") for m in items if isinstance(m, dict) and m.get("id")]
+            return ids or MODEL_NAMES
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
# Safely parse JSON; fallback to defaults on failure
try:
model_list = response.json()
except (json.JSONDecodeError, ValueError) as e:
self.status = f"Error decoding models response: {e}"
return MODEL_NAMES
return [model["id"] for model in model_list.get("data", [])]
except requests.RequestException as e:
self.status = f"Error fetching models: {e}"
return MODEL_NAMES
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
# Safely parse JSON; fallback to defaults on failure
try:
payload = response.json()
except (json.JSONDecodeError, ValueError) as e:
self.status = f"Error decoding models response: {e}"
return MODEL_NAMES
# Accept either {"data": [...]} or a top-level list
items = payload.get("data", []) if isinstance(payload, dict) else (payload if isinstance(payload, list) else [])
ids = [m.get("id") for m in items if isinstance(m, dict) and m.get("id")]
return ids or MODEL_NAMES
except requests.RequestException as e:
self.status = f"Error fetching models: {e}"
return MODEL_NAMES
🤖 Prompt for AI Agents
In src/lfx/src/lfx/components/cometapi/cometapi.py around lines 101 to 113, the
JSON parsing assumes the API returns a dict with a "data" key and will fail if
the response is a top-level list; update the parsing to accept both shapes:
parse response.json() into a variable, if it's a list use it as the model_list,
if it's a dict extract model_list = parsed.get("data", []), then ensure
model_list is an iterable (else set status and return MODEL_NAMES), map over
model_list only picking entries that are dicts with an "id" key and return those
ids; on any parsing/type error set self.status with a concise error and return
MODEL_NAMES (keeping the existing exception handling for requests).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants