Skip to content

feat: Add Converse component and improve output extraction#9901

Merged
Cristhianzl merged 17 commits intomainfrom
cz/fix-events-agent
Oct 2, 2025
Merged

feat: Add Converse component and improve output extraction#9901
Cristhianzl merged 17 commits intomainfrom
cz/fix-events-agent

Conversation

@Cristhianzl
Copy link
Member

@Cristhianzl Cristhianzl commented Sep 17, 2025

This pull request adds comprehensive tests for field name conversion and output extraction utilities, and updates async handling in agent test scripts for consistency. The main changes include extensive new test coverage for field name conversion between camelCase and snake_case, thorough tests for the _extract_output_text function (including edge cases and backward compatibility), and updates to use the run_until_complete helper for asynchronous toolkit initialization in agent-related tests.

Testing improvements:

  • Added a comprehensive test class TestFieldNameConversion to test_mcp_util.py to cover all scenarios of camelCase to snake_case conversion, including edge cases, integration with Pydantic schemas, and value preservation. Also added TestToolExecutionWithFieldConversion to verify that tool execution functions correctly handle field name conversion in both async and sync contexts.
  • Added a large suite of tests for the _extract_output_text function in test_agent_events.py, covering various input formats, edge cases, backward compatibility, and specific scenarios related to ChatBedrockConverse and streaming responses.

Async handling consistency:

  • Updated agent test scripts (simple_agent.py and test_simple_agent_in_lfx_run.py) to use the run_until_complete helper from lfx.utils.async_helpers for initializing toolkits, ensuring consistent async execution patterns across tests. [1] [2] [3] [4] [5]

Test imports and dependencies:

  • Added missing import of _extract_output_text in test_agent_events.py to enable direct testing of this utility.

Summary by CodeRabbit

  • New Features

    • Added Amazon Bedrock Converse component with configurable credentials, regions, generation parameters, streaming toggle, and extra request fields.
  • Improvements

    • Tool parameters now accept camelCase or snake_case seamlessly.
    • Tool retrieval supports both sync and async implementations; improved metadata-based filtering.
    • More robust extraction of text from mixed output formats for better compatibility.
  • Bug Fixes

    • Prevents errors when parsing diverse output item shapes by handling edge cases gracefully.
  • Documentation

    • Updated legacy Amazon Bedrock component description to recommend using Bedrock Converse.

https://www.loom.com/share/959bd9ea2ee44873852e6f79dc0750a5?sid=5afa3f75-e724-4a8f-874b-55027a2afbdb

…compatibility with async functions

🔧 (test_simple_agent_in_lfx_run.py): Replace direct call to url_component.to_toolkit() with await to handle async function correctly
♻️ (component.py): Refactor _get_tools method to handle both synchronous and asynchronous implementations
…d names to snake_case for better compatibility with schema field names.
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 17, 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

Introduces Amazon Bedrock Converse component; updates legacy Bedrock description text. Adds field-name normalization in MCP tool utilities. Expands _extract_output_text to support varied output shapes. Enhances CustomComponent tool retrieval for sync/async _get_tools and metadata early-return. Updates tests and harnesses to bridge async to_toolkit via run_until_complete and adds comprehensive tests.

Changes

Cohort / File(s) Summary
Test harness: async bridging for toolkit
src/backend/tests/data/simple_agent.py, src/backend/tests/unit/test_simple_agent_in_lfx_run.py
Replace direct asyncio.run/sync calls with run_until_complete(url_component.to_toolkit()); adjust imports and embedded script to await to_toolkit.
Tests: events output text extraction
src/backend/tests/unit/components/agents/test_agent_events.py
Add extensive tests for _extract_output_text, covering strings, lists, dict variants, Bedrock Converse-like shapes, concatenation, and edge cases; import updated function.
Tests: MCP util field conversion & tool execution
src/backend/tests/unit/base/mcp/test_mcp_util.py
Add tests for camelCase→snake_case conversion and end-to-end tool execution paths for coroutine/sync wrappers, including validation behaviors.
Agents events extraction logic
src/lfx/src/lfx/base/agents/events.py
Replace strict single-item handling with flexible list processing: collect text across items; skip tool_use, partial_json, and index-only dicts; return empty string on unexpected formats.
MCP util: field-name normalization
src/lfx/src/lfx/base/mcp/util.py
Add _camel_to_snake and _convert_field_names; apply conversion in create_tool_coroutine and create_tool_func before validation to map camelCase inputs to snake_case schema fields.
Custom component: toolkit sync/async + metadata path
src/lfx/src/lfx/custom/custom_component/component.py
to_toolkit and _build_tools_metadata_input now support sync/async _get_tools; introduce early return when metadata input present via _update_tools_with_metadata; otherwise preserve filtering path.
New component: Amazon Bedrock Converse
src/lfx/src/lfx/components/amazon/amazon_bedrock_converse.py
Add AmazonBedrockConverseComponent with inputs for AWS credentials/region/model params; lazily import ChatBedrockConverse; construct init params including optional additional request fields; handle errors with user-friendly messages.
Docs text update: legacy Bedrock
src/lfx/src/lfx/components/amazon/amazon_bedrock_model.py
Expand description to note legacy ChatBedrock API and recommend using Amazon Bedrock Converse.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Test as Test/Caller
  participant Comp as CustomComponent
  participant Tools as _get_tools (sync/async)
  participant Meta as _update_tools_with_metadata
  participant Filter as _filter_tools_by_status

  Test->>Comp: to_toolkit()
  alt _get_tools is coroutine
    Comp->>Tools: await _get_tools()
    Tools-->>Comp: tools
  else sync
    Comp->>Tools: _get_tools()
    Tools-->>Comp: tools
  end
  alt metadata input present
    Comp->>Meta: _update_tools_with_metadata(tools, metadata)
    Meta-->>Comp: updated_tools
    Comp-->>Test: updated_tools (early return)
  else
    Comp->>Filter: _filter_tools_by_status(tools, metadata=None)
    Filter-->>Comp: filtered_tools
    Comp-->>Test: filtered_tools
  end
Loading
sequenceDiagram
  autonumber
  participant Caller as Tool Caller
  participant Util as mcp.util
  participant Schema as Pydantic Schema

  Caller->>Util: create_tool_coroutine/func(*args, **kwargs)
  Util->>Util: merge positional + keyword args -> provided_args
  Util->>Util: _convert_field_names(provided_args, Schema)
  Util->>Schema: validate converted args
  Schema-->>Util: validated data / errors
  Util-->>Caller: callable or raises validation error
Loading
sequenceDiagram
  autonumber
  participant Producer as Model Output Producer
  participant Events as _extract_output_text
  Producer-->>Events: output (list[str|dict]|str|other)
  alt list
    loop items
      alt item is str
        Events->>Events: append text
      else item is dict with "text"
        Events->>Events: append item["text"] or ""
      else item type "tool_use" / has "partial_json" / index-only
        Events->>Events: skip
      else
        Events->>Events: skip
      end
    end
    Events-->>Producer: concatenated text (may be "")
  else str
    Events-->>Producer: str
  else other
    Events-->>Producer: ""
  end
Loading
sequenceDiagram
  autonumber
  participant User as User
  participant Comp as AmazonBedrockConverseComponent
  participant LC as langchain_aws.ChatBedrockConverse

  User->>Comp: build_model()
  Comp->>Comp: prepare init_params (model, region, creds, endpoint, profile)
  Comp->>Comp: add generation params (temperature, max_tokens, top_p, disable_streaming)
  Comp->>Comp: merge additional_model_request_fields
  Comp->>LC: instantiate ChatBedrockConverse(init_params)
  LC-->>Comp: model instance
  Comp-->>User: model
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60–90 minutes

Possibly related PRs

Suggested labels

enhancement, size:L, lgtm

Suggested reviewers

  • edwinjosechittilappilly
  • ogabrielluiz
  • mfortman11

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The title "feat: Add Converse component and improve output extraction" succinctly captures the two principal changes in the diff—the new Converse (Amazon Bedrock Converse) component and the broadened output-extraction logic—without unnecessary detail. It is concise, directly related to the changeset, and will be clear to reviewers scanning history.
Docstring Coverage ✅ Passed Docstring coverage is 87.27% which is sufficient. The required threshold is 80.00%.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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.

@github-actions github-actions bot added enhancement New feature or request and removed enhancement New feature or request labels Sep 17, 2025
@codecov
Copy link

codecov bot commented Sep 17, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 23.01%. Comparing base (150dfa8) to head (6bef4b0).
⚠️ Report is 3 commits behind head on main.

❌ Your project status has failed because the head coverage (8.12%) is below the target coverage (10.00%). You can increase the head coverage or adjust the target coverage.

Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main    #9901      +/-   ##
==========================================
- Coverage   24.10%   23.01%   -1.10%     
==========================================
  Files        1091     1084       -7     
  Lines       40009    39651     -358     
  Branches     5543     5420     -123     
==========================================
- Hits         9645     9125     -520     
- Misses      30193    30371     +178     
+ Partials      171      155      -16     
Flag Coverage Δ
backend 46.96% <ø> (+<0.01%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.
see 144 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
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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (5)
src/lfx/src/lfx/base/agents/events.py (1)

272-276: Bug: isinstance with PEP 604 union at runtime raises TypeError on Python ≤3.12.

Replace isinstance(output, str | list) with a tuple form to avoid runtime errors in streams.

Apply this diff:

-        if output and isinstance(output, str | list):
+        if output and isinstance(output, (str, list)):
src/backend/tests/unit/test_simple_agent_in_lfx_run.py (3)

55-66: Fixture script content is syntactically invalid: await at module top-level.

ast.parse will fail; match the real sample (use run_until_complete).

Apply this diff to the embedded script string:

- from lfx.log.logger import LogConfig
+ from lfx.log.logger import LogConfig
+ from lfx.utils.async_helpers import run_until_complete
@@
-url_component = cp.URLComponent()
-tools = await url_component.to_toolkit()
+url_component = cp.URLComponent()
+tools = run_until_complete(url_component.to_toolkit())

142-166: Async test lacks @pytest.mark.asyncio and uses run_until_complete inside an async test.

Mark the test async and just await the coroutine.

Apply this diff:

@@
-    async def test_agent_workflow_direct_execution(self):
+    @pytest.mark.asyncio
+    async def test_agent_workflow_direct_execution(self):
@@
-            from lfx.log.logger import LogConfig
-            from lfx.utils.async_helpers import run_until_complete
+            from lfx.log.logger import LogConfig
@@
-        tools = run_until_complete(url_component.to_toolkit())
+        tools = await url_component.to_toolkit()

212-227: Same issue: add asyncio marker and await instead of run_until_complete.

Apply this diff:

-    async def test_url_component_to_toolkit_functionality(self):
+    @pytest.mark.asyncio
+    async def test_url_component_to_toolkit_functionality(self):
@@
-            from lfx import components as cp
-            from lfx.utils.async_helpers import run_until_complete
+            from lfx import components as cp
@@
-        tools = run_until_complete(url_component.to_toolkit())
+        tools = await url_component.to_toolkit()
src/backend/tests/unit/components/agents/test_agent_events.py (1)

1-21: Async tests missing pytest.mark.asyncio — add module-level marker.

Prevents collection/execution issues per guidelines.

Apply this diff:

 from collections.abc import AsyncIterator
 from typing import Any
 from unittest.mock import AsyncMock
+import pytest
@@
-from lfx.base.agents.agent import process_agent_events
+from lfx.base.agents.agent import process_agent_events
+
+# Mark all async tests in this module
+pytestmark = pytest.mark.asyncio
🧹 Nitpick comments (5)
src/lfx/src/lfx/custom/custom_component/component.py (2)

1329-1332: Don’t block the event loop when _get_tools is sync

If subclasses implement a synchronous _get_tools that performs I/O, calling it directly from this async method will block the loop. Offload the sync path to a thread.

Apply this diff:

-        if asyncio.iscoroutinefunction(self._get_tools):
-            tools = await self._get_tools()
-        else:
-            tools = self._get_tools()
+        if asyncio.iscoroutinefunction(self._get_tools):
+            tools = await self._get_tools()
+        else:
+            tools = await asyncio.to_thread(self._get_tools)

1428-1433: Same here: offload sync _get_tools and fix TODO typos

Avoid blocking in _build_tools_metadata_input and correct the comment.

Apply this diff:

-            # TODO: this check can be remomved ince get tools is async
+            # TODO: this check can be removed once _get_tools is always async
             if asyncio.iscoroutinefunction(self._get_tools):
                 tools = await self._get_tools()
             else:
-                tools = self._get_tools()
+                tools = await asyncio.to_thread(self._get_tools)
src/lfx/src/lfx/base/mcp/util.py (1)

192-199: Avoid redundant local import; module already imports re

Minor cleanup: drop the inner import and use the module-level re.

Apply this diff:

 def _camel_to_snake(name: str) -> str:
     """Convert camelCase to snake_case."""
-    import re
-
     # Insert an underscore before any uppercase letter that follows a lowercase letter
     s1 = re.sub("([a-z0-9])([A-Z])", r"\1_\2", name)
     return s1.lower()
src/lfx/src/lfx/base/agents/events.py (1)

94-131: Robust, backward-compatible extraction logic — nice.

Covers single/multi-item lists, skips tool_use/index/partial_json, and degrades gracefully. Consider casting dict["text"] to str to avoid unexpected non-str payloads, but OK as-is.

src/backend/tests/unit/components/agents/test_agent_events.py (1)

458-461: Remove stray f-string expression (no effect).

Likely leftover debug; keep test tidy.

Apply this diff:

-    f"{end_event['name']}_{end_event['run_id']}"
+    # tool_key = f"{end_event['name']}_{end_event['run_id']}"  # not needed here
📜 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 ca2309f and ee4cf63.

📒 Files selected for processing (9)
  • src/backend/tests/data/simple_agent.py (2 hunks)
  • src/backend/tests/unit/base/mcp/test_mcp_util.py (1 hunks)
  • src/backend/tests/unit/components/agents/test_agent_events.py (2 hunks)
  • src/backend/tests/unit/test_simple_agent_in_lfx_run.py (7 hunks)
  • src/lfx/src/lfx/base/agents/events.py (1 hunks)
  • src/lfx/src/lfx/base/mcp/util.py (3 hunks)
  • src/lfx/src/lfx/components/amazon/amazon_bedrock_converse.py (1 hunks)
  • src/lfx/src/lfx/components/amazon/amazon_bedrock_model.py (1 hunks)
  • src/lfx/src/lfx/custom/custom_component/component.py (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
{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/data/simple_agent.py
  • src/backend/tests/unit/test_simple_agent_in_lfx_run.py
  • src/backend/tests/unit/components/agents/test_agent_events.py
  • src/backend/tests/unit/base/mcp/test_mcp_util.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/data/simple_agent.py
  • src/backend/tests/unit/test_simple_agent_in_lfx_run.py
  • src/backend/tests/unit/components/agents/test_agent_events.py
  • src/backend/tests/unit/base/mcp/test_mcp_util.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/test_simple_agent_in_lfx_run.py
  • src/backend/tests/unit/components/agents/test_agent_events.py
  • src/backend/tests/unit/base/mcp/test_mcp_util.py
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/agents/test_agent_events.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/unit/components/agents/test_agent_events.py
🧠 Learnings (1)
📚 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 : Be aware of ContextVar propagation in async tests; test both direct event loop execution and 'asyncio.to_thread' scenarios to ensure proper context isolation.

Applied to files:

  • src/backend/tests/unit/test_simple_agent_in_lfx_run.py
🧬 Code graph analysis (6)
src/backend/tests/data/simple_agent.py (1)
src/lfx/src/lfx/custom/custom_component/component.py (1)
  • to_toolkit (1314-1339)
src/backend/tests/unit/test_simple_agent_in_lfx_run.py (1)
src/lfx/src/lfx/custom/custom_component/component.py (1)
  • to_toolkit (1314-1339)
src/lfx/src/lfx/components/amazon/amazon_bedrock_converse.py (1)
src/lfx/src/lfx/components/amazon/amazon_bedrock_model.py (1)
  • build_model (83-128)
src/backend/tests/unit/components/agents/test_agent_events.py (1)
src/lfx/src/lfx/base/agents/events.py (1)
  • _extract_output_text (88-131)
src/lfx/src/lfx/custom/custom_component/component.py (3)
src/lfx/src/lfx/base/agents/agent.py (1)
  • _get_tools (257-268)
src/lfx/src/lfx/components/agents/agent.py (1)
  • _get_tools (547-558)
src/lfx/src/lfx/base/composio/composio_base.py (1)
  • _get_tools (1953-1957)
src/backend/tests/unit/base/mcp/test_mcp_util.py (1)
src/lfx/src/lfx/base/mcp/util.py (8)
  • _camel_to_snake (192-198)
  • _convert_field_names (201-220)
  • run_tool (915-1019)
  • run_tool (1220-1330)
  • tool_coroutine (224-251)
  • create_tool_coroutine (223-253)
  • tool_func (257-281)
  • create_tool_func (256-283)
⏰ 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). (14)
  • GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 2
  • GitHub Check: Lint Backend / Run Mypy (3.11)
  • GitHub Check: Run Backend Tests / Unit Tests - Python 3.10 - Group 3
  • GitHub Check: Lint Backend / Run Mypy (3.13)
  • 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 5
  • 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: Ruff Style Check (3.13)
  • GitHub Check: Run Ruff Check and Format
  • GitHub Check: Update Starter Projects
🔇 Additional comments (11)
src/lfx/src/lfx/components/amazon/amazon_bedrock_model.py (1)

10-14: Description update aligns users toward Converse — LGTM

Clear, actionable guidance pointing to the Converse component. No functional changes.

src/lfx/src/lfx/base/mcp/util.py (3)

201-221: Field-name normalization is solid — LGTM

Keeps exact schema keys, falls back to snake_case, otherwise preserves for validation. Matches the new tests.

If inputs contain both “top_n” and “topN”, the converted map may overwrite one value. If you expect such collisions, do you want to raise on conflict?


256-282: Sync wrapper may raise when called inside a running event loop

create_tool_func uses get_event_loop().run_until_complete, which raises RuntimeError if invoked from within a running loop. Since the async variant exists, this is acceptable if callers only use create_tool_func from sync contexts. Please confirm usage sites.

Would you like a patch to auto-detect a running loop and delegate to the coroutine path (or a shared run_until_complete helper) for safety?


236-238: End-to-end conversion in wrappers — LGTM

Applying _convert_field_names in both async and sync wrappers closes the validation gap the tests cover.

Also applies to: 266-268

src/lfx/src/lfx/components/amazon/amazon_bedrock_converse.py (1)

154-157: Verify parameter name for streaming control

ChatBedrockConverse may expect a streaming boolean rather than disable_streaming. Please confirm the correct kwarg and adjust accordingly.

src/backend/tests/unit/base/mcp/test_mcp_util.py (2)

254-413: Field-name conversion tests — LGTM

Thorough coverage of exact-match, conversions, edge cases, and value preservation. Clear docstrings.


415-611: Wrapper integration tests — LGTM

Good end-to-end assertions for coroutine/sync wrappers, positional/mixed args, and validation errors.

src/backend/tests/data/simple_agent.py (1)

24-36: Good switch to run_until_complete for top-level async bridging.

Import and usage look correct and match component.to_toolkit()’s async nature.

src/backend/tests/unit/test_simple_agent_in_lfx_run.py (1)

319-336: LGTM for sync integration test using run_until_complete.

Appropriate use in a non-async test context.

src/backend/tests/unit/components/agents/test_agent_events.py (2)

9-16: Importing _extract_output_text for direct tests — good.

Import set looks correct and minimal.


546-733: Comprehensive coverage for _extract_output_text — well done.

Covers empty, single/multi, tool_use, partial_json, index-only, mixed, and streaming.

Comment on lines +1 to +6
from langflow.base.models.aws_constants import AWS_REGIONS, AWS_MODEL_IDs
from langflow.base.models.model import LCModelComponent
from langflow.field_typing import LanguageModel
from langflow.inputs.inputs import BoolInput, FloatInput, IntInput, MessageTextInput, SecretStrInput
from langflow.io import DictInput, DropdownInput

Copy link
Contributor

@coderabbitai coderabbitai bot Sep 17, 2025

Choose a reason for hiding this comment

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

⚠️ Potential issue

Broken imports: use lfx. package paths in this repository*

The current imports point to langflow., which will fail here. Switch to lfx. to match the rest of the codebase.

Apply this diff:

-from langflow.base.models.aws_constants import AWS_REGIONS, AWS_MODEL_IDs
-from langflow.base.models.model import LCModelComponent
-from langflow.field_typing import LanguageModel
-from langflow.inputs.inputs import BoolInput, FloatInput, IntInput, MessageTextInput, SecretStrInput
-from langflow.io import DictInput, DropdownInput
+from lfx.base.models.aws_constants import AWS_REGIONS, AWS_MODEL_IDs
+from lfx.base.models.model import LCModelComponent
+from lfx.field_typing import LanguageModel
+from lfx.inputs.inputs import BoolInput, FloatInput, IntInput, MessageTextInput, SecretStrInput
+from lfx.io import DictInput, DropdownInput
📝 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
from langflow.base.models.aws_constants import AWS_REGIONS, AWS_MODEL_IDs
from langflow.base.models.model import LCModelComponent
from langflow.field_typing import LanguageModel
from langflow.inputs.inputs import BoolInput, FloatInput, IntInput, MessageTextInput, SecretStrInput
from langflow.io import DictInput, DropdownInput
from lfx.base.models.aws_constants import AWS_REGIONS, AWS_MODEL_IDs
from lfx.base.models.model import LCModelComponent
from lfx.field_typing import LanguageModel
from lfx.inputs.inputs import BoolInput, FloatInput, IntInput, MessageTextInput, SecretStrInput
from lfx.io import DictInput, DropdownInput
🤖 Prompt for AI Agents
In src/lfx/src/lfx/components/amazon/amazon_bedrock_converse.py around lines 1
to 6, the imports use langflow.* which are invalid in this repo; replace each
langflow.* import path with the equivalent lfx.* path (e.g.,
langflow.base.models.aws_constants -> lfx.base.models.aws_constants,
langflow.base.models.model -> lfx.base.models.model, langflow.field_typing ->
lfx.field_typing, langflow.inputs.inputs -> lfx.inputs.inputs, langflow.io ->
lfx.io) keeping the imported symbol names identical so the rest of the file
continues to work.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Is this true? I see you resolved but just checking since the imports could technically be moved to lfx

Copy link
Contributor

Choose a reason for hiding this comment

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check what imports are used in other component files in the same directory
echo "=== Checking imports in other amazon component files ==="
fd -e py . src/lfx/src/lfx/components/amazon/ --exec head -20 {} \;

echo -e "\n=== Checking imports in other component files ==="
fd -e py . src/lfx/src/lfx/components/ -d 2 --exec grep -l "from.*base.models.model import" {} \; | head -5 | xargs -I {} sh -c 'echo "File: {}" && head -20 {}'

echo -e "\n=== Checking if lfx.base.models exists ==="
fd -t d "models" src/lfx/src/lfx/base/

echo -e "\n=== Checking if langflow package exists in the repo ==="
fd -t d "langflow" src/ | head -10

Length of output: 7143


@jordanrfrazier Yes, this is true and the CodeRabbit suggestion is correct!

I verified by checking other files in the same directory and across the codebase:

Evidence from the codebase:

  • amazon_bedrock_model.py (same directory): uses from lfx.base.models.aws_constants import...
  • amazon_bedrock_embedding.py (same directory): uses from lfx.base.models.aws_constants import...
  • All other component files (xai, vertexai, aiml, sambanova): use from lfx.base.models.model import...

The issue:

  • amazon_bedrock_converse.py is the only file in the lfx package using langflow.* imports
  • The langflow package exists in src/backend/langflow/, but this file is in src/lfx/src/lfx/components/
  • These imports will fail at runtime

The imports should be changed from langflow.* to lfx.* to match the rest of the codebase. The comment appears to have been resolved prematurely.

- Add MCPStructuredTool class to handle camelCase to snake_case parameter conversion before LangChain validation
- Fix asyncio import scope issues in MCPStdioClient and MCPSseClient run_tool methods
- Add comprehensive tests for MCPStructuredTool parameter conversion functionality
- Add alias support for camelCase field names in JSON schema creation
- Improve error handling for tools called with empty arguments

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
@github-actions github-actions bot added enhancement New feature or request and removed enhancement New feature or request labels Sep 17, 2025
…ed to parameter conversion in MCPStructuredTool

♻️ (util.py): Refactor MCPStructuredTool to handle parameter conversion before LangChain validation for camelCase to snake_case conversion.
@github-actions github-actions bot added enhancement New feature or request and removed enhancement New feature or request labels Sep 17, 2025
Copy link
Contributor

@ogabrielluiz ogabrielluiz left a comment

Choose a reason for hiding this comment

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

Is the current Bedrock component useful to keep it or should we just make it use the Converse version?

@edwinjosechittilappilly
Copy link
Collaborator

Is the current Bedrock component useful to keep it or should we just make it use the Converse version?

I would suggest to deprecate the old one since it might be using the not supported LMbackend of AWS

…_output_text function

📝 (amazon_bedrock_converse.py): update description to provide clearer information about the component
♻️ (amazon_bedrock_model.py): refactor to set legacy flag to True for AmazonBedrockComponent
@github-actions github-actions bot added enhancement New feature or request and removed enhancement New feature or request labels Sep 24, 2025
@github-actions
Copy link
Contributor

github-actions bot commented Sep 24, 2025

Frontend Unit Test Coverage Report

Coverage Summary

Lines Statements Branches Functions
Coverage: 10%
10.56% (2781/26331) 4.6% (931/20202) 6.49% (370/5698)

Unit Test Results

Tests Skipped Failures Errors Time
1195 0 💤 0 ❌ 0 🔥 18.13s ⏱️

@github-actions github-actions bot removed the enhancement New feature or request label Sep 25, 2025
@github-actions github-actions bot added the enhancement New feature or request label Oct 1, 2025
@github-actions github-actions bot added enhancement New feature or request and removed enhancement New feature or request labels Oct 1, 2025
@github-actions github-actions bot added enhancement New feature or request and removed enhancement New feature or request labels Oct 1, 2025
…onvert_camel_case_to_snake_case for clarity and consistency

🔧 (test_mcp_util.py): refactor util function _convert_camel_case_to_snake_case to improve readability and maintainability
🔧 (test_mcp_util.py): handle tool validation errors with detailed error messages for better debugging and user guidance
🔧 (util.py): refactor create_tool_coroutine and create_tool_func to use _convert_camel_case_to_snake_case for field name conversion
🔧 (util.py): refactor update_tools function to handle tool validation errors with detailed error messages for better debugging and user guidance
🔧 (amazon_bedrock_model.py): deprecate AmazonBedrockComponent in favor of Amazon Bedrock Converse for improved features and compatibility
🔧 (json_schema.py): refactor _snake_to_camel function to handle leading and trailing underscores for more accurate conversion
@github-actions github-actions bot added enhancement New feature or request and removed enhancement New feature or request labels Oct 1, 2025
# Using the new flattened component access
from lfx import components as cp

# Using the new flattened component access
Copy link
Collaborator

Choose a reason for hiding this comment

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

what is this?

Copy link
Member Author

Choose a reason for hiding this comment

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

just merge issue with the comments.

# Test with camelCase fields
result = tool_func(userName="testuser", maxResults=10)

assert result == "sync_result"
Copy link
Collaborator

Choose a reason for hiding this comment

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

Are these mocks still testing what we want them to?

Copy link
Member Author

Choose a reason for hiding this comment

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

yes, just various scenarios testing the in/out of the function xD

Comment on lines +1 to +6
from langflow.base.models.aws_constants import AWS_REGIONS, AWS_MODEL_IDs
from langflow.base.models.model import LCModelComponent
from langflow.field_typing import LanguageModel
from langflow.inputs.inputs import BoolInput, FloatInput, IntInput, MessageTextInput, SecretStrInput
from langflow.io import DictInput, DropdownInput

Copy link
Collaborator

Choose a reason for hiding this comment

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

Is this true? I see you resolved but just checking since the imports could technically be moved to lfx

)
icon = "Amazon"
name = "AmazonBedrockModel"
legacy = True
Copy link
Collaborator

Choose a reason for hiding this comment

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

There's a flag called replacement.

e.g.

    replacement = "amazon.AmazonConverseWhateverTheCorrectNameIs"

if "_" in prop_name:
camel_case_name = _snake_to_camel(prop_name)
if camel_case_name != prop_name: # Only add alias if it's different
field_kwargs["validation_alias"] = AliasChoices(prop_name, camel_case_name)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Awesome. Would mention an abbreviated version of this somewhere wherever this is being done in MCP

@github-actions github-actions bot added the lgtm This PR has been approved by a maintainer label Oct 1, 2025
…nt access

♻️ (amazon_bedrock_converse.py): refactor import statements for better organization and readability
♻️ (amazon_bedrock_model.py): refactor class attributes for better clarity and maintainability
@github-actions github-actions bot added enhancement New feature or request and removed enhancement New feature or request labels Oct 1, 2025
@Cristhianzl Cristhianzl enabled auto-merge October 2, 2025 13:30
@github-actions github-actions bot added enhancement New feature or request and removed enhancement New feature or request labels Oct 2, 2025
@sonarqubecloud
Copy link

sonarqubecloud bot commented Oct 2, 2025

@Cristhianzl Cristhianzl added this pull request to the merge queue Oct 2, 2025
Merged via the queue into main with commit db3ed7f Oct 2, 2025
31 of 33 checks passed
@Cristhianzl Cristhianzl deleted the cz/fix-events-agent branch October 2, 2025 13:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request lgtm This PR has been approved by a maintainer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants