feat: Add Converse component and improve output extraction#9901
feat: Add Converse component and improve output extraction#9901Cristhianzl merged 17 commits intomainfrom
Conversation
…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.
|
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 WalkthroughIntroduces 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
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
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
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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60–90 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Pre-merge checks and finishing touches✅ 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 |
Codecov Report✅ All modified and coverable lines are covered by tests. ❌ 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@@ 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
Flags with carried forward coverage won't be shown. Click here to find out more. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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:awaitat 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.asyncioand 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 andawaitinstead 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 missingpytest.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 syncIf 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 typosAvoid 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 reMinor 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
📒 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.pysrc/backend/tests/unit/test_simple_agent_in_lfx_run.pysrc/backend/tests/unit/components/agents/test_agent_events.pysrc/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.pysrc/backend/tests/unit/test_simple_agent_in_lfx_run.pysrc/backend/tests/unit/components/agents/test_agent_events.pysrc/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.pysrc/backend/tests/unit/components/agents/test_agent_events.pysrc/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
iconattribute 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 — LGTMClear, 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 — LGTMKeeps 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 loopcreate_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 — LGTMApplying _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 controlChatBedrockConverse 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 — LGTMThorough coverage of exact-match, conversions, edge cases, and value preservation. Clear docstrings.
415-611: Wrapper integration tests — LGTMGood 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.
| 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 | ||
|
|
There was a problem hiding this comment.
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.
| 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.
There was a problem hiding this comment.
Is this true? I see you resolved but just checking since the imports could technically be moved to lfx
There was a problem hiding this comment.
🧩 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): usesfrom lfx.base.models.aws_constants import...amazon_bedrock_embedding.py(same directory): usesfrom 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.pyis the only file in thelfxpackage usinglangflow.*imports- The
langflowpackage exists insrc/backend/langflow/, but this file is insrc/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>
…ed to parameter conversion in MCPStructuredTool ♻️ (util.py): Refactor MCPStructuredTool to handle parameter conversion before LangChain validation for camelCase to snake_case conversion.
ogabrielluiz
left a comment
There was a problem hiding this comment.
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
…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
… into cz/fix-events-agent
| # Using the new flattened component access | ||
| from lfx import components as cp | ||
|
|
||
| # Using the new flattened component access |
There was a problem hiding this comment.
just merge issue with the comments.
| # Test with camelCase fields | ||
| result = tool_func(userName="testuser", maxResults=10) | ||
|
|
||
| assert result == "sync_result" |
There was a problem hiding this comment.
Are these mocks still testing what we want them to?
There was a problem hiding this comment.
yes, just various scenarios testing the in/out of the function xD
| 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 | ||
|
|
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
Awesome. Would mention an abbreviated version of this somewhere wherever this is being done in MCP
…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
|



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_textfunction (including edge cases and backward compatibility), and updates to use therun_until_completehelper for asynchronous toolkit initialization in agent-related tests.Testing improvements:
TestFieldNameConversiontotest_mcp_util.pyto cover all scenarios of camelCase to snake_case conversion, including edge cases, integration with Pydantic schemas, and value preservation. Also addedTestToolExecutionWithFieldConversionto verify that tool execution functions correctly handle field name conversion in both async and sync contexts._extract_output_textfunction intest_agent_events.py, covering various input formats, edge cases, backward compatibility, and specific scenarios related to ChatBedrockConverse and streaming responses.Async handling consistency:
simple_agent.pyandtest_simple_agent_in_lfx_run.py) to use therun_until_completehelper fromlfx.utils.async_helpersfor initializing toolkits, ensuring consistent async execution patterns across tests. [1] [2] [3] [4] [5]Test imports and dependencies:
_extract_output_textintest_agent_events.pyto enable direct testing of this utility.Summary by CodeRabbit
New Features
Improvements
Bug Fixes
Documentation
https://www.loom.com/share/959bd9ea2ee44873852e6f79dc0750a5?sid=5afa3f75-e724-4a8f-874b-55027a2afbdb