sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
langflow-ai/langflow:src/lfx/tests/unit/cli/test_run_real_flows.py
"""Integration tests for the run command with real flows.""" import json from pathlib import Path import pytest from lfx.__main__ import app from typer.testing import CliRunner runner = CliRunner() class TestExecuteRealFlows: """Test run command with real flow files.""" @pytest.fixture def test_data_dir(self): """Get the test data directory.""" return Path(__file__).parent.parent.parent / "data" @pytest.fixture def simple_chat_json(self, test_data_dir): """Path to the simple chat JSON flow.""" return test_data_dir / "simple_chat_no_llm.json" @pytest.fixture def simple_chat_py(self, test_data_dir): """Path to the simple chat Python script.""" return test_data_dir / "simple_chat_no_llm.py" def test_run_json_flow_basic(self, simple_chat_json): """Test executing a basic JSON flow.""" result = runner.invoke( app, ["run", str(simple_chat_json), "Hello from test!"], ) # Should succeed assert result.exit_code == 0 # Parse output - should be valid JSON output = json.loads(result.stdout) assert output["success"] is True assert "result" in output assert "Hello from test!" in output["result"] def test_run_json_flow_verbose(self, simple_chat_json): """Test executing with verbose output.""" result = runner.invoke( app, ["run", "-vv", str(simple_chat_json), "Test verbose"], ) # Should succeed assert result.exit_code == 0 # Verbose output should contain diagnostic messages assert "Analyzing JSON flow" in result.stderr assert "Valid JSON flow file detected" in result.stderr assert "Loading and executing JSON flow" in result.stderr assert "Preparing graph for execution" in result.stderr # Even in verbose mode, output should have the JSON result # When using CliRunner, check result.output which contains combined stdout/stderr json_output = result.stdout if result.stdout else result.output # Find the JSON block by looking for lines that start with { and collecting until } json_lines = [] in_json = False brace_count = 0 for line in json_output.split("\n"): line_stripped = line.strip() if not in_json and line_stripped.startswith("{"): in_json = True json_lines = [line] brace_count = line.count("{") - line.count("}") elif in_json: json_lines.append(line) brace_count += line.count("{") - line.count("}") if brace_count == 0: # Found complete JSON object break if json_lines: try: json_str = "\n".join(json_lines) output = json.loads(json_str) except json.JSONDecodeError as e: pytest.fail(f"Failed to parse JSON: {e}. JSON was: {json_str[:500]}") else: # If we couldn't find valid JSON, show what we got for debugging pytest.fail(f"No valid JSON output found. Output was: {json_output[:500]}") assert output["success"] is True assert "result" in output assert "Test verbose" in output["result"] @pytest.mark.parametrize("fmt", ["json", "text", "message", "result"]) def test_run_json_flow_different_formats(self, simple_chat_json, fmt): """Test different output formats.""" result = runner.invoke( app, ["run", "-f", fmt, str(simple_chat_json), f"Test {fmt} format"], ) # Should succeed assert result.exit_code == 0 assert len(result.stdout) > 0 if fmt == "json": # Should be valid JSON output = json.loads(result.stdout) assert output["success"] is True assert "result" in output assert f"Test {fmt} format" in output["result"] else: # For other formats, check output contains the message assert f"Test {fmt} format" in result.stdout def test_run_json_flow_with_stdin(self, simple_chat_json): """Test executing JSON flow from stdin.""" with simple_chat_json.open() as f: json_content = f.read() result = runner.invoke( app, ["run", "--stdin", "--input-value", "Hello from stdin!"], input=json_content, ) # Should succeed assert result.exit_code == 0 # Parse output output = json.loads(result.stdout) assert output["success"] is True assert "result" in output assert "Hello from stdin!" in output["result"] def test_run_json_flow_inline(self, simple_chat_json): """Test executing JSON flow passed inline.""" with simple_chat_json.open() as f: json_content = f.read() result = runner.invoke( app, ["run", "--flow-json", json_content, "--input-value", "Hello inline!"], ) # Should succeed assert result.exit_code == 0 # Parse output output = json.loads(result.stdout) assert output["success"] is True assert "result" in output assert "Hello inline!" in output["result"] def test_run_python_script(self, simple_chat_py): """Test executing a Python script with a graph.""" # Python script should exist assert simple_chat_py.exists() result = runner.invoke( app, ["run", str(simple_chat_py), "Hello from Python!"], ) # Should succeed assert result.exit_code == 0 # Parse output - should be JSON output = json.loads(result.stdout) assert output["success"] is True assert "result" in output assert "Hello from Python!" in output["result"] def test_run_no_input_value(self, simple_chat_json): """Test executing without input value.""" result = runner.invoke( app, ["run", str(simple_chat_json)], ) # Should succeed even without input assert result.exit_code == 0 # Parse output output = json.loads(result.stdout) assert output["success"] is True assert "result" in output def test_run_check_variables(self, simple_chat_json): """Test the check-variables functionality.""" result = runner.invoke( app, ["run", "--check-variables", str(simple_chat_json), "Test"], ) # Should succeed as simple_chat_no_llm doesn't have global variables assert result.exit_code == 0 # Parse output output = json.loads(result.stdout) assert output["success"] is True assert "result" in output def test_run_no_check_variables(self, simple_chat_json): """Test disabling variable checking.""" result = runner.invoke( app, ["run", "--no-check-variables", str(simple_chat_json), "Test"], ) # Should succeed assert result.exit_code == 0 # Parse output output = json.loads(result.stdout) assert output["success"] is True assert "result" in output def test_run_error_cases(self): """Test various error cases.""" # No input source result = runner.invoke(app, ["execute"]) assert result.exit_code == 2 # Typer returns 2 for missing required arguments # Typer's error message will be different from our custom message # Non-existent file result = runner.invoke(app, ["run", "does_not_exist.json"]) assert result.exit_code == 1 # Without verbose, error should be JSON in stdout # Extract the last line which should be the JSON error lines = result.stdout.strip().split("\n") json_line = lines[-1] if lines else "" if json_line: error_output = json.loads(json_line) assert error_output["success"] is False assert "exception_message" in error_output, f"Got: {error_output}" assert "does not exist" in error_output["exception_message"], f"Got: {error_output}" # Invalid file extension result = runner.invoke(app, ["run", "test.txt"]) assert result.exit_code == 1 # Without verbose, error should be JSON in stdout # Extract the last line which should be the JSON error lines = result.stdout.strip().split("\n") json_line = lines[-1] if lines else "" if json_line: error_output = json.loads(json_line) assert error_output["success"] is False # The error could be either "does not exist" or "must be a .py or .json file" # depending on whether the file exists assert "exception_message" in error_output, f"Got: {error_output}" assert ( "does not exist" in error_output["exception_message"] or "must be a .py or .json file" in error_output["exception_message"] ), f"Got: {error_output}" # Multiple input sources result = runner.invoke( app, ["run", "--stdin", "--flow-json", '{"data": {}}', "test"], ) assert result.exit_code == 1 # Without verbose, error should be JSON in stdout lines = result.stdout.strip().split("\n") json_line = lines[-1] if lines else "" if json_line: error_output = json.loads(json_line) assert error_output["success"] is False assert "exception_message" in error_output, f"Got: {error_output}" assert "Multiple input sources" in error_output["exception_message"], f"Got: {error_output}" def test_run_input_precedence(self, simple_chat_json): """Test input value precedence (positional over option).""" result = runner.invoke( app, [ "run", str(simple_chat_json), "positional_value", "--input-value", "option_value", ], ) # Should succeed assert result.exit_code == 0 # Parse output and verify positional value was used output = json.loads(result.stdout) assert output["success"] is True assert "result" in output assert "positional_value" in output["result"] assert "option_value" not in output["result"] def test_run_json_output_format(self, simple_chat_json): """Test that JSON output is single-line when not verbose, multi-line when verbose.""" # Non-verbose mode - should be compact single-line JSON result = runner.invoke( app, ["run", str(simple_chat_json), "Test compact"], ) # Should succeed assert result.exit_code == 0 # Output should be single line (no newlines except at the end) assert result.stdout.count("\n") == 1 # Only the trailing newline # Should still be valid JSON output = json.loads(result.stdout) assert output["success"] is True assert "Test compact" in output["result"] # Verbose mode - should be pretty-printed multi-line JSON result_verbose = runner.invoke( app, ["run", "--verbose", str(simple_chat_json), "Test pretty"], ) # Should succeed assert result_verbose.exit_code == 0 # output should have pretty-printed JSON (multi-line) json_output = result_verbose.stdout if result_verbose.stdout else result_verbose.output # Find the JSON block by looking for lines that start with { and collecting until } json_lines = [] in_json = False brace_count = 0 for line in json_output.split("\n"): line_stripped = line.strip() if not in_json and line_stripped.startswith("{"): in_json = True json_lines = [line] brace_count = line.count("{") - line.count("}") elif in_json: json_lines.append(line) brace_count += line.count("{") - line.count("}") if brace_count == 0: # Found complete JSON object break if json_lines: try: json_str = "\n".join(json_lines) output = json.loads(json_str) except json.JSONDecodeError as e: pytest.fail(f"Failed to parse JSON: {e}. JSON was: {json_str[:500]}") else: pytest.fail("No JSON output found") assert output["success"] is True assert "Test pretty" in output["result"] def test_run_error_output_verbose(self): """Test that errors go to stderr when verbose is true.""" # Non-existent file with verbose flag result = runner.invoke(app, ["run", "--verbose", "does_not_exist.json"]) assert result.exit_code == 1 # With verbose, error should be in stderr, not JSON in stdout assert "does not exist" in result.stderr # stdout should not contain JSON error if result.stdout: # If there's any stdout, it shouldn't be a JSON error try: output = json.loads(result.stdout) assert output.get("success") is False, f"Got: {output}" except json.JSONDecodeError: pytest.fail(f"Unexpected non-JSON stdout: {result.stdout}") class TestAsyncFunctionality: """Test that async functions are being called correctly.""" @pytest.fixture def test_data_dir(self): """Get the test data directory.""" return Path(__file__).parent.parent.parent / "data" @pytest.fixture def simple_chat_json(self, test_data_dir): """Path to the simple chat JSON flow.""" return test_data_dir / "simple_chat_no_llm.json" def test_async_load_is_used(self, simple_chat_json, monkeypatch): """Test that aload_flow_from_json is being used - expects failure in lfx environment.""" from lfx.load import aload_flow_from_json # Track if the async function was called async_called = False original_aload = aload_flow_from_json async def mock_aload(*args, **kwargs): nonlocal async_called async_called = True return await original_aload(*args, **kwargs) monkeypatch.setattr("lfx.load.aload_flow_from_json", mock_aload) result = runner.invoke( app, ["run", str(simple_chat_json), "Test async"], ) # Should succeed assert result.exit_code == 0 assert async_called, "aload_flow_from_json should have been called" # Parse output output = json.loads(result.stdout) assert output["success"] is True assert "result" in output def test_async_start_is_used(self, simple_chat_json): """Test that graph.async_start is being used.""" # This is harder to test without mocking the entire graph, # but we can at least verify the flow completes successfully result = runner.invoke( app, ["run", "--verbose", str(simple_chat_json), "Test async start"], ) # Should succeed assert result.exit_code == 0 # If async_start wasn't working, we'd get an error output = json.loads(result.stdout) assert output["success"] is True assert "result" in output
{ "repo_id": "langflow-ai/langflow", "file_path": "src/lfx/tests/unit/cli/test_run_real_flows.py", "license": "MIT License", "lines": 359, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/lfx/tests/unit/cli/test_script_loader.py
"""Unit tests for LFX CLI script loader.""" import sys import tempfile from pathlib import Path from unittest.mock import MagicMock, patch import pytest from lfx.cli.script_loader import ( _load_module_from_script, _validate_graph_instance, extract_message_from_result, extract_structured_result, extract_text_from_result, find_graph_variable, load_graph_from_script, temporary_sys_path, ) @pytest.fixture def test_data_dir(): """Get the test data directory.""" return Path(__file__).parent.parent.parent / "data" @pytest.fixture def simple_chat_py(test_data_dir): """Path to the simple chat Python script.""" return test_data_dir / "simple_chat_no_llm.py" class TestSysPath: """Test sys.path manipulation utilities.""" def test_temporary_sys_path_adds_and_removes(self): """Test that temporary_sys_path correctly adds and removes path.""" test_path = "/test/path" original_path = sys.path.copy() assert test_path not in sys.path with temporary_sys_path(test_path): assert test_path in sys.path assert sys.path[0] == test_path assert test_path not in sys.path assert sys.path == original_path def test_temporary_sys_path_already_exists(self): """Test temporary_sys_path when path already exists.""" test_path = sys.path[0] # Use existing path original_path = sys.path.copy() with temporary_sys_path(test_path): # Should not add duplicate assert sys.path == original_path assert sys.path == original_path def test_temporary_sys_path_with_exception(self): """Test that path is removed even if exception occurs.""" test_path = "/test/exception/path" def assert_and_raise_exception(): assert test_path in sys.path msg = "Test exception" raise ValueError(msg) # Test that the path is removed even when an exception occurs with pytest.raises(ValueError, match="Test exception"), temporary_sys_path(test_path): assert_and_raise_exception() assert test_path not in sys.path class TestModuleLoading: """Test module loading functionality.""" def test_load_module_from_script_success(self): """Test successful module loading from script.""" with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f: f.write("test_var = 'Hello World'\n") f.write("def test_func(): return 42\n") script_path = Path(f.name) try: module = _load_module_from_script(script_path) assert hasattr(module, "test_var") assert module.test_var == "Hello World" assert hasattr(module, "test_func") assert module.test_func() == 42 finally: script_path.unlink() def test_load_module_from_script_import_error(self): """Test module loading with import error.""" with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f: f.write("import non_existent_module\n") script_path = Path(f.name) try: with pytest.raises(ImportError): _load_module_from_script(script_path) finally: script_path.unlink() def test_load_module_from_script_syntax_error(self): """Test module loading with syntax error.""" with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f: f.write("def broken_func(\n") # Invalid syntax script_path = Path(f.name) try: with pytest.raises(SyntaxError): _load_module_from_script(script_path) finally: script_path.unlink() class TestGraphValidation: """Test graph validation functionality.""" def test_validate_graph_instance_valid(self): """Test validation of valid graph instance.""" from lfx.components.input_output import ChatInput, ChatOutput from lfx.graph import Graph # Create a real graph with ChatInput and ChatOutput chat_input = ChatInput() chat_output = ChatOutput().set(input_value=chat_input.message_response) graph = Graph(chat_input, chat_output) result = _validate_graph_instance(graph) assert result == graph def test_validate_graph_instance_wrong_type(self): """Test validation with wrong type.""" not_a_graph = {"not": "a graph"} with pytest.raises(TypeError, match="Graph object is not a LFX Graph instance"): _validate_graph_instance(not_a_graph) def test_validate_graph_instance_missing_chat_input(self): """Test validation with missing ChatInput.""" from lfx.components.input_output import ChatOutput from lfx.graph import Graph # Create a graph with only ChatOutput, no ChatInput chat_output = ChatOutput() graph = Graph(start=chat_output, end=chat_output) with pytest.raises(ValueError, match="Graph does not contain any ChatInput component"): _validate_graph_instance(graph) def test_validate_graph_instance_missing_chat_output(self): """Test validation with missing ChatOutput.""" from lfx.components.input_output import ChatInput from lfx.graph import Graph # Create a graph with only ChatInput, no ChatOutput chat_input = ChatInput() graph = Graph(start=chat_input, end=chat_input) with pytest.raises(ValueError, match="Graph does not contain any ChatOutput component"): _validate_graph_instance(graph) class TestLoadGraphFromScript: """Test loading graph from script functionality.""" async def test_load_graph_from_script_success(self, simple_chat_py): """Test successful graph loading from script with real Graph object.""" # Use the existing test data file graph = await load_graph_from_script(simple_chat_py) # Verify it's a real Graph instance from lfx.graph import Graph assert isinstance(graph, Graph) # Verify it has the expected components component_names = {v.custom_component.__class__.__name__ for v in graph.vertices} assert "ChatInput" in component_names assert "ChatOutput" in component_names async def test_load_graph_from_script_no_graph_variable(self): """Test error when script has no graph variable.""" with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f: f.write("other_var = 123\n") script_path = Path(f.name) try: with pytest.raises(RuntimeError, match="No 'graph' variable or 'get_graph\\(\\)' function found"): await load_graph_from_script(script_path) finally: script_path.unlink() async def test_load_graph_from_script_import_error(self): """Test error handling for import errors.""" script_path = Path("/non/existent/script.py") with pytest.raises(RuntimeError, match="Error executing script"): await load_graph_from_script(script_path) async def test_load_graph_from_script_with_async_get_graph(self): """Test loading graph from script with async get_graph function.""" with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f: f.write("from lfx.components.input_output import ChatInput, ChatOutput\n") f.write("from lfx.graph import Graph\n") f.write("\n") f.write("async def get_graph():\n") f.write(" chat_input = ChatInput()\n") f.write(" chat_output = ChatOutput().set(input_value=chat_input.message_response)\n") f.write(" return Graph(chat_input, chat_output)\n") script_path = Path(f.name) try: graph = await load_graph_from_script(script_path) # Verify it's a real Graph instance from lfx.graph import Graph assert isinstance(graph, Graph) # Verify it has the expected components component_names = {v.custom_component.__class__.__name__ for v in graph.vertices} assert "ChatInput" in component_names assert "ChatOutput" in component_names finally: script_path.unlink() async def test_load_graph_from_script_with_sync_get_graph(self): """Test loading graph from script with sync get_graph function.""" with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f: f.write("from lfx.components.input_output import ChatInput, ChatOutput\n") f.write("from lfx.graph import Graph\n") f.write("\n") f.write("def get_graph():\n") f.write(" chat_input = ChatInput()\n") f.write(" chat_output = ChatOutput().set(input_value=chat_input.message_response)\n") f.write(" return Graph(chat_input, chat_output)\n") script_path = Path(f.name) try: graph = await load_graph_from_script(script_path) # Verify it's a real Graph instance from lfx.graph import Graph assert isinstance(graph, Graph) # Verify it has the expected components component_names = {v.custom_component.__class__.__name__ for v in graph.vertices} assert "ChatInput" in component_names assert "ChatOutput" in component_names finally: script_path.unlink() class TestResultExtraction: """Test result extraction utilities.""" def test_extract_message_from_result_success(self): """Test extracting message from result.""" from lfx.graph.schema import ResultData from lfx.schema.message import Message # Create a real Message object message = Message(text="Hello") # Create ResultData with the message result_data = ResultData( results={"message": message}, component_display_name="Chat Output", component_id="test-123" ) # Create a minimal mock for the vertex structure mock_result = MagicMock() mock_result.vertex.custom_component.display_name = "Chat Output" mock_result.result_dict = result_data results = [mock_result] message_json = extract_message_from_result(results) assert "Hello" in message_json assert "text" in message_json def test_extract_message_from_result_no_chat_output(self): """Test extraction when no Chat Output found.""" mock_result = MagicMock() mock_result.vertex.custom_component.display_name = "Other Component" results = [mock_result] message = extract_message_from_result(results) assert message == "No response generated" def test_extract_text_from_result_success(self): """Test extracting text content from result.""" from lfx.graph.schema import ResultData from lfx.schema.message import Message # Create a real Message object message = Message(text="Hello World") # Create ResultData with the message result_data = ResultData( results={"message": message}, component_display_name="Chat Output", component_id="test-123" ) # Create a minimal mock for the vertex structure mock_result = MagicMock() mock_result.vertex.custom_component.display_name = "Chat Output" mock_result.result_dict = result_data results = [mock_result] text = extract_text_from_result(results) assert text == "Hello World" def test_extract_text_from_result_no_text_attribute(self): """Test extraction when message has no text attribute.""" from lfx.graph.schema import ResultData # Use a plain string as message result_data = ResultData( results={"message": "Plain string message"}, component_display_name="Chat Output", component_id="test-123" ) mock_result = MagicMock() mock_result.vertex.custom_component.display_name = "Chat Output" mock_result.result_dict = result_data results = [mock_result] text = extract_text_from_result(results) assert text == "Plain string message" def test_extract_text_from_result_with_dict_message(self): """Test extraction when message is a dict with text key.""" from lfx.graph.schema import ResultData # Use a dict as message result_data = ResultData( results={"message": {"text": "Dict message text"}}, component_display_name="Chat Output", component_id="test-123", ) mock_result = MagicMock() mock_result.vertex.custom_component.display_name = "Chat Output" mock_result.result_dict = result_data results = [mock_result] text = extract_text_from_result(results) assert text == "Dict message text" def test_extract_structured_result_success(self): """Test extracting structured result data.""" from lfx.graph.schema import ResultData from lfx.schema.message import Message # Create a real Message object message = Message(text="Test message") # Create ResultData with the message result_data = ResultData( results={"message": message}, component_display_name="Chat Output", component_id="vertex-123" ) mock_result = MagicMock() mock_result.vertex.custom_component.display_name = "Chat Output" mock_result.vertex.id = "vertex-123" mock_result.result_dict = result_data results = [mock_result] structured = extract_structured_result(results, extract_text=True) assert structured == { "result": "Test message", "type": "message", "component": "Chat Output", "component_id": "vertex-123", "success": True, } def test_extract_structured_result_no_text_extraction(self): """Test structured extraction without text extraction.""" from lfx.graph.schema import ResultData from lfx.schema.message import Message # Create a real Message object message = Message(text="Test message") # Create ResultData with the message result_data = ResultData( results={"message": message}, component_display_name="Chat Output", component_id="vertex-123" ) mock_result = MagicMock() mock_result.vertex.custom_component.display_name = "Chat Output" mock_result.vertex.id = "vertex-123" mock_result.result_dict = result_data results = [mock_result] structured = extract_structured_result(results, extract_text=False) assert structured["result"] == message assert structured["type"] == "message" assert structured["component"] == "Chat Output" assert structured["success"] is True def test_extract_structured_result_extraction_error(self): """Test structured extraction with error.""" from lfx.graph.schema import ResultData # Create a custom message class that has text attribute but raises when accessed class ErrorMessage: @property def text(self): msg = "No text available" raise AttributeError(msg) def __str__(self): return "ErrorMessage instance" # Create ResultData with the error message result_data = ResultData( results={"message": ErrorMessage()}, component_display_name="Chat Output", component_id="vertex-123" ) mock_result = MagicMock() mock_result.vertex.custom_component.display_name = "Chat Output" mock_result.vertex.id = "vertex-123" mock_result.result_dict = result_data results = [mock_result] structured = extract_structured_result(results, extract_text=True) # Since hasattr returns False for properties that raise AttributeError, # the code returns the message object itself (no warning) assert structured["success"] is True assert "warning" not in structured # No warning because hasattr is False assert structured["result"] == result_data.results["message"] # Returns the ErrorMessage instance assert structured["type"] == "message" assert structured["component"] == "Chat Output" def test_extract_structured_result_no_results(self): """Test structured extraction with no results.""" results = [] structured = extract_structured_result(results) assert structured == { "text": "No response generated", "type": "error", "success": False, } class TestFindGraphVariable: """Test AST-based graph variable finding.""" def test_find_graph_variable_function_call(self): """Test finding graph variable with function call.""" with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f: f.write("from lfx import Graph\n") f.write("\n") f.write("graph = Graph(nodes=[], edges=[])\n") script_path = Path(f.name) try: result = find_graph_variable(script_path) assert result is not None assert result["type"] == "function_call" assert result["function"] == "Graph" assert result["line_number"] == 3 assert "graph = Graph" in result["source_line"] finally: script_path.unlink() def test_find_graph_variable_method_call(self): """Test finding graph variable with method call.""" with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f: f.write("from lfx import Graph\n") f.write("\n") f.write("graph = Graph.from_payload(data)\n") script_path = Path(f.name) try: result = find_graph_variable(script_path) assert result is not None assert result["type"] == "function_call" assert result["function"] == "Graph.from_payload" assert result["line_number"] == 3 finally: script_path.unlink() def test_find_graph_variable_assignment(self): """Test finding graph variable with simple assignment.""" with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f: f.write("existing_graph = get_graph()\n") f.write("graph = existing_graph\n") script_path = Path(f.name) try: result = find_graph_variable(script_path) assert result is not None assert result["type"] == "assignment" assert result["line_number"] == 2 assert "graph = existing_graph" in result["source_line"] finally: script_path.unlink() def test_find_graph_variable_not_found(self): """Test when no graph variable is found.""" with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f: f.write("other_var = 123\n") f.write("another_var = 'test'\n") script_path = Path(f.name) try: result = find_graph_variable(script_path) assert result is None finally: script_path.unlink() def test_find_graph_variable_syntax_error(self): """Test handling of syntax errors.""" with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f: f.write("def broken(\n") # Invalid syntax script_path = Path(f.name) try: with patch("typer.echo") as mock_echo: result = find_graph_variable(script_path) assert result is None mock_echo.assert_called_once() assert "Invalid Python syntax" in mock_echo.call_args[0][0] finally: script_path.unlink() def test_find_graph_variable_file_not_found(self): """Test handling of missing file.""" script_path = Path("/non/existent/file.py") with patch("typer.echo") as mock_echo: result = find_graph_variable(script_path) assert result is None mock_echo.assert_called_once() assert "not found" in mock_echo.call_args[0][0] class TestIntegrationWithRealFlows: """Integration tests using real flows and minimal mocking.""" async def test_load_and_validate_real_script(self, simple_chat_py): """Test loading and validating a real script file.""" # Load the real graph from the script graph = await load_graph_from_script(simple_chat_py) # Verify it's a real Graph from lfx.graph import Graph assert isinstance(graph, Graph) # Verify components component_types = {v.custom_component.__class__.__name__ for v in graph.vertices} assert "ChatInput" in component_types assert "ChatOutput" in component_types async def test_execute_real_flow_with_results(self, simple_chat_py): """Test executing a real flow and extracting results.""" # Load the real graph graph = await load_graph_from_script(simple_chat_py) # Execute the graph with real input from lfx.graph.schema import RunOutputs # Start the graph execution results = [result async for result in graph.async_start(inputs={"input_value": "Test message"})] # Extract results using our functions if isinstance(results, RunOutputs) and results.outputs: # Convert RunOutputs to the format expected by extract functions result_list = [] for output in results.outputs: mock_result = MagicMock() mock_result.vertex.custom_component.display_name = output.component_display_name mock_result.vertex.id = output.component_id mock_result.result_dict = output result_list.append(mock_result) # Test extraction functions with real results text = extract_text_from_result(result_list) assert "Test message" in text message_json = extract_message_from_result(result_list) assert "Test message" in message_json structured = extract_structured_result(result_list) assert structured["success"] is True assert "Test message" in str(structured["result"])
{ "repo_id": "langflow-ai/langflow", "file_path": "src/lfx/tests/unit/cli/test_script_loader.py", "license": "MIT License", "lines": 468, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/lfx/tests/unit/cli/test_serve.py
"""Tests for LFX serve command.""" import json import os import tempfile from pathlib import Path from unittest.mock import AsyncMock, MagicMock, patch import pytest from fastapi.testclient import TestClient from lfx.cli.common import ( flow_id_from_path, get_api_key, get_best_access_host, get_free_port, is_port_in_use, ) from lfx.cli.serve_app import FlowMeta, create_multi_serve_app def test_is_port_in_use(): """Test port availability checking.""" # Port 0 should always be available (OS assigns) assert not is_port_in_use(0) # Very high ports are likely available assert not is_port_in_use(65123) def test_get_free_port(): """Test finding a free port.""" port = get_free_port(8000) assert 8000 <= port < 65535 assert not is_port_in_use(port) def test_get_best_access_host(): """Test host resolution for display.""" assert get_best_access_host("0.0.0.0") == "localhost" assert get_best_access_host("") == "localhost" assert get_best_access_host("127.0.0.1") == "127.0.0.1" assert get_best_access_host("example.com") == "example.com" def test_get_api_key_missing(): """Test API key retrieval when not set.""" with ( patch.dict(os.environ, {}, clear=True), pytest.raises( ValueError, match="LANGFLOW_API_KEY environment variable is not set", ), ): get_api_key() def test_get_api_key_present(): """Test API key retrieval when set.""" with patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-key-123"}): # pragma: allowlist secret assert get_api_key() == "test-key-123" def test_flow_id_from_path(): """Test deterministic flow ID generation.""" root = Path("/tmp/flows") path1 = root / "flow1.json" path2 = root / "subdir" / "flow2.json" # Same path should always generate same ID id1a = flow_id_from_path(path1, root) id1b = flow_id_from_path(path1, root) assert id1a == id1b # Different paths should generate different IDs id2 = flow_id_from_path(path2, root) assert id1b != id2 @pytest.fixture def mock_graph(): """Create a mock graph for testing.""" graph = MagicMock() graph.nodes = {"node1": MagicMock()} graph.prepare = MagicMock() graph.arun = AsyncMock(return_value=[]) return graph @pytest.fixture def test_flow_meta(): """Create test flow metadata.""" return FlowMeta( id="test-flow-id", relative_path="test.json", title="Test Flow", description="A test flow", ) def test_create_multi_serve_app_single_flow(mock_graph, test_flow_meta): """Test creating app for single flow.""" with patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-key"}): # pragma: allowlist secret app = create_multi_serve_app( root_dir=Path("/tmp"), graphs={"test-flow-id": mock_graph}, metas={"test-flow-id": test_flow_meta}, verbose_print=lambda x: None, # noqa: ARG005 ) client = TestClient(app) # Test health endpoint response = client.get("/health") assert response.status_code == 200 assert response.json() == {"status": "healthy", "flow_count": 1} # Test run endpoint without auth response = client.post("/flows/test-flow-id/run", json={"input_value": "test"}) assert response.status_code == 401 # Test run endpoint with auth response = client.post( "/flows/test-flow-id/run", json={"input_value": "test"}, headers={"x-api-key": "test-key"}, ) assert response.status_code == 200 def test_create_multi_serve_app_multiple_flows(mock_graph, test_flow_meta): """Test creating app for multiple flows.""" meta2 = FlowMeta( id="flow-2", relative_path="flow2.json", title="Flow 2", description="Second flow", ) with patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-key"}): # pragma: allowlist secret app = create_multi_serve_app( root_dir=Path("/tmp"), graphs={"test-flow-id": mock_graph, "flow-2": mock_graph}, metas={"test-flow-id": test_flow_meta, "flow-2": meta2}, verbose_print=lambda x: None, # noqa: ARG005 ) client = TestClient(app) # Test flows listing response = client.get("/flows") assert response.status_code == 200 flows = response.json() assert len(flows) == 2 assert any(f["id"] == "test-flow-id" for f in flows) assert any(f["id"] == "flow-2" for f in flows) # Test individual flow run response = client.post( "/flows/test-flow-id/run", json={"input_value": "test"}, headers={"x-api-key": "test-key"}, ) assert response.status_code == 200 # Test flow info response = client.get( "/flows/test-flow-id/info", headers={"x-api-key": "test-key"}, ) assert response.status_code == 200 assert response.json()["id"] == "test-flow-id" def test_serve_command_json_file(): """Test serve command with JSON file input.""" # Create a temporary JSON flow file flow_data = { "nodes": [], "edges": [], } with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f: json.dump(flow_data, f) temp_path = f.name try: # Mock the necessary dependencies with ( patch("lfx.cli.commands.load_graph_from_path") as mock_load, patch("lfx.cli.commands.uvicorn.Server.serve", new=AsyncMock(return_value=None)) as mock_uvicorn, patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-key"}), # pragma: allowlist secret ): import typer from lfx.cli.commands import serve_command from typer.testing import CliRunner # Create a mock graph mock_graph = MagicMock() mock_graph.prepare = MagicMock() # Mock nodes as a dictionary for graph analysis mock_node = MagicMock() mock_node.data = { "type": "TestComponent", "display_name": "Test Component", "description": "A test component", "template": {}, } mock_graph.nodes = {"node1": mock_node} # Mock edges as a list mock_edge = MagicMock() mock_edge.source = "node1" mock_edge.target = "node2" mock_graph.edges = [mock_edge] mock_load.return_value = mock_graph # Create CLI app app = typer.Typer() app.command()(serve_command) runner = CliRunner() result = runner.invoke(app, [temp_path, "--verbose"]) assert result.exit_code == 0, result.stdout # Should start the server assert mock_uvicorn.called mock_load.assert_called_once() # Check that the mock was called with the correct arguments args, kwargs = mock_load.call_args assert args[0] == Path(temp_path).resolve() assert args[1] == ".json" # args[2] is the verbose_print function, which is harder to assert assert "verbose" in kwargs assert kwargs["verbose"] is True finally: Path(temp_path).unlink() def test_serve_command_inline_json(): """Test serve command with inline JSON.""" flow_json = '{"nodes": [], "edges": []}' with ( patch("lfx.cli.commands.load_graph_from_path") as mock_load, patch("lfx.cli.commands.uvicorn.Server.serve", new=AsyncMock(return_value=None)) as mock_uvicorn, patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-key"}), # pragma: allowlist secret ): import typer from lfx.cli.commands import serve_command from typer.testing import CliRunner # Create a mock graph mock_graph = MagicMock() mock_graph.prepare = MagicMock() mock_graph.nodes = {} mock_load.return_value = mock_graph # Create CLI app app = typer.Typer() app.command()(serve_command) runner = CliRunner() result = runner.invoke(app, ["--flow-json", flow_json, "--verbose"]) assert result.exit_code == 0, result.stdout # Should start the server assert mock_uvicorn.called mock_load.assert_called_once() # Check that the mock was called with the correct arguments args, kwargs = mock_load.call_args assert args[0].suffix == ".json" assert args[1] == ".json" assert "verbose" in kwargs assert kwargs["verbose"] is True
{ "repo_id": "langflow-ai/langflow", "file_path": "src/lfx/tests/unit/cli/test_serve.py", "license": "MIT License", "lines": 224, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/lfx/tests/unit/cli/test_serve_app.py
"""Unit tests for LFX CLI FastAPI serve app.""" import json import os from pathlib import Path from unittest.mock import MagicMock, Mock, patch import pytest from fastapi import HTTPException from fastapi.testclient import TestClient from lfx.cli.serve_app import ( FlowMeta, create_multi_serve_app, verify_api_key, ) from lfx.graph import Graph from lfx.graph.schema import ResultData from lfx.schema.message import Message class TestSecurityFunctions: """Test security-related functions.""" def test_verify_api_key_with_query_param(self): """Test API key verification with query parameter.""" with patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-key-123"}): # pragma: allowlist secret result = verify_api_key("test-key-123", None) assert result == "test-key-123" def test_verify_api_key_with_header_param(self): """Test API key verification with header parameter.""" with patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-key-123"}): # pragma: allowlist secret result = verify_api_key(None, "test-key-123") assert result == "test-key-123" def test_verify_api_key_header_takes_precedence(self): """Test that query parameter is used when both are provided.""" with patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-key-123"}): # pragma: allowlist secret result = verify_api_key("test-key-123", "wrong-key") assert result == "test-key-123" def test_verify_api_key_missing(self): """Test error when no API key is provided.""" with pytest.raises(HTTPException) as exc_info: verify_api_key(None, None) assert exc_info.value.status_code == 401 assert exc_info.value.detail == "API key required" def test_verify_api_key_invalid(self): """Test error when API key is invalid.""" with patch.dict(os.environ, {"LANGFLOW_API_KEY": "correct-key"}): # pragma: allowlist secret with pytest.raises(HTTPException) as exc_info: verify_api_key("wrong-key", None) assert exc_info.value.status_code == 401 assert exc_info.value.detail == "Invalid API key" def test_verify_api_key_env_not_set(self): """Test error when environment variable is not set.""" with patch.dict(os.environ, {}, clear=True): with pytest.raises(HTTPException) as exc_info: verify_api_key("any-key", None) assert exc_info.value.status_code == 500 assert "LANGFLOW_API_KEY environment variable is not set" in exc_info.value.detail class TestCreateServeApp: """Test FastAPI app creation.""" @pytest.fixture def simple_chat_json(self): """Load the simple chat JSON test data.""" test_data_dir = Path(__file__).parent.parent.parent / "data" json_path = test_data_dir / "simple_chat_no_llm.json" with json_path.open() as f: return json.load(f) @pytest.fixture def real_graph(self, simple_chat_json): """Create a real graph using Graph.from_payload to match serve_app expectations.""" # Create graph using from_payload with real test data return Graph.from_payload(simple_chat_json, flow_id="test-flow-id") @pytest.fixture def mock_meta(self): """Create mock flow metadata.""" return FlowMeta( id="test-flow-id", relative_path="test.json", title="Test Flow", description="A test flow", ) def test_create_multi_serve_app_single_flow(self, real_graph, mock_meta): """Test creating app with single flow.""" graphs = {"test-flow-id": real_graph} metas = {"test-flow-id": mock_meta} verbose_print = Mock() app = create_multi_serve_app( root_dir=Path("/test"), graphs=graphs, metas=metas, verbose_print=verbose_print, ) assert app.title == "LFX Multi-Flow Server (1)" assert "Use `/flows` to list available IDs" in app.description # Check routes routes = [route.path for route in app.routes] assert "/health" in routes assert "/flows" in routes # Multi-flow always has this assert "/flows/test-flow-id/run" in routes # Flow-specific endpoint def test_create_multi_serve_app_multiple_flows(self, real_graph, mock_meta, simple_chat_json): """Test creating app with multiple flows.""" # Create second real graph using from_payload graph2 = Graph.from_payload(simple_chat_json, flow_id="flow-2") meta2 = FlowMeta( id="flow-2", relative_path="flow2.json", title="Flow 2", description="Second flow", ) graphs = {"test-flow-id": real_graph, "flow-2": graph2} metas = {"test-flow-id": mock_meta, "flow-2": meta2} verbose_print = Mock() app = create_multi_serve_app( root_dir=Path("/test"), graphs=graphs, metas=metas, verbose_print=verbose_print, ) assert app.title == "LFX Multi-Flow Server (2)" assert "Use `/flows` to list available IDs" in app.description # Check routes routes = [route.path for route in app.routes] assert "/health" in routes assert "/flows" in routes assert "/flows/test-flow-id/run" in routes assert "/flows/test-flow-id/info" in routes assert "/flows/flow-2/run" in routes assert "/flows/flow-2/info" in routes def test_create_multi_serve_app_mismatched_keys(self, real_graph, mock_meta): """Test error when graphs and metas have different keys.""" graphs = {"test-flow-id": real_graph} metas = {"different-id": mock_meta} verbose_print = Mock() with pytest.raises(ValueError, match="graphs and metas must contain the same keys"): create_multi_serve_app( root_dir=Path("/test"), graphs=graphs, metas=metas, verbose_print=verbose_print, ) class TestServeAppEndpoints: """Test the FastAPI endpoints.""" @pytest.fixture def simple_chat_json(self): """Load the simple chat JSON test data.""" test_data_dir = Path(__file__).parent.parent.parent / "data" json_path = test_data_dir / "simple_chat_no_llm.json" with json_path.open() as f: return json.load(f) @pytest.fixture def real_graph_with_async(self, simple_chat_json): """Create a real graph with async execution capability.""" # Create graph using from_payload with real test data graph = Graph.from_payload(simple_chat_json, flow_id="test-flow-id") # Store original async_start to restore later if needed original_async_start = graph.async_start # Mock successful execution with real ResultData async def mock_async_start(inputs): # noqa: ARG001 # Create real Message and ResultData objects message = Message(text="Hello from flow") result_data = ResultData( results={"message": message}, component_display_name="Chat Output", component_id=graph.vertices[-1].id if graph.vertices else "test-123", ) # Create a mock result that mimics the real structure mock_result = MagicMock() mock_result.vertex.custom_component.display_name = "Chat Output" mock_result.vertex.id = result_data.component_id mock_result.result_dict = result_data yield mock_result graph.async_start = mock_async_start graph._original_async_start = original_async_start return graph @pytest.fixture def app_client(self, real_graph_with_async): """Create test client with single flow app.""" meta = FlowMeta( id="test-flow-id", relative_path="test.json", title="Test Flow", description="A test flow", ) graphs = {"test-flow-id": real_graph_with_async} metas = {"test-flow-id": meta} verbose_print = Mock() app = create_multi_serve_app( root_dir=Path("/test"), graphs=graphs, metas=metas, verbose_print=verbose_print, ) # Set up test API key with patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-api-key"}): # pragma: allowlist secret return TestClient(app) @pytest.fixture def multi_flow_client(self, real_graph_with_async, simple_chat_json): """Create test client with multiple flows.""" # Create second real graph using the same JSON structure graph2 = Graph.from_payload(simple_chat_json, flow_id="flow-2") async def mock_async_start2(inputs): # noqa: ARG001 # Return empty results for this test yield MagicMock(outputs=[]) graph2.async_start = mock_async_start2 meta1 = FlowMeta( id="test-flow-id", relative_path="test.json", title="Test Flow", description="First flow", ) meta2 = FlowMeta( id="flow-2", relative_path="flow2.json", title="Flow 2", description="Second flow", ) graphs = {"test-flow-id": real_graph_with_async, "flow-2": graph2} metas = {"test-flow-id": meta1, "flow-2": meta2} verbose_print = Mock() app = create_multi_serve_app( root_dir=Path("/test"), graphs=graphs, metas=metas, verbose_print=verbose_print, ) with patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-api-key"}): # pragma: allowlist secret return TestClient(app) def test_health_endpoint(self, app_client): """Test health check endpoint.""" response = app_client.get("/health") assert response.status_code == 200 data = response.json() assert data["status"] == "healthy" assert data["flow_count"] == 1 def test_run_endpoint_success(self, app_client): """Test successful flow execution.""" request_data = {"input_value": "Test input"} headers = {"x-api-key": "test-api-key"} with ( patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-api-key"}), # pragma: allowlist secret patch("lfx.cli.common.extract_structured_result") as mock_extract, ): mock_extract.return_value = { "result": "Hello from flow", "success": True, "type": "message", "component": "TestComponent", } response = app_client.post("/flows/test-flow-id/run", json=request_data, headers=headers) assert response.status_code == 200 data = response.json() assert data["result"] == "Hello from flow" assert data["success"] is True assert data["type"] == "message" def test_run_endpoint_no_auth(self, app_client): """Test flow execution without authentication.""" request_data = {"input_value": "Test input"} with patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-api-key"}): # pragma: allowlist secret response = app_client.post("/flows/test-flow-id/run", json=request_data) assert response.status_code == 401 assert response.json()["detail"] == "API key required" def test_run_endpoint_wrong_auth(self, app_client): """Test flow execution with wrong API key.""" request_data = {"input_value": "Test input"} headers = {"x-api-key": "wrong-key"} with patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-api-key"}): # pragma: allowlist secret response = app_client.post("/flows/test-flow-id/run", json=request_data, headers=headers) assert response.status_code == 401 assert response.json()["detail"] == "Invalid API key" def test_run_endpoint_query_auth(self, app_client): """Test flow execution with query parameter authentication.""" request_data = {"input_value": "Test input"} with ( patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-api-key"}), # pragma: allowlist secret patch("lfx.cli.common.extract_structured_result") as mock_extract, ): mock_extract.return_value = { "result": "Hello from flow", "success": True, "type": "message", "component": "TestComponent", } response = app_client.post("/flows/test-flow-id/run?x-api-key=test-api-key", json=request_data) assert response.status_code == 200 assert response.json()["success"] is True def test_run_endpoint_execution_error(self, app_client): """Test flow execution with error.""" request_data = {"input_value": "Test input"} headers = {"x-api-key": "test-api-key"} # Mock execute_graph_with_capture to raise an error async def mock_execute_error(graph, input_value): # noqa: ARG001 msg = "Flow execution failed" raise RuntimeError(msg) with ( patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-api-key"}), # pragma: allowlist secret patch("lfx.cli.serve_app.execute_graph_with_capture", mock_execute_error), ): response = app_client.post("/flows/test-flow-id/run", json=request_data, headers=headers) assert response.status_code == 200 # Returns 200 with error in response body data = response.json() assert data["success"] is False # serve_app error handling returns "Flow execution failed: {error}" assert data["result"] == "Flow execution failed: Flow execution failed" assert data["type"] == "error" # The error message should be in the logs assert "ERROR: Flow execution failed" in data["logs"] def test_run_endpoint_no_results(self, app_client): """Test flow execution with no results.""" request_data = {"input_value": "Test input"} headers = {"x-api-key": "test-api-key"} # Mock execute_graph_with_capture to return empty results async def mock_execute_empty(graph, input_value): # noqa: ARG001 return [], "" # Empty results and logs with ( patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-api-key"}), # pragma: allowlist secret patch("lfx.cli.serve_app.execute_graph_with_capture", mock_execute_empty), ): response = app_client.post("/flows/test-flow-id/run", json=request_data, headers=headers) assert response.status_code == 200 data = response.json() assert data["result"] == "No response generated" assert data["success"] is False assert data["type"] == "error" def test_list_flows_endpoint(self, multi_flow_client): """Test listing flows in multi-flow mode.""" response = multi_flow_client.get("/flows") assert response.status_code == 200 flows = response.json() assert len(flows) == 2 assert any(f["id"] == "test-flow-id" for f in flows) assert any(f["id"] == "flow-2" for f in flows) def test_flow_info_endpoint(self, multi_flow_client): """Test getting flow info in multi-flow mode.""" headers = {"x-api-key": "test-api-key"} with patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-api-key"}): # pragma: allowlist secret response = multi_flow_client.get("/flows/test-flow-id/info", headers=headers) assert response.status_code == 200 info = response.json() assert info["id"] == "test-flow-id" assert info["title"] == "Test Flow" assert info["description"] == "First flow" def test_flow_run_endpoint_multi_flow(self, multi_flow_client): """Test running specific flow in multi-flow mode.""" request_data = {"input_value": "Test input"} headers = {"x-api-key": "test-api-key"} with ( patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-api-key"}), # pragma: allowlist secret patch("lfx.cli.common.extract_structured_result") as mock_extract, ): mock_extract.return_value = { "result": "Hello from flow", "success": True, "type": "message", "component": "TestComponent", } response = multi_flow_client.post("/flows/test-flow-id/run", json=request_data, headers=headers) assert response.status_code == 200 data = response.json() assert data["result"] == "Hello from flow" assert data["success"] is True def test_invalid_request_body(self, app_client): """Test with invalid request body.""" headers = {"x-api-key": "test-api-key"} with patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-api-key"}): # pragma: allowlist secret response = app_client.post("/flows/test-flow-id/run", json={}, headers=headers) assert response.status_code == 422 # Validation error def test_flow_execution_with_message_output(self, app_client, real_graph_with_async): """Test flow execution with message-type output.""" # Create a real message output scenario async def mock_async_start_message(inputs): # noqa: ARG001 # Create real Message and ResultData objects message = Message(text="Message output") result_data = ResultData( results={"message": message}, component_display_name="Chat Output", component_id="test-123" ) # Create result structure mock_result = MagicMock() mock_result.vertex.custom_component.display_name = "Chat Output" mock_result.vertex.id = "test-123" mock_result.result_dict = result_data # Add message attribute for backwards compatibility mock_result.message = message yield mock_result real_graph_with_async.async_start = mock_async_start_message request_data = {"input_value": "Test input"} headers = {"x-api-key": "test-api-key"} with ( patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-api-key"}), # pragma: allowlist secret patch("lfx.cli.common.extract_structured_result") as mock_extract, ): mock_extract.return_value = { "result": "Message output", "success": True, "type": "message", "component": "Chat Output", } response = app_client.post("/flows/test-flow-id/run", json=request_data, headers=headers) assert response.status_code == 200 data = response.json() assert data["result"] == "Message output" assert data["success"] is True
{ "repo_id": "langflow-ai/langflow", "file_path": "src/lfx/tests/unit/cli/test_serve_app.py", "license": "MIT License", "lines": 396, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/lfx/tests/unit/cli/test_serve_app_streaming.py
"""Unit tests for streaming functionality in multi-serve app.""" import asyncio import tempfile from pathlib import Path from unittest.mock import patch import pytest from asgi_lifespan import LifespanManager from httpx import ASGITransport, AsyncClient from lfx.cli.serve_app import FlowMeta, StreamRequest, create_multi_serve_app class MockNode: """Mock node for testing graph structure.""" def __init__(self, node_id: str, node_type: str = "TestComponent", display_name: str | None = None): self.data = { "id": node_id, "type": node_type, "display_name": display_name or node_type, "description": f"Mock {node_type} component", "template": { "input_field": {"type": "str", "value": "default_value"}, "output_field": {"type": "str", "value": ""}, }, } class MockEdge: """Mock edge for testing graph structure.""" def __init__(self, source: str, target: str): self.source = source self.target = target class MockGraph: """Mock graph for testing.""" def __init__(self, nodes=None, edges=None): self.nodes = nodes or { "input_node": MockNode("input_node", "ChatInput", "Chat Input"), "output_node": MockNode("output_node", "ChatOutput", "Chat Output"), } self.edges = edges or [MockEdge("input_node", "output_node")] @pytest.fixture def mock_graphs(): """Create mock graphs for testing.""" return { "flow1": MockGraph(), "flow2": MockGraph( nodes={ "text_input": MockNode("text_input", "TextInput", "Text Input"), "processor": MockNode("processor", "Processor", "Text Processor"), "text_output": MockNode("text_output", "TextOutput", "Text Output"), }, edges=[MockEdge("text_input", "processor"), MockEdge("processor", "text_output")], ), } @pytest.fixture def mock_metas(): """Create mock metadata for testing.""" return { "flow1": FlowMeta( id="flow1", relative_path="flow1.json", title="Test Flow 1", description="A simple test flow for chat" ), "flow2": FlowMeta( id="flow2", relative_path="flow2.json", title="Test Flow 2", description="A test flow with text processing" ), } @pytest.fixture def multi_serve_app(mock_graphs, mock_metas, monkeypatch): """Create a multi-serve app for testing.""" # Set required environment variable monkeypatch.setenv("LANGFLOW_API_KEY", "test-api-key") with patch("lfx.cli.serve_app.execute_graph_with_capture") as mock_execute: # Mock successful execution mock_execute.return_value = ( [{"result": "Test response", "type": "message"}], "Execution completed successfully", ) with tempfile.TemporaryDirectory() as temp_dir: app = create_multi_serve_app( root_dir=Path(temp_dir), graphs=mock_graphs, metas=mock_metas, verbose_print=lambda _: None ) # Override the dependency after app creation def mock_verify_api_key(query_param: str | None = None, header_param: str | None = None) -> str: # noqa: ARG001 return "test-api-key" # Import the original dependency from lfx.cli.serve_app import verify_api_key app.dependency_overrides[verify_api_key] = mock_verify_api_key yield app # Clean up app.dependency_overrides.clear() @pytest.fixture def mock_api_key(monkeypatch): """Mock API key for authentication.""" # Set the required environment variable monkeypatch.setenv("LANGFLOW_API_KEY", "test-api-key") with patch("lfx.cli.serve_app.verify_api_key") as mock_verify: mock_verify.return_value = True yield "test-api-key" class TestMultiServeStreaming: """Test cases for multi-serve streaming functionality.""" @pytest.mark.asyncio async def test_stream_endpoint_exists(self, multi_serve_app, mock_api_key): """Test that streaming endpoints are properly created.""" async with ( LifespanManager(multi_serve_app, startup_timeout=None, shutdown_timeout=None) as manager, AsyncClient(transport=ASGITransport(app=manager.app), base_url="http://testserver/", http2=True) as client, ): # Test that stream endpoints exist for each flow response = await client.post( "/flows/flow1/stream", json={"input_value": "Hello, world!"}, headers={"x-api-key": mock_api_key} ) # Should not be 404 (endpoint exists) assert response.status_code != 404 @pytest.mark.asyncio async def test_stream_basic_functionality(self, multi_serve_app, mock_api_key): """Test basic streaming functionality.""" with patch("lfx.cli.serve_app.run_flow_generator_for_serve") as mock_generator: # Mock the streaming generator async def mock_stream_generator(*args, **kwargs): # noqa: ARG001 event_manager = kwargs.get("event_manager") client_consumed_queue = kwargs.get("client_consumed_queue") if event_manager: event_manager.on_end(data={"result": {"result": "Streamed response", "success": True}}) if client_consumed_queue: await client_consumed_queue.get() else: msg = "client_consumed_queue is None" raise RuntimeError(msg) # Send the final None to close the stream await event_manager.queue.put((None, None, 0)) mock_generator.side_effect = mock_stream_generator async with ( LifespanManager(multi_serve_app, startup_timeout=None, shutdown_timeout=None) as manager, AsyncClient( transport=ASGITransport(app=manager.app), base_url="http://testserver/", http2=True ) as client, ): response = await client.post( "/flows/flow1/stream", json={"input_value": "Test streaming input"}, headers={"x-api-key": mock_api_key}, ) # Debug output removed to pass linting assert response.status_code == 200 assert response.headers["content-type"] == "text/event-stream; charset=utf-8" @pytest.mark.asyncio async def test_stream_request_validation(self, multi_serve_app, mock_api_key): """Test StreamRequest model validation.""" async with ( LifespanManager(multi_serve_app, startup_timeout=None, shutdown_timeout=None) as manager, AsyncClient(transport=ASGITransport(app=manager.app), base_url="http://testserver/", http2=True) as client, ): # Test with minimal valid request response = await client.post( "/flows/flow1/stream", json={"input_value": "test"}, headers={"x-api-key": mock_api_key} ) assert response.status_code == 200 # Test with full request response = await client.post( "/flows/flow1/stream", json={ "input_value": "test input", "input_type": "chat", "output_type": "chat", "session_id": "test-session-123", "tweaks": {"component1": {"param1": "value1"}}, }, headers={"x-api-key": mock_api_key}, ) assert response.status_code == 200 @pytest.mark.asyncio async def test_stream_authentication_required(self, multi_serve_app): """Test that streaming endpoints require authentication.""" # Temporarily remove the auth override to test real auth behavior from lfx.cli.serve_app import verify_api_key override = multi_serve_app.dependency_overrides.pop(verify_api_key, None) try: async with ( LifespanManager(multi_serve_app, startup_timeout=None, shutdown_timeout=None) as manager, AsyncClient( transport=ASGITransport(app=manager.app), base_url="http://testserver/", http2=True ) as client, ): # Test without API key response = await client.post("/flows/flow1/stream", json={"input_value": "test"}) # Should fail authentication assert response.status_code in [401, 403] finally: # Restore the override for other tests if override: multi_serve_app.dependency_overrides[verify_api_key] = override @pytest.mark.asyncio async def test_stream_flow_not_found(self, multi_serve_app, mock_api_key): """Test streaming with non-existent flow.""" async with ( LifespanManager(multi_serve_app, startup_timeout=None, shutdown_timeout=None) as manager, AsyncClient(transport=ASGITransport(app=manager.app), base_url="http://testserver/", http2=True) as client, ): response = await client.post( "/flows/nonexistent/stream", json={"input_value": "test"}, headers={"x-api-key": mock_api_key} ) assert response.status_code == 404 @pytest.mark.asyncio async def test_stream_error_handling(self, multi_serve_app, mock_api_key): """Test error handling in streaming endpoint.""" with patch("lfx.cli.serve_app.run_flow_generator_for_serve") as mock_generator: # Mock an error in the generator that properly terminates the stream async def mock_error_generator(graph, input_request, flow_id, event_manager, client_consumed_queue): # noqa: ARG001 try: msg = "Test error during streaming" raise RuntimeError(msg) except Exception as e: # Properly handle the error like the real function does event_manager.on_error(data={"error": str(e)}) finally: # Always send termination signal import time await event_manager.queue.put((None, None, time.time())) mock_generator.side_effect = mock_error_generator async with ( LifespanManager(multi_serve_app, startup_timeout=None, shutdown_timeout=None) as manager, AsyncClient( transport=ASGITransport(app=manager.app), base_url="http://testserver/", http2=True ) as client, ): response = await client.post( "/flows/flow1/stream", json={"input_value": "test"}, headers={"x-api-key": mock_api_key} ) # Should still return 200 but with error stream assert response.status_code == 200 assert response.headers["content-type"] == "text/event-stream; charset=utf-8" @pytest.mark.asyncio async def test_stream_multiple_flows(self, multi_serve_app, mock_api_key): """Test streaming with multiple flows.""" async with ( LifespanManager(multi_serve_app, startup_timeout=None, shutdown_timeout=None) as manager, AsyncClient(transport=ASGITransport(app=manager.app), base_url="http://testserver/", http2=True) as client, ): # Test streaming for flow1 response1 = await client.post( "/flows/flow1/stream", json={"input_value": "test flow 1"}, headers={"x-api-key": mock_api_key} ) assert response1.status_code == 200 # Test streaming for flow2 response2 = await client.post( "/flows/flow2/stream", json={"input_value": "test flow 2"}, headers={"x-api-key": mock_api_key} ) assert response2.status_code == 200 @pytest.mark.asyncio async def test_regular_run_endpoint_still_works(self, multi_serve_app, mock_api_key): """Test that regular run endpoints still work alongside streaming.""" with patch("lfx.cli.serve_app.extract_result_data") as mock_extract: mock_extract.return_value = { "result": "Regular response", "success": True, "type": "message", "component": "test", } async with ( LifespanManager(multi_serve_app, startup_timeout=None, shutdown_timeout=None) as manager, AsyncClient( transport=ASGITransport(app=manager.app), base_url="http://testserver/", http2=True ) as client, ): response = await client.post( "/flows/flow1/run", json={"input_value": "test regular run"}, headers={"x-api-key": mock_api_key} ) assert response.status_code == 200 assert response.headers["content-type"] == "application/json" data = response.json() assert data["result"] == "Regular response" assert data["success"] is True @pytest.mark.asyncio async def test_list_flows_endpoint(self, multi_serve_app): """Test that the flows listing endpoint works.""" async with ( LifespanManager(multi_serve_app, startup_timeout=None, shutdown_timeout=None) as manager, AsyncClient(transport=ASGITransport(app=manager.app), base_url="http://testserver/", http2=True) as client, ): response = await client.get("/flows") assert response.status_code == 200 flows = response.json() assert len(flows) == 2 assert any(flow["id"] == "flow1" for flow in flows) assert any(flow["id"] == "flow2" for flow in flows) def test_stream_request_model(self): """Test the StreamRequest model validation.""" # Test minimal request request = StreamRequest(input_value="test") assert request.input_value == "test" assert request.input_type == "chat" # default assert request.output_type == "chat" # default assert request.session_id is None assert request.tweaks is None # Test full request request = StreamRequest( input_value="test input", input_type="text", output_type="debug", output_component="specific_component", session_id="session123", tweaks={"comp1": {"param1": "value1"}}, ) assert request.input_value == "test input" assert request.input_type == "text" assert request.output_type == "debug" assert request.output_component == "specific_component" assert request.session_id == "session123" assert request.tweaks == {"comp1": {"param1": "value1"}} @pytest.mark.asyncio async def test_concurrent_streaming(self, multi_serve_app, mock_api_key): """Test concurrent streaming requests.""" async with ( LifespanManager(multi_serve_app, startup_timeout=None, shutdown_timeout=None) as manager, AsyncClient(transport=ASGITransport(app=manager.app), base_url="http://testserver/", http2=True) as client, ): # Start multiple concurrent streaming requests tasks = [] for i in range(3): task = asyncio.create_task( client.post( "/flows/flow1/stream", json={"input_value": f"concurrent test {i}"}, headers={"x-api-key": mock_api_key}, ) ) tasks.append(task) # Wait for all requests to complete responses = await asyncio.gather(*tasks) # All should be successful for response in responses: assert response.status_code == 200 assert response.headers["content-type"] == "text/event-stream; charset=utf-8"
{ "repo_id": "langflow-ai/langflow", "file_path": "src/lfx/tests/unit/cli/test_serve_app_streaming.py", "license": "MIT License", "lines": 327, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/lfx/tests/unit/cli/test_serve_components.py
"""Unit tests for serve components without CLI runner dependencies.""" import json import tempfile from pathlib import Path from unittest.mock import Mock, patch import pytest import typer from fastapi.testclient import TestClient from lfx.cli.common import flow_id_from_path, load_graph_from_path, validate_script_path from lfx.cli.serve_app import ( ErrorResponse, FlowMeta, RunRequest, RunResponse, _analyze_graph_structure, _generate_dynamic_run_description, create_multi_serve_app, ) from lfx.graph import Graph from pydantic import ValidationError class TestDataModels: """Test Pydantic data models.""" def test_flow_meta_model(self): """Test FlowMeta model creation and validation.""" meta = FlowMeta( id="test-flow-123", relative_path="flows/test_flow.json", title="Test Flow", description="A test flow for unit testing", ) assert meta.id == "test-flow-123" assert meta.relative_path == "flows/test_flow.json" assert meta.title == "Test Flow" assert meta.description == "A test flow for unit testing" # Test required fields with pytest.raises(ValidationError): FlowMeta() def test_run_request_model(self): """Test RunRequest model creation and validation.""" request = RunRequest(input_value="Hello, world!") assert request.input_value == "Hello, world!" # Test required field with pytest.raises(ValidationError): RunRequest() def test_run_response_model(self): """Test RunResponse model creation and validation.""" response = RunResponse( result="Processed successfully", success=True, logs="Execution completed", type="message", component="TestComponent", ) assert response.result == "Processed successfully" assert response.success is True assert response.logs == "Execution completed" assert response.type == "message" assert response.component == "TestComponent" def test_error_response_model(self): """Test ErrorResponse model creation.""" error = ErrorResponse(error="Something went wrong") assert error.error == "Something went wrong" assert error.success is False class TestGraphAnalysis: """Test graph analysis functions.""" def test_analyze_graph_structure_basic(self): """Test basic graph structure analysis.""" # Create a mock graph that matches what _analyze_graph_structure expects mock_graph = Mock() # Create mock node objects with the expected structure node1 = Mock() node1.data = { "type": "ChatInput", "display_name": "Chat Input", "description": "Input component", "template": {"input_value": {"type": "str"}}, } node2 = Mock() node2.data = { "type": "ChatOutput", "display_name": "Chat Output", "description": "Output component", "template": {"output_value": {"type": "str"}}, } mock_graph.nodes = {"input-1": node1, "output-1": node2} # Create mock edges edge = Mock() edge.source = "input-1" edge.target = "output-1" mock_graph.edges = [edge] analysis = _analyze_graph_structure(mock_graph) assert analysis["node_count"] == 2 assert analysis["edge_count"] == 1 assert len(analysis["components"]) == 2 assert isinstance(analysis["input_types"], list) assert isinstance(analysis["output_types"], list) def test_analyze_graph_structure_error_handling(self): """Test graph analysis with malformed graph.""" mock_graph = Mock() mock_graph.nodes = {} mock_graph.edges = [] # Force an exception during analysis mock_graph.nodes = None analysis = _analyze_graph_structure(mock_graph) # Should provide fallback values assert len(analysis["components"]) == 1 assert analysis["components"][0]["type"] == "Unknown" assert "text" in analysis["input_types"] assert "text" in analysis["output_types"] def test_generate_dynamic_run_description(self): """Test dynamic description generation.""" # Create a mock graph for _generate_dynamic_run_description mock_graph = Mock() # Mock the analyze function to return expected data with patch("lfx.cli.serve_app._analyze_graph_structure") as mock_analyze: mock_analyze.return_value = { "node_count": 2, "edge_count": 1, "components": [{"type": "ChatInput"}, {"type": "ChatOutput"}], "input_types": ["text"], "output_types": ["text"], "entry_points": [{"template": {"input_value": {"type": "str"}}}], "exit_points": [{"template": {"output_value": {"type": "str"}}}], } description = _generate_dynamic_run_description(mock_graph) assert "Execute the deployed LFX graph" in description assert "Authentication Required" in description assert "Example Request" in description assert "Example Response" in description class TestCommonFunctions: """Test common utility functions.""" def test_flow_id_from_path(self, tmp_path): """Test flow ID generation from path.""" test_path = tmp_path / "test_flow.json" root_dir = tmp_path flow_id = flow_id_from_path(test_path, root_dir) # Should be a deterministic UUID5 assert isinstance(flow_id, str) assert len(flow_id.replace("-", "")) == 32 # UUID without dashes # Same path should produce same ID assert flow_id == flow_id_from_path(test_path, root_dir) def test_validate_script_path_valid(self): """Test script path validation with valid path.""" with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as tmp: tmp.write(b'{"test": "data"}') tmp.flush() path = Path(tmp.name) def verbose_print(msg): pass # Real function file_ext, result = validate_script_path(str(path), verbose_print) assert result == path assert file_ext == ".json" def test_validate_script_path_invalid(self): """Test script path validation with invalid path.""" def verbose_print(msg): pass # Real function with pytest.raises(typer.Exit): validate_script_path("/nonexistent/path.json", verbose_print) @patch("lfx.cli.common.load_flow_from_json") @pytest.mark.asyncio async def test_load_graph_from_path_success(self, mock_load_flow): """Test successful graph loading.""" mock_graph = Mock() mock_load_flow.return_value = mock_graph with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as tmp: tmp.write(b'{"test": "flow"}') tmp.flush() def verbose_print(msg): pass # Real function graph = await load_graph_from_path(Path(tmp.name), ".json", verbose_print, verbose=True) assert graph == mock_graph mock_load_flow.assert_called_once_with(Path(tmp.name), disable_logs=False) @patch("lfx.cli.common.load_flow_from_json") @pytest.mark.asyncio async def test_load_graph_from_path_error(self, mock_load_flow): """Test graph loading with error.""" mock_load_flow.side_effect = Exception("Parse error") with tempfile.NamedTemporaryFile(suffix=".json", delete=False) as tmp: tmp.write(b"invalid json") tmp.flush() def verbose_print(msg): pass # Real function with pytest.raises(typer.Exit): await load_graph_from_path(Path(tmp.name), ".json", verbose_print, verbose=False) mock_load_flow.assert_called_once_with(Path(tmp.name), disable_logs=True) # Removed create_mock_graph - use create_real_graph() instead def simple_chat_json(): """Load the simple chat JSON test data.""" test_data_dir = Path(__file__).parent.parent.parent / "data" json_path = test_data_dir / "simple_chat_no_llm.json" with json_path.open() as f: return json.load(f) def create_real_graph(): """Helper function to create a real LFX graph with nodes/edges for serve_app.""" # Load real JSON data and create graph using from_payload json_data = simple_chat_json() return Graph.from_payload(json_data, flow_id="test-flow-id") class TestFastAPIAppCreation: """Test FastAPI application creation.""" def test_create_multi_serve_app_basic(self, tmp_path): """Test basic multi-serve app creation.""" root_dir = tmp_path graphs = {"test-flow": create_real_graph()} metas = {"test-flow": FlowMeta(id="test-flow", relative_path="test.json", title="Test Flow")} def verbose_print(msg): pass # Real function with patch("lfx.cli.serve_app.verify_api_key"): app = create_multi_serve_app(root_dir=root_dir, graphs=graphs, metas=metas, verbose_print=verbose_print) assert app.title.startswith("LFX Multi-Flow Server") assert "1" in app.title # Should show count def test_create_multi_serve_app_mismatched_keys(self, tmp_path): """Test app creation with mismatched graph/meta keys.""" root_dir = tmp_path graphs = {"flow1": create_real_graph()} metas = {"flow2": FlowMeta(id="flow2", relative_path="test.json", title="Test")} def verbose_print(msg): pass # Real function with pytest.raises(ValueError, match="graphs and metas must contain the same keys"): create_multi_serve_app(root_dir=root_dir, graphs=graphs, metas=metas, verbose_print=verbose_print) class TestFastAPIEndpoints: """Test FastAPI endpoints using TestClient.""" def setup_method(self, tmp_path): """Set up test client with mock data.""" self.root_dir = tmp_path self.real_graph = create_real_graph() self.graphs = {"test-flow": self.real_graph} self.metas = { "test-flow": FlowMeta( id="test-flow", relative_path="test.json", title="Test Flow", description="A test flow" ) } def verbose_print(msg): pass # Real function self.verbose_print = verbose_print # Create the app first with patch("lfx.cli.serve_app.verify_api_key"): self.app = create_multi_serve_app( root_dir=self.root_dir, graphs=self.graphs, metas=self.metas, verbose_print=self.verbose_print ) # Override the dependency for testing def mock_verify_key(): return "test-key" # Import here to avoid circular import issues from lfx.cli.serve_app import verify_api_key self.app.dependency_overrides[verify_api_key] = mock_verify_key self.client = TestClient(self.app) def test_list_flows_endpoint(self): """Test the /flows endpoint.""" response = self.client.get("/flows") assert response.status_code == 200 flows = response.json() assert len(flows) == 1 assert flows[0]["id"] == "test-flow" assert flows[0]["title"] == "Test Flow" def test_health_endpoint(self): """Test the /health endpoint.""" response = self.client.get("/health") assert response.status_code == 200 health = response.json() assert health["status"] == "healthy" assert health["flow_count"] == 1 @patch("lfx.cli.common.execute_graph_with_capture") @patch("lfx.cli.common.extract_result_data") def test_flow_run_endpoint_success(self, mock_extract, mock_execute): """Test successful flow execution path (without auth validation).""" mock_execute.return_value = ({"result": "success"}, "execution logs") mock_extract.return_value = { "result": "Processed successfully", "success": True, "type": "message", "component": "TestComponent", } # Test that the execute and extract functions would be called properly # (Testing the business logic, not the HTTP layer) assert mock_execute.return_value == ({"result": "success"}, "execution logs") assert mock_extract.return_value["result"] == "Processed successfully" assert mock_extract.return_value["success"] is True @patch("lfx.cli.common.execute_graph_with_capture") @pytest.mark.asyncio async def test_flow_run_endpoint_error(self, mock_execute): """Test flow execution error handling logic.""" mock_execute.side_effect = Exception("Execution failed") # Test that the exception would be raised properly with pytest.raises(Exception, match="Execution failed"): await mock_execute(self.real_graph, "test input") def test_flow_info_endpoint(self): """Test the flow info endpoint returns basic metadata.""" response = self.client.get("/flows/test-flow/info") # Just test that the endpoint exists and returns something # The exact response depends on auth which is complex to mock assert response.status_code in [200, 422] # Either success or auth failure def test_flow_run_without_auth(self): """Test flow execution without authentication.""" # Clear the dependency override to test auth failure from lfx.cli.serve_app import verify_api_key if verify_api_key in self.app.dependency_overrides: del self.app.dependency_overrides[verify_api_key] response = self.client.post("/flows/test-flow/run", json={"input_value": "test input"}) # Should fail due to missing auth (exact status depends on verify_api_key implementation) assert response.status_code in [401, 403, 422] class TestErrorHandling: """Test error handling in various components.""" def test_invalid_json_in_request(self, tmp_path): """Test handling of invalid JSON in requests.""" with patch("lfx.cli.serve_app.verify_api_key", return_value="test-key"): app = create_multi_serve_app( root_dir=tmp_path, graphs={"test": create_real_graph()}, metas={"test": FlowMeta(id="test", relative_path="test.json", title="Test")}, verbose_print=lambda msg: None, # noqa: ARG005 ) client = TestClient(app) response = client.post( "/flows/test/run", data="invalid json", headers={"x-api-key": "test-key", "Content-Type": "application/json"}, ) assert response.status_code == 422 # Validation error def test_missing_flow_id(self, tmp_path): """Test accessing non-existent flow.""" with patch("lfx.cli.serve_app.verify_api_key", return_value="test-key"): app = create_multi_serve_app( root_dir=tmp_path, graphs={"test": create_real_graph()}, metas={"test": FlowMeta(id="test", relative_path="test.json", title="Test")}, verbose_print=lambda msg: None, # noqa: ARG005 ) client = TestClient(app) response = client.post( "/flows/nonexistent/run", json={"input_value": "test"}, headers={"x-api-key": "test-key"} ) assert response.status_code == 404 class TestIntegration: """Integration tests combining multiple components.""" @patch("lfx.cli.common.load_flow_from_json") @pytest.mark.asyncio async def test_full_app_integration(self, mock_load_flow): """Test full app integration with realistic data.""" # Setup real graph real_graph = create_real_graph() mock_load_flow.return_value = real_graph # Create temporary flow file with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as tmp: json.dump({"nodes": [], "edges": []}, tmp) tmp.flush() flow_path = Path(tmp.name) # Test flow loading def verbose_print(msg): pass # Real function mock_verbose_print = verbose_print loaded_graph = await load_graph_from_path(flow_path, ".json", mock_verbose_print) assert loaded_graph == real_graph # Test flow ID generation flow_id = flow_id_from_path(flow_path, flow_path.parent) assert isinstance(flow_id, str) # Test metadata creation meta = FlowMeta( id=flow_id, relative_path=flow_path.name, title=flow_path.stem, description="Integration test flow" ) # Test app creation with patch("lfx.cli.serve_app.verify_api_key", return_value="test-key"): app = create_multi_serve_app( root_dir=flow_path.parent, graphs={flow_id: loaded_graph}, metas={flow_id: meta}, verbose_print=mock_verbose_print, ) client = TestClient(app) # Test endpoints flows_response = client.get("/flows") assert flows_response.status_code == 200 assert len(flows_response.json()) == 1 health_response = client.get("/health") assert health_response.status_code == 200 assert health_response.json()["flow_count"] == 1
{ "repo_id": "langflow-ai/langflow", "file_path": "src/lfx/tests/unit/cli/test_serve_components.py", "license": "MIT License", "lines": 375, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/lfx/tests/unit/cli/test_serve_simple.py
"""Simple tests for LFX serve command focusing on CLI functionality.""" import json import os import tempfile from pathlib import Path from unittest.mock import patch from typer.testing import CliRunner def test_cli_imports(): """Test that we can import the CLI components.""" # These imports should work without errors from lfx.__main__ import app, main assert main is not None assert app is not None def test_serve_command_help(): """Test that serve command shows help.""" from lfx.__main__ import app runner = CliRunner() result = runner.invoke(app, ["serve", "--help"]) assert result.exit_code == 0 assert "Serve a flow as an API" in result.output def test_serve_command_missing_api_key(): """Test that serve command fails without API key.""" from lfx.__main__ import app # Create a temporary JSON flow file flow_data = { "data": { "nodes": [], "edges": [], } } with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as f: json.dump(flow_data, f) temp_path = f.name try: # Clear API key from environment with patch.dict(os.environ, {}, clear=True): runner = CliRunner() result = runner.invoke(app, ["serve", temp_path]) assert result.exit_code == 1 # Check both output and exception since typer may output to different streams assert "LANGFLOW_API_KEY" in str(result.output or result.exception or "") finally: Path(temp_path).unlink() def test_serve_command_with_flow_json(): """Test serve command with inline JSON.""" from lfx.__main__ import app flow_json = '{"data": {"nodes": [], "edges": []}}' with patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-key"}), patch("uvicorn.run") as mock_uvicorn: runner = CliRunner() result = runner.invoke(app, ["serve", "--flow-json", flow_json]) # Should try to start the server assert mock_uvicorn.called or result.exit_code != 0 def test_serve_command_invalid_json(): """Test serve command with invalid JSON.""" from lfx.__main__ import app invalid_json = '{"invalid": json}' with patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-key"}): runner = CliRunner() result = runner.invoke(app, ["serve", "--flow-json", invalid_json], catch_exceptions=False) assert result.exit_code == 1 def test_serve_command_nonexistent_file(): """Test serve command with non-existent file.""" from lfx.__main__ import app with patch.dict(os.environ, {"LANGFLOW_API_KEY": "test-key"}): runner = CliRunner() result = runner.invoke(app, ["serve", "/path/to/nonexistent/file.json"], catch_exceptions=False) assert result.exit_code == 1 def test_cli_utility_functions(): """Test basic utility functions that don't have complex dependencies.""" from lfx.cli.common import ( flow_id_from_path, get_best_access_host, get_free_port, is_port_in_use, ) # Test port functions assert not is_port_in_use(0) # Port 0 is always available port = get_free_port(8000) assert 8000 <= port < 65535 # Test host resolution assert get_best_access_host("0.0.0.0") == "localhost" assert get_best_access_host("") == "localhost" assert get_best_access_host("127.0.0.1") == "127.0.0.1" # Test flow ID generation root = Path("/tmp/flows") path = root / "test.json" flow_id = flow_id_from_path(path, root) assert isinstance(flow_id, str) assert len(flow_id) == 36 # UUID length
{ "repo_id": "langflow-ai/langflow", "file_path": "src/lfx/tests/unit/cli/test_serve_simple.py", "license": "MIT License", "lines": 89, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/lfx/tests/unit/cli/test_validation.py
"""Tests for CLI validation utilities.""" from unittest.mock import MagicMock, patch from lfx.cli.validation import is_valid_env_var_name, validate_global_variables_for_env from lfx.graph.graph.base import Graph from lfx.graph.vertex.base import Vertex class TestIsValidEnvVarName: """Test cases for is_valid_env_var_name function.""" def test_valid_env_var_names(self): """Test that valid environment variable names are accepted.""" valid_names = [ "MY_VAR", "_PRIVATE_VAR", "VAR123", "LONG_VARIABLE_NAME_123", "a", "A", "_", "__double_underscore__", ] for name in valid_names: assert is_valid_env_var_name(name), f"'{name}' should be valid" def test_invalid_env_var_names(self): """Test that invalid environment variable names are rejected.""" invalid_names = [ "MY VAR", # Contains space "MY-VAR", # Contains hyphen "123VAR", # Starts with number "MY.VAR", # Contains dot "MY@VAR", # Contains special character "MY$VAR", # Contains dollar sign "MY%VAR", # Contains percent "MY(VAR)", # Contains parentheses "MY[VAR]", # Contains brackets "MY{VAR}", # Contains braces "", # Empty string " ", # Just space "MY\nVAR", # Contains newline "MY\tVAR", # Contains tab "Глобальная_переменная", # Contains non-ASCII characters ] for name in invalid_names: assert not is_valid_env_var_name(name), f"'{name}' should be invalid" class TestValidateGlobalVariablesForEnv: """Test cases for validate_global_variables_for_env function.""" @patch("lfx.services.deps.get_settings_service") def test_no_validation_when_database_available(self, mock_get_settings): """Test that no validation occurs when database is available.""" # Mock settings to indicate database is available mock_settings_service = MagicMock() mock_settings_service.settings.use_noop_database = False mock_get_settings.return_value = mock_settings_service # Create a mock graph with vertices graph = MagicMock(spec=Graph) vertex = MagicMock(spec=Vertex) vertex.load_from_db_fields = ["api_key"] vertex.params = {"api_key": "MY VAR WITH SPACES"} # pragma: allowlist secret graph.vertices = [vertex] # Should return no errors since database is available errors = validate_global_variables_for_env(graph) assert errors == [] @patch("lfx.services.deps.get_settings_service") def test_validation_when_noop_database(self, mock_get_settings): """Test that validation occurs when using noop database.""" # Mock settings to indicate noop database mock_settings_service = MagicMock() mock_settings_service.settings.use_noop_database = True mock_get_settings.return_value = mock_settings_service # Create a mock graph with vertices graph = MagicMock(spec=Graph) # Vertex with invalid variable name vertex1 = MagicMock(spec=Vertex) vertex1.id = "vertex1" vertex1.display_name = "OpenAI Model" vertex1.load_from_db_fields = ["api_key"] vertex1.params = {"api_key": "MY API KEY"} # Invalid: contains spaces # pragma: allowlist secret # Vertex with valid variable name vertex2 = MagicMock(spec=Vertex) vertex2.id = "vertex2" vertex2.display_name = "Anthropic Model" vertex2.load_from_db_fields = ["api_key"] vertex2.params = {"api_key": "ANTHROPIC_API_KEY"} # Valid # pragma: allowlist secret graph.vertices = [vertex1, vertex2] # Should return errors for the invalid variable errors = validate_global_variables_for_env(graph) assert len(errors) == 1 assert "OpenAI Model" in errors[0] assert "vertex1" in errors[0] assert "MY API KEY" in errors[0] assert "invalid characters" in errors[0] @patch("lfx.services.deps.get_settings_service") def test_multiple_invalid_fields(self, mock_get_settings): """Test validation with multiple invalid fields in same vertex.""" # Mock settings to indicate noop database mock_settings_service = MagicMock() mock_settings_service.settings.use_noop_database = True mock_get_settings.return_value = mock_settings_service # Create a mock graph with vertices graph = MagicMock(spec=Graph) vertex = MagicMock(spec=Vertex) vertex.id = "vertex1" vertex.display_name = "Database Connection" vertex.load_from_db_fields = ["username", "password", "host"] vertex.params = { # pragma: allowlist secret "username": "DB USER", # Invalid: contains space "password": "DB-PASSWORD", # Invalid: contains hyphen # pragma: allowlist secret "host": "DB_HOST", # Valid } graph.vertices = [vertex] # Should return errors for both invalid variables errors = validate_global_variables_for_env(graph) assert len(errors) == 2 # Check that both errors are present error_text = " ".join(errors) assert "DB USER" in error_text assert "DB-PASSWORD" in error_text assert "DB_HOST" not in error_text # Valid variable should not be in errors @patch("lfx.services.deps.get_settings_service") def test_empty_or_none_values_ignored(self, mock_get_settings): """Test that empty or None values are ignored.""" # Mock settings to indicate noop database mock_settings_service = MagicMock() mock_settings_service.settings.use_noop_database = True mock_get_settings.return_value = mock_settings_service # Create a mock graph with vertices graph = MagicMock(spec=Graph) vertex = MagicMock(spec=Vertex) vertex.id = "vertex1" vertex.display_name = "Test Component" vertex.load_from_db_fields = ["field1", "field2", "field3"] vertex.params = { "field1": "", # Empty string - should be ignored "field2": None, # None - should be ignored "field3": "VALID_VAR", # Valid } graph.vertices = [vertex] # Should return no errors errors = validate_global_variables_for_env(graph) assert errors == [] @patch("lfx.services.deps.get_settings_service") def test_vertex_without_load_from_db_fields(self, mock_get_settings): """Test vertices without load_from_db_fields attribute.""" # Mock settings to indicate noop database mock_settings_service = MagicMock() mock_settings_service.settings.use_noop_database = True mock_get_settings.return_value = mock_settings_service # Create a mock graph with vertices graph = MagicMock(spec=Graph) vertex = MagicMock(spec=Vertex) vertex.id = "vertex1" vertex.display_name = "Test Component" # No load_from_db_fields attribute delattr(vertex, "load_from_db_fields") graph.vertices = [vertex] # Should handle gracefully with getattr default errors = validate_global_variables_for_env(graph) assert errors == [] @patch("lfx.services.deps.get_settings_service") def test_non_string_values_ignored(self, mock_get_settings): """Test that non-string values are ignored.""" # Mock settings to indicate noop database mock_settings_service = MagicMock() mock_settings_service.settings.use_noop_database = True mock_get_settings.return_value = mock_settings_service # Create a mock graph with vertices graph = MagicMock(spec=Graph) vertex = MagicMock(spec=Vertex) vertex.id = "vertex1" vertex.display_name = "Test Component" vertex.load_from_db_fields = ["field1", "field2", "field3"] vertex.params = { "field1": 123, # Integer - should be ignored "field2": ["list"], # List - should be ignored "field3": {"dict": "value"}, # Dict - should be ignored } graph.vertices = [vertex] # Should return no errors errors = validate_global_variables_for_env(graph) assert errors == [] @patch("lfx.services.deps.get_settings_service") def test_check_variables_option_in_execute(self, mock_get_settings): """Test that check_variables option controls validation in execute command.""" # This test verifies the check_variables option works correctly # when used with the execute command (--check-variables/--no-check-variables) # Mock settings to indicate noop database mock_settings_service = MagicMock() mock_settings_service.settings.use_noop_database = True mock_get_settings.return_value = mock_settings_service # Create a mock graph with invalid variable graph = MagicMock(spec=Graph) vertex = MagicMock(spec=Vertex) vertex.id = "vertex1" vertex.display_name = "Test Component" vertex.load_from_db_fields = ["api_key"] vertex.params = {"api_key": "INVALID VAR NAME"} # Invalid: contains spaces # pragma: allowlist secret graph.vertices = [vertex] # When check_variables=True (default), validation should find errors errors = validate_global_variables_for_env(graph) assert len(errors) == 1 assert "INVALID VAR NAME" in errors[0] @patch("lfx.services.deps.get_settings_service") def test_check_variables_option_in_serve(self, mock_get_settings): """Test that check_variables option controls validation in serve command.""" # This test verifies the check_variables option works correctly # when used with the serve command (--check-variables/--no-check-variables) # Mock settings to indicate noop database mock_settings_service = MagicMock() mock_settings_service.settings.use_noop_database = True mock_get_settings.return_value = mock_settings_service # Create a mock graph with invalid variable graph = MagicMock(spec=Graph) vertex = MagicMock(spec=Vertex) vertex.id = "vertex1" vertex.display_name = "API Component" vertex.load_from_db_fields = ["token"] vertex.params = {"token": "MY-API-TOKEN"} # Invalid: contains hyphen graph.vertices = [vertex] # Validation should find errors when check is enabled errors = validate_global_variables_for_env(graph) assert len(errors) == 1 assert "MY-API-TOKEN" in errors[0] assert "invalid characters" in errors[0]
{ "repo_id": "langflow-ai/langflow", "file_path": "src/lfx/tests/unit/cli/test_validation.py", "license": "MIT License", "lines": 221, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/lfx/tests/unit/events/test_event_manager.py
"""Unit tests for lfx.events.event_manager module.""" import asyncio import json from unittest.mock import MagicMock import pytest from lfx.events.event_manager import ( EventManager, create_default_event_manager, create_stream_tokens_event_manager, ) class TestEventManager: """Test cases for the EventManager class.""" def test_event_manager_creation(self): """Test creating EventManager with queue.""" queue = asyncio.Queue() manager = EventManager(queue) assert manager.queue == queue assert manager.events == {} def test_event_manager_creation_without_queue(self): """Test creating EventManager without queue.""" manager = EventManager(None) assert manager.queue is None assert manager.events == {} def test_register_event_with_default_callback(self): """Test registering event with default callback.""" queue = asyncio.Queue() manager = EventManager(queue) manager.register_event("on_test", "test_event") assert "on_test" in manager.events assert callable(manager.events["on_test"]) def test_register_event_with_custom_callback(self): """Test registering event with custom callback.""" queue = asyncio.Queue() manager = EventManager(queue) def custom_callback(*, manager, event_type, data): pass manager.register_event("on_custom", "custom_event", custom_callback) assert "on_custom" in manager.events assert callable(manager.events["on_custom"]) def test_register_event_validation_empty_name(self): """Test event registration validation for empty name.""" queue = asyncio.Queue() manager = EventManager(queue) with pytest.raises(ValueError, match="Event name cannot be empty"): manager.register_event("", "test_event") def test_register_event_validation_name_prefix(self): """Test event registration validation for name prefix.""" queue = asyncio.Queue() manager = EventManager(queue) with pytest.raises(ValueError, match="Event name must start with 'on_'"): manager.register_event("invalid_name", "test_event") def test_validate_callback_not_callable(self): """Test callback validation for non-callable.""" with pytest.raises(TypeError, match="Callback must be callable"): EventManager._validate_callback("not_callable") def test_validate_callback_wrong_parameters(self): """Test callback validation for wrong parameters.""" def wrong_callback(param1, param2): pass with pytest.raises(ValueError, match="Callback must have exactly 3 parameters"): EventManager._validate_callback(wrong_callback) def test_validate_callback_wrong_parameter_names(self): """Test callback validation for wrong parameter names.""" def wrong_names(wrong1, wrong2, wrong3): pass with pytest.raises(ValueError, match="Callback must have exactly 3 parameters: manager, event_type, and data"): EventManager._validate_callback(wrong_names) def test_send_event_with_queue(self): """Test sending event with queue available.""" queue = MagicMock() manager = EventManager(queue) test_data = {"message": "test"} manager.send_event(event_type="test", data=test_data) # Verify queue.put_nowait was called queue.put_nowait.assert_called_once() call_args = queue.put_nowait.call_args[0][0] # Verify the event structure event_id, data_bytes, timestamp = call_args assert event_id.startswith("test-") assert isinstance(data_bytes, bytes) assert isinstance(timestamp, float) # Parse the data data_str = data_bytes.decode("utf-8").strip() parsed_data = json.loads(data_str) assert parsed_data["event"] == "test" assert parsed_data["data"] == test_data def test_send_event_without_queue(self): """Test sending event without queue (should not raise error).""" manager = EventManager(None) test_data = {"message": "test"} # Should not raise any exception manager.send_event(event_type="test", data=test_data) def test_send_event_queue_exception(self): """Test sending event when queue raises exception.""" queue = MagicMock() queue.put_nowait.side_effect = Exception("Queue error") manager = EventManager(queue) test_data = {"message": "test"} # Should not raise exception, just log debug message manager.send_event(event_type="test", data=test_data) def test_noop_method(self): """Test noop method.""" queue = asyncio.Queue() manager = EventManager(queue) # Should not raise any exception manager.noop(data={"test": "data"}) def test_getattr_existing_event(self): """Test __getattr__ for existing event.""" queue = asyncio.Queue() manager = EventManager(queue) manager.register_event("on_test", "test_event") event_callback = manager.on_test assert callable(event_callback) assert event_callback == manager.events["on_test"] def test_getattr_nonexistent_event(self): """Test __getattr__ for non-existent event returns noop.""" queue = asyncio.Queue() manager = EventManager(queue) nonexistent_callback = manager.on_nonexistent assert callable(nonexistent_callback) assert nonexistent_callback == manager.noop def test_event_callback_execution(self): """Test that event callbacks can be executed.""" queue = MagicMock() manager = EventManager(queue) manager.register_event("on_test", "test_event") # Execute the callback test_data = {"key": "value"} manager.on_test(data=test_data) # Verify queue was called (since it uses default send_event callback) queue.put_nowait.assert_called_once() def test_event_types_handling(self): """Test handling of different event types.""" queue = MagicMock() manager = EventManager(queue) # Test different event types that should be processed event_types = ["message", "error", "warning", "info", "token"] for event_type in event_types: test_data = {"type": event_type, "content": f"test {event_type}"} manager.send_event(event_type=event_type, data=test_data) # Verify all events were sent assert queue.put_nowait.call_count == len(event_types) def test_event_data_serialization(self): """Test that event data is properly serialized.""" queue = MagicMock() manager = EventManager(queue) # Complex data structure complex_data = { "string": "test", "number": 42, "boolean": True, "null": None, "array": [1, 2, 3], "object": {"nested": "value"}, } manager.send_event(event_type="complex", data=complex_data) # Get the serialized data call_args = queue.put_nowait.call_args[0][0] _, data_bytes, _ = call_args data_str = data_bytes.decode("utf-8").strip() parsed_data = json.loads(data_str) assert parsed_data["data"] == complex_data class TestEventManagerFactories: """Test cases for EventManager factory functions.""" def test_create_default_event_manager(self): """Test creating default event manager.""" queue = asyncio.Queue() manager = create_default_event_manager(queue) assert isinstance(manager, EventManager) assert manager.queue == queue # Check that default events are registered expected_events = [ "on_token", "on_vertices_sorted", "on_error", "on_end", "on_message", "on_remove_message", "on_end_vertex", "on_build_start", "on_build_end", ] for event_name in expected_events: assert event_name in manager.events assert callable(manager.events[event_name]) def test_create_default_event_manager_without_queue(self): """Test creating default event manager without queue.""" manager = create_default_event_manager() assert isinstance(manager, EventManager) assert manager.queue is None # Events should still be registered assert "on_token" in manager.events assert "on_error" in manager.events def test_create_stream_tokens_event_manager(self): """Test creating stream tokens event manager.""" queue = asyncio.Queue() manager = create_stream_tokens_event_manager(queue) assert isinstance(manager, EventManager) assert manager.queue == queue # Check that stream-specific events are registered expected_events = ["on_message", "on_token", "on_end"] for event_name in expected_events: assert event_name in manager.events assert callable(manager.events[event_name]) def test_create_stream_tokens_event_manager_without_queue(self): """Test creating stream tokens event manager without queue.""" manager = create_stream_tokens_event_manager() assert isinstance(manager, EventManager) assert manager.queue is None # Events should still be registered assert "on_message" in manager.events assert "on_token" in manager.events assert "on_end" in manager.events def test_default_manager_event_execution(self): """Test that events in default manager can be executed.""" queue = MagicMock() manager = create_default_event_manager(queue) # Test executing different events test_events = [ ("on_token", {"chunk": "test"}), ("on_error", {"error": "test error"}), ("on_message", {"text": "test message"}), ] for event_name, data in test_events: event_callback = getattr(manager, event_name) event_callback(data=data) # Verify all events were sent to queue assert queue.put_nowait.call_count == len(test_events) def test_stream_manager_event_execution(self): """Test that events in stream manager can be executed.""" queue = MagicMock() manager = create_stream_tokens_event_manager(queue) # Test executing stream-specific events manager.on_token(data={"chunk": "test token"}) manager.on_message(data={"text": "test message"}) manager.on_end(data={"status": "completed"}) # Verify all events were sent to queue expected_call_count = 3 assert queue.put_nowait.call_count == expected_call_count @pytest.mark.asyncio class TestEventManagerAsync: """Test async functionality related to EventManager.""" @pytest.mark.asyncio async def test_event_manager_with_asyncio_queue(self): """Test EventManager with real asyncio queue.""" queue = asyncio.Queue() manager = EventManager(queue) test_data = {"message": "async test"} manager.send_event(event_type="test", data=test_data) # Get item from queue item = await queue.get() event_id, data_bytes, timestamp = item assert event_id.startswith("test-") assert isinstance(data_bytes, bytes) assert isinstance(timestamp, float) # Parse the data data_str = data_bytes.decode("utf-8").strip() parsed_data = json.loads(data_str) assert parsed_data["event"] == "test" assert parsed_data["data"] == test_data @pytest.mark.asyncio async def test_multiple_events_with_queue(self): """Test sending multiple events to queue.""" queue = asyncio.Queue() manager = create_default_event_manager(queue) # Send multiple events events_to_send = [("token", {"chunk": "hello"}), ("message", {"text": "world"}), ("end", {"status": "done"})] for event_type, data in events_to_send: manager.send_event(event_type=event_type, data=data) # Verify all events are in queue assert queue.qsize() == len(events_to_send) # Process all events received_events = [] while not queue.empty(): item = await queue.get() _, data_bytes, _ = item data_str = data_bytes.decode("utf-8").strip() parsed_data = json.loads(data_str) received_events.append((parsed_data["event"], parsed_data["data"])) # Verify all events were received correctly assert len(received_events) == len(events_to_send) for sent, received in zip(events_to_send, received_events, strict=False): assert sent[0] == received[0] # event type assert sent[1] == received[1] # data
{ "repo_id": "langflow-ai/langflow", "file_path": "src/lfx/tests/unit/events/test_event_manager.py", "license": "MIT License", "lines": 284, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/lfx/tests/unit/memory/test_memory.py
"""Unit tests for lfx.memory module.""" import asyncio import pytest from lfx.memory import ( aadd_messages, aadd_messagetables, add_messages, astore_message, get_messages, store_message, ) # Import the appropriate Message class based on what's available try: from langflow.schema.message import Message except (ImportError, ModuleNotFoundError): from lfx.schema.message import Message class TestMemoryFunctions: """Test cases for memory functions.""" @pytest.mark.asyncio async def test_astore_message_single(self): """Test storing a single message asynchronously.""" message = Message(text="Hello", sender="User", sender_name="Test User", session_id="test-session") result = await astore_message(message) assert isinstance(result, list) assert len(result) == 1 assert isinstance(result[0], Message) assert result[0].text == "Hello" assert result[0].sender == "User" @pytest.mark.asyncio async def test_astore_message_list(self): """Test storing multiple messages asynchronously one by one.""" messages = [ Message(text="Hello", sender="User", sender_name="Test User", session_id="test-session"), Message(text="Hi there", sender="AI", sender_name="Assistant", session_id="test-session"), ] # Store each message individually results = [] for message in messages: result = await astore_message(message) results.extend(result) assert isinstance(results, list) assert len(results) == 2 assert all(isinstance(msg, Message) for msg in results) @pytest.mark.asyncio async def test_aadd_messages_single(self): """Test adding a single message asynchronously.""" message = Message(text="Test message", sender="User", sender_name="Test User", session_id="test-session") result = await aadd_messages(message) assert isinstance(result, list) assert len(result) == 1 assert result[0].text == "Test message" @pytest.mark.asyncio async def test_aadd_messages_list(self): """Test adding multiple messages asynchronously.""" messages = [ Message(text="Message 1", sender="User", sender_name="Test User", session_id="test-session"), Message(text="Message 2", sender="AI", sender_name="Assistant", session_id="test-session"), Message(text="Message 3", sender="User", sender_name="Test User", session_id="test-session"), ] result = await aadd_messages(messages) assert isinstance(result, list) assert len(result) == 3 assert all(isinstance(msg, Message) for msg in result) @pytest.mark.asyncio async def test_aadd_messagetables_single(self): """Test adding message tables asynchronously.""" message = Message(text="Table message", sender="System", sender_name="System", session_id="test-session") result = await aadd_messagetables(message) assert isinstance(result, list) assert len(result) == 1 assert result[0].text == "Table message" @pytest.mark.asyncio async def test_aadd_messagetables_list(self): """Test adding multiple message tables asynchronously.""" messages = [ Message(text="Table 1", sender="User", sender_name="Test User", session_id="test-session"), Message(text="Table 2", sender="AI", sender_name="Assistant", session_id="test-session"), ] result = await aadd_messagetables(messages) assert isinstance(result, list) assert len(result) == 2 def test_store_message_single(self): """Test storing a single message synchronously.""" message = Message(text="Sync message", sender="User", sender_name="Test User", session_id="test-session") result = store_message(message) assert isinstance(result, list) assert len(result) == 1 assert result[0].text == "Sync message" def test_store_message_list(self): """Test storing multiple messages synchronously one by one.""" messages = [ Message(text="Sync 1", sender="User", sender_name="Test User", session_id="test-session"), Message(text="Sync 2", sender="AI", sender_name="Assistant", session_id="test-session"), ] # Store each message individually results = [] for message in messages: result = store_message(message) results.extend(result) assert isinstance(results, list) assert len(results) == 2 def test_add_messages_single(self): """Test adding a single message synchronously.""" message = Message(text="Add message", sender="User", sender_name="Test User", session_id="test-session") result = add_messages(message) assert isinstance(result, list) assert len(result) == 1 assert result[0].text == "Add message" def test_add_messages_list(self): """Test adding multiple messages synchronously.""" messages = [ Message(text="Add 1", sender="User", sender_name="Test User", session_id="test-session"), Message(text="Add 2", sender="AI", sender_name="Assistant", session_id="test-session"), Message(text="Add 3", sender="System", sender_name="System", session_id="test-session"), ] result = add_messages(messages) assert isinstance(result, list) assert len(result) == 3 def test_get_messages_basic(self): """Test getting messages basic functionality.""" # Since this is a stub implementation, it should return empty list result = get_messages() assert isinstance(result, list) assert len(result) == 0 def test_get_messages_with_params(self): """Test getting messages with parameters.""" # Test with various parameters that might be used result = get_messages(limit=10, session_id="test", flow_id="flow_test") assert isinstance(result, list) assert len(result) == 0 @pytest.mark.asyncio async def test_memory_functions_with_empty_input(self): """Test memory functions with empty input.""" # Test with empty list result = await aadd_messages([]) assert isinstance(result, list) assert len(result) == 0 # Test sync version sync_result = add_messages([]) assert isinstance(sync_result, list) assert len(sync_result) == 0 @pytest.mark.asyncio async def test_memory_functions_preserve_message_properties(self): """Test that memory functions preserve message properties.""" original_message = Message( text="Test with properties", sender="User", sender_name="Test User", flow_id="test_flow", session_id="test_session", error=False, category="message", ) # Test async version async_result = await aadd_messages(original_message) stored_message = async_result[0] assert stored_message.text == original_message.text assert stored_message.sender == original_message.sender assert stored_message.sender_name == original_message.sender_name assert stored_message.flow_id == original_message.flow_id assert stored_message.session_id == original_message.session_id assert stored_message.error == original_message.error assert stored_message.category == original_message.category @pytest.mark.asyncio async def test_memory_functions_with_mixed_message_types(self): """Test memory functions with different types of messages.""" messages = [ Message( text="User message", sender="User", sender_name="Test User", session_id="test-mixed", category="message" ), Message( text="AI response", sender="Machine", sender_name="Bot", session_id="test-mixed", category="message" ), Message( text="System alert", sender="System", sender_name="System", session_id="test-mixed", category="info", error=False, ), ] result = await aadd_messages(messages) assert len(result) == 3 assert result[0].sender == "User" assert result[1].sender == "Machine" assert result[2].sender == "System" assert result[2].category == "info" class TestMemoryAsync: """Test async behavior of memory functions.""" @pytest.mark.asyncio async def test_concurrent_message_storage(self): """Test storing messages concurrently.""" import asyncio messages = [ Message(text=f"Message {i}", sender="User", sender_name="Test User", session_id="test-concurrent") for i in range(5) ] # Store messages concurrently tasks = [astore_message(msg) for msg in messages] results = await asyncio.gather(*tasks) assert len(results) == 5 for i, result in enumerate(results): assert len(result) == 1 assert result[0].text == f"Message {i}" @pytest.mark.asyncio async def test_async_message_operations_sequence(self): """Test a sequence of async message operations.""" # Create initial message message1 = Message(text="First message", sender="User", sender_name="Test User", session_id="test-seq") result1 = await astore_message(message1) # Add more messages additional_messages = [ Message(text="Second message", sender="AI", sender_name="Assistant", session_id="test-seq"), Message(text="Third message", sender="User", sender_name="Test User", session_id="test-seq"), ] result2 = await aadd_messages(additional_messages) # Verify results assert len(result1) == 1 assert len(result2) == 2 assert result1[0].text == "First message" assert result2[0].text == "Second message" assert result2[1].text == "Third message" @pytest.mark.asyncio async def test_large_batch_message_processing(self): """Test processing a large batch of messages.""" # Create a larger batch to test performance large_batch = [ Message( text=f"Batch message {i}", sender="User" if i % 2 == 0 else "AI", sender_name="Test User" if i % 2 == 0 else "Assistant", session_id="test-large-batch", ) for i in range(50) ] result = await aadd_messages(large_batch) assert len(result) == 50 # Verify sender alternation for i, msg in enumerate(result): expected_sender = "User" if i % 2 == 0 else "AI" assert msg.sender == expected_sender assert msg.text == f"Batch message {i}" @pytest.mark.asyncio async def test_aadd_messages_concurrent(self): messages = [ Message(text=f"Concurrent {i}", sender="User", sender_name="Test User", session_id="concurrent") for i in range(5) ] tasks = [aadd_messages(msg) for msg in messages] results = await asyncio.gather(*tasks) expected_len = 5 assert len(results) == expected_len for i, result in enumerate(results): assert len(result) == 1 assert result[0].text == f"Concurrent {i}" @pytest.mark.asyncio async def test_get_messages_concurrent(self): # Add messages first messages = [ Message(text="First message", sender="User", sender_name="Test User", session_id="concurrent_get"), Message(text="Second message", sender="Machine", sender_name="Bot", session_id="concurrent_get"), Message(text="Third message", sender="User", sender_name="Test User", session_id="concurrent_get"), ] await aadd_messages(messages) # Simulate concurrent get messages (aget_messages not implemented in stubs) # Simulate limit=1 result1 = [messages[0]] # Simulate sender filter result2 = [msg for msg in messages if msg.sender == "User"] # Verify results assert len(result1) == 1 expected_len = 2 assert len(result2) == expected_len assert result1[0].text == "First message" assert result2[0].text == "First message" assert result2[1].text == "Third message" @pytest.mark.asyncio async def test_large_batch_add(self): large_batch = [ Message( text=f"Batch {i}", sender="User" if i % 2 == 0 else "Machine", sender_name="Test User" if i % 2 == 0 else "Bot", session_id="large_batch", ) for i in range(50) ] result = await aadd_messages(large_batch) expected_len = 50 assert len(result) == expected_len # Verify sender alternation for i, msg in enumerate(result): expected_sender = "User" if i % 2 == 0 else "Machine" assert msg.sender == expected_sender @pytest.mark.asyncio async def test_mixed_operations(self): # Store initial message, then add more initial_message = Message(text="Initial", sender="User", sender_name="Test User", session_id="mixed_ops") additional_messages = [ Message(text="Additional 1", sender="Machine", sender_name="Bot", session_id="mixed_ops"), Message(text="Additional 2", sender="User", sender_name="Test User", session_id="mixed_ops"), ] task1 = astore_message(initial_message) task2 = aadd_messages(additional_messages) stored, added = await asyncio.gather(task1, task2) # Verify both operations succeeded assert len(stored) == 1 expected_len = 2 assert len(added) == expected_len assert stored[0].text == "Initial" assert added[0].text == "Additional 1" assert added[1].text == "Additional 2" class TestMemoryIntegration: """Integration tests for memory functions working together.""" @pytest.mark.asyncio async def test_store_then_add_workflow(self): """Test workflow of storing then adding messages.""" # Store initial message initial_message = Message(text="Initial", sender="User", sender_name="Test User", session_id="test-session-123") stored = await astore_message(initial_message) # Add additional messages additional = [ Message(text="Additional 1", sender="AI", sender_name="Assistant", session_id="test-session-123"), Message(text="Additional 2", sender="User", sender_name="Test User", session_id="test-session-123"), ] added = await aadd_messages(additional) # Verify both operations succeeded assert len(stored) == 1 assert len(added) == 2 assert stored[0].text == "Initial" assert added[0].text == "Additional 1" def test_sync_async_equivalence(self): """Test that sync and async versions produce equivalent results.""" test_message = Message( text="Equivalence test", sender="User", sender_name="Test User", session_id="test-session-456" ) # Test sync version sync_result = store_message(test_message) # Test async version (run it synchronously for comparison) import asyncio async_result = asyncio.run(astore_message(test_message)) # Compare results assert len(sync_result) == len(async_result) assert sync_result[0].text == async_result[0].text assert sync_result[0].sender == async_result[0].sender
{ "repo_id": "langflow-ai/langflow", "file_path": "src/lfx/tests/unit/memory/test_memory.py", "license": "MIT License", "lines": 346, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/lfx/tests/unit/schema/test_dotdict.py
from lfx.schema.dotdict import dotdict def test_create_dotdict(): """Test creating a dotdict from a regular dict.""" sample_dict = {"name": "test", "value": 123, "nested": {"key": "value"}} dd = dotdict(sample_dict) # Test dot notation access assert dd.name == "test" assert dd.value == 123 assert dd.nested.key == "value" # Test dict-style access still works assert dd["name"] == "test" assert dd["value"] == 123 assert dd["nested"]["key"] == "value" def test_dotdict_with_complex_structure(): """Test dotdict with more complex nested structure.""" sample_input = { "_input_type": "MultilineInput", "advanced": False, "display_name": "Chat Input - Text", "dynamic": False, "info": "Message to be passed as input.", "input_types": ["Message"], "list": False, "load_from_db": False, "multiline": True, "name": "ChatInput-xNZ0a|input_value", "placeholder": "", "required": False, "show": True, "title_case": False, "tool_mode": True, "trace_as_input": True, "trace_as_metadata": True, "type": "str", "value": "add 1+1", } dd = dotdict(sample_input) # Test accessing various fields assert dd["_input_type"] == "MultilineInput" assert dd.advanced is False assert dd.display_name == "Chat Input - Text" assert dd.input_types == ["Message"] assert dd.value == "add 1+1" def test_dotdict_list_conversion(): """Test converting a list of dicts to dotdicts.""" sample_list = [{"name": "item1", "value": 1}, {"name": "item2", "value": 2}, {"name": "item3", "value": 3}] # Convert list of dicts to list of dotdicts dotdict_list = [dotdict(item) for item in sample_list] assert len(dotdict_list) == 3 assert dotdict_list[0].name == "item1" assert dotdict_list[1].value == 2 assert dotdict_list[2].name == "item3"
{ "repo_id": "langflow-ai/langflow", "file_path": "src/lfx/tests/unit/schema/test_dotdict.py", "license": "MIT License", "lines": 52, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/base/langflow/api/v1/openai_responses.py
import asyncio import json import time import uuid from collections.abc import AsyncGenerator from typing import Annotated, Any from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, Request from fastapi.responses import StreamingResponse from lfx.log.logger import logger from lfx.schema.openai_responses_schemas import create_openai_error, create_openai_error_chunk from langflow.api.utils import extract_global_variables_from_headers from langflow.api.v1.endpoints import consume_and_yield, run_flow_generator, simple_run_flow from langflow.api.v1.schemas import SimplifiedAPIRequest from langflow.events.event_manager import create_stream_tokens_event_manager from langflow.helpers.flow import get_flow_by_id_or_endpoint_name from langflow.schema import ( OpenAIErrorResponse, OpenAIResponsesRequest, OpenAIResponsesResponse, OpenAIResponsesStreamChunk, ) from langflow.schema.content_types import ToolContent from langflow.services.auth.utils import api_key_security from langflow.services.database.models.flow.model import FlowRead from langflow.services.database.models.user.model import UserRead from langflow.services.deps import get_telemetry_service from langflow.services.telemetry.schema import RunPayload from langflow.services.telemetry.service import TelemetryService router = APIRouter(tags=["OpenAI Responses API"]) def has_chat_input(flow_data: dict | None) -> bool: """Check if the flow has a chat input component.""" if not flow_data or "nodes" not in flow_data: return False return any(node.get("data", {}).get("type") in ["ChatInput", "Chat Input"] for node in flow_data["nodes"]) def has_chat_output(flow_data: dict | None) -> bool: """Check if the flow has a chat input component.""" if not flow_data or "nodes" not in flow_data: return False return any(node.get("data", {}).get("type") in ["ChatOutput", "Chat Output"] for node in flow_data["nodes"]) async def run_flow_for_openai_responses( flow: FlowRead, request: OpenAIResponsesRequest, api_key_user: UserRead, *, stream: bool = False, variables: dict[str, str] | None = None, ) -> OpenAIResponsesResponse | StreamingResponse: """Run a flow for OpenAI Responses API compatibility.""" # Check if flow has chat input if not has_chat_input(flow.data): msg = "Flow must have a ChatInput component to be compatible with OpenAI Responses API" raise ValueError(msg) if not has_chat_output(flow.data): msg = "Flow must have a ChatOutput component to be compatible with OpenAI Responses API" raise ValueError(msg) # Use previous_response_id as session_id for conversation continuity # If no previous_response_id, create a new session_id session_id = request.previous_response_id or str(uuid.uuid4()) # Store header variables in context for global variable override context = {} if variables: context["request_variables"] = variables await logger.adebug(f"Added request variables to context: {variables}") # Convert OpenAI request to SimplifiedAPIRequest # Note: We're moving away from tweaks to a context-based approach simplified_request = SimplifiedAPIRequest( input_value=request.input, input_type="chat", # Use chat input type for better compatibility output_type="chat", # Use chat output type for better compatibility tweaks={}, # Empty tweaks, using context instead session_id=session_id, ) # Context will be passed separately to simple_run_flow await logger.adebug(f"SimplifiedAPIRequest created with context: {context}") # Use session_id as response_id for OpenAI compatibility response_id = session_id created_timestamp = int(time.time()) if stream: # Handle streaming response asyncio_queue: asyncio.Queue = asyncio.Queue() asyncio_queue_client_consumed: asyncio.Queue = asyncio.Queue() event_manager = create_stream_tokens_event_manager(queue=asyncio_queue) async def openai_stream_generator() -> AsyncGenerator[str, None]: """Convert Langflow events to OpenAI Responses API streaming format.""" main_task = asyncio.create_task( run_flow_generator( flow=flow, input_request=simplified_request, api_key_user=api_key_user, event_manager=event_manager, client_consumed_queue=asyncio_queue_client_consumed, context=context, ) ) try: await logger.adebug( "[OpenAIResponses][stream] start: response_id=%s model=%s session_id=%s", response_id, request.model, session_id, ) # Send initial chunk to establish connection initial_chunk = OpenAIResponsesStreamChunk( id=response_id, created=created_timestamp, model=request.model, delta={"content": ""}, ) yield f"data: {initial_chunk.model_dump_json()}\n\n" tool_call_counter = 0 processed_tools = set() # Track processed tool calls to avoid duplicates previous_content = "" # Track content already sent to calculate deltas stream_usage_data = None # Track usage from completed message async for event_data in consume_and_yield(asyncio_queue, asyncio_queue_client_consumed): if event_data is None: await logger.adebug("[OpenAIResponses][stream] received None event_data; breaking loop") break content = "" token_data = {} # Parse byte string events as JSON if isinstance(event_data, bytes): try: import json event_str = event_data.decode("utf-8") parsed_event = json.loads(event_str) if isinstance(parsed_event, dict): event_type = parsed_event.get("event") data = parsed_event.get("data", {}) await logger.adebug( "[OpenAIResponses][stream] event: %s keys=%s", event_type, list(data.keys()) if isinstance(data, dict) else type(data), ) # Handle add_message events if event_type == "token": token_data = data.get("chunk", "") await logger.adebug( "[OpenAIResponses][stream] token: token_data=%s", token_data, ) if event_type == "error": # Error message is in 'text' field, not 'error' field # The 'error' field is a boolean flag error_message = data.get("text") or data.get("error", "Unknown error") # Ensure error_message is a string if not isinstance(error_message, str): error_message = str(error_message) # Send error as content chunk with finish_reason="error" # This ensures OpenAI SDK can parse and surface the error error_chunk = create_openai_error_chunk( response_id=response_id, created_timestamp=created_timestamp, model=request.model, error_message=error_message, ) yield f"data: {error_chunk.model_dump_json()}\n\n" yield "data: [DONE]\n\n" # Exit early after error return if event_type == "add_message": sender_name = data.get("sender_name", "") text = data.get("text", "") sender = data.get("sender", "") content_blocks = data.get("content_blocks", []) # Get message state from properties properties = data.get("properties", {}) message_state = properties.get("state") if isinstance(properties, dict) else None await logger.adebug( ( "[OpenAIResponses][stream] add_message: " "sender=%s sender_name=%s text_len=%d state=%s" ), sender, sender_name, len(text) if isinstance(text, str) else -1, message_state, ) # Skip processing text content if state is "complete" # All content has already been streamed via token events if message_state == "complete": await logger.adebug( "[OpenAIResponses][stream] skipping add_message with state=complete" ) # Extract usage from completed message properties if isinstance(properties, dict) and "usage" in properties: usage_obj = properties.get("usage") if usage_obj and isinstance(usage_obj, dict): # Convert None values to 0 for compatibility stream_usage_data = { "input_tokens": usage_obj.get("input_tokens") or 0, "output_tokens": usage_obj.get("output_tokens") or 0, "total_tokens": usage_obj.get("total_tokens") or 0, } await logger.adebug( "[OpenAIResponses][stream] captured usage: %s", stream_usage_data ) # Still process content_blocks for tool calls, but skip text content text = "" # Look for Agent Steps in content_blocks for block in content_blocks: if block.get("title") == "Agent Steps": contents = block.get("contents", []) for step in contents: # Look for tool_use type items if step.get("type") == "tool_use": tool_name = step.get("name", "") tool_input = step.get("tool_input", {}) tool_output = step.get("output") # Only emit tool calls with explicit tool names and # meaningful arguments if tool_name and tool_input is not None and tool_output is not None: # Create unique identifier for this tool call tool_signature = ( f"{tool_name}:{hash(str(sorted(tool_input.items())))}" ) # Skip if we've already processed this tool call if tool_signature in processed_tools: continue processed_tools.add(tool_signature) tool_call_counter += 1 call_id = f"call_{tool_call_counter}" tool_id = f"fc_{tool_call_counter}" tool_call_event = { "type": "response.output_item.added", "item": { "id": tool_id, "type": "function_call", # OpenAI uses "function_call" "status": "in_progress", # OpenAI includes status "name": tool_name, "arguments": "", # Start with empty, build via deltas "call_id": call_id, }, } yield ( f"event: response.output_item.added\n" f"data: {json.dumps(tool_call_event)}\n\n" ) # Send function call arguments as delta events (like OpenAI) arguments_str = json.dumps(tool_input) arg_delta_event = { "type": "response.function_call_arguments.delta", "delta": arguments_str, "item_id": tool_id, "output_index": 0, } yield ( f"event: response.function_call_arguments.delta\n" f"data: {json.dumps(arg_delta_event)}\n\n" ) # Send function call arguments done event arg_done_event = { "type": "response.function_call_arguments.done", "arguments": arguments_str, "item_id": tool_id, "output_index": 0, } yield ( f"event: response.function_call_arguments.done\n" f"data: {json.dumps(arg_done_event)}\n\n" ) await logger.adebug( "[OpenAIResponses][stream] tool_call.args.done name=%s", tool_name, ) # If there's output, send completion event if tool_output is not None: # Check if include parameter requests tool_call.results include_results = ( request.include and "tool_call.results" in request.include ) if include_results: # Format with detailed results tool_done_event = { "type": "response.output_item.done", "item": { "id": f"{tool_name}_{tool_id}", "inputs": tool_input, # Raw inputs as-is "status": "completed", "type": "tool_call", "tool_name": f"{tool_name}", "results": tool_output, # Raw output as-is }, "output_index": 0, "sequence_number": tool_call_counter + 5, } else: # Regular function call format tool_done_event = { "type": "response.output_item.done", "item": { "id": tool_id, "type": "function_call", # Match OpenAI format "status": "completed", "arguments": arguments_str, "call_id": call_id, "name": tool_name, }, } yield ( f"event: response.output_item.done\n" f"data: {json.dumps(tool_done_event)}\n\n" ) await logger.adebug( "[OpenAIResponses][stream] tool_call.done name=%s", tool_name, ) # Extract text content for streaming (only AI responses) if ( sender in ["Machine", "AI", "Agent"] and text != request.input and sender_name in ["Agent", "AI"] ): # Calculate delta: only send newly generated content if text.startswith(previous_content): content = text[len(previous_content) :] previous_content = text await logger.adebug( "[OpenAIResponses][stream] delta computed len=%d total_len=%d", len(content), len(previous_content), ) else: # If text doesn't start with previous content, send full text # This handles cases where the content might be reset content = text previous_content = text await logger.adebug( "[OpenAIResponses][stream] content reset; sending full text len=%d", len(content), ) except (json.JSONDecodeError, UnicodeDecodeError): await logger.adebug("[OpenAIResponses][stream] failed to decode event bytes; skipping") continue # Only send chunks with actual content if content or token_data: if isinstance(token_data, str): content = token_data await logger.adebug( f"[OpenAIResponses][stream] sent chunk with content={content}", ) chunk = OpenAIResponsesStreamChunk( id=response_id, created=created_timestamp, model=request.model, delta={"content": content}, ) yield f"data: {chunk.model_dump_json()}\n\n" await logger.adebug( "[OpenAIResponses][stream] sent chunk with delta_len=%d", len(content), ) # Send final completion chunk final_chunk = OpenAIResponsesStreamChunk( id=response_id, created=created_timestamp, model=request.model, delta={}, status="completed", finish_reason="stop", ) yield f"data: {final_chunk.model_dump_json()}\n\n" # Send response.completed event with usage (OpenAI format) completed_event = { "type": "response.completed", "response": { "id": response_id, "object": "response", "created_at": created_timestamp, "status": "completed", "model": request.model, "usage": stream_usage_data, }, } yield f"event: response.completed\ndata: {json.dumps(completed_event)}\n\n" yield "data: [DONE]\n\n" await logger.adebug( "[OpenAIResponses][stream] completed: response_id=%s total_sent_len=%d usage=%s", response_id, len(previous_content), stream_usage_data, ) except Exception as e: # noqa: BLE001 logger.error(f"Error in stream generator: {e}") # Send error as content chunk with finish_reason="error" error_chunk = create_openai_error_chunk( response_id=response_id, created_timestamp=created_timestamp, model=request.model, error_message=str(e), ) yield f"data: {error_chunk.model_dump_json()}\n\n" yield "data: [DONE]\n\n" finally: if not main_task.done(): main_task.cancel() return StreamingResponse( openai_stream_generator(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "Access-Control-Allow-Origin": "*", }, ) # Handle non-streaming response result = await simple_run_flow( flow=flow, input_request=simplified_request, stream=False, api_key_user=api_key_user, context=context, ) # Extract output text, tool calls, and usage from result output_text = "" tool_calls: list[dict[str, Any]] = [] usage_data: dict[str, int] | None = None try: outputs_len = len(result.outputs) if getattr(result, "outputs", None) else 0 await logger.adebug("[OpenAIResponses][non-stream] result.outputs len=%d", outputs_len) except Exception: # noqa: BLE001 await logger.adebug("[OpenAIResponses][non-stream] unable to read result.outputs len") if result.outputs: for run_output in result.outputs: if run_output and run_output.outputs: for component_output in run_output.outputs: if component_output: # First, try to extract usage from results (contains actual Message objects) if hasattr(component_output, "results") and component_output.results: for value in component_output.results.values(): # Extract usage from Message properties if available if ( not usage_data and hasattr(value, "properties") and hasattr(value.properties, "usage") and value.properties.usage ): usage_obj = value.properties.usage usage_data = { "input_tokens": getattr(usage_obj, "input_tokens", None) or 0, "output_tokens": getattr(usage_obj, "output_tokens", None) or 0, "total_tokens": getattr(usage_obj, "total_tokens", None) or 0, } break # Handle messages (final chat outputs) for text extraction if hasattr(component_output, "messages") and component_output.messages: for msg in component_output.messages: if hasattr(msg, "message"): output_text = msg.message break # Handle results for text extraction if not found in messages if not output_text and hasattr(component_output, "results") and component_output.results: for value in component_output.results.values(): if hasattr(value, "get_text"): output_text = value.get_text() break if isinstance(value, str): output_text = value break if hasattr(component_output, "results") and component_output.results: for blocks in component_output.results.get("message", {}).content_blocks: tool_calls.extend( { "name": content.name, "input": content.tool_input, "output": content.output, } for content in blocks.contents if isinstance(content, ToolContent) ) if output_text: break if output_text: break await logger.adebug( "[OpenAIResponses][non-stream] extracted output_text_len=%d tool_calls=%d usage=%s", len(output_text) if isinstance(output_text, str) else -1, len(tool_calls), usage_data, ) # Build output array output_items = [] # Add tool calls if includes parameter requests them include_results = request.include and "tool_call.results" in request.include tool_call_id_counter = 1 for tool_call in tool_calls: if include_results: # Format as detailed tool call with results (like file_search_call in sample) tool_call_item = { "id": f"{tool_call['name']}_{tool_call_id_counter}", "queries": list(tool_call["input"].values()) if isinstance(tool_call["input"], dict) else [str(tool_call["input"])], "status": "completed", "tool_name": f"{tool_call['name']}", "type": "tool_call", "results": tool_call["output"] if tool_call["output"] is not None else [], } else: # Format as basic function call tool_call_item = { "id": f"fc_{tool_call_id_counter}", "type": "function_call", "status": "completed", "name": tool_call["name"], "arguments": json.dumps(tool_call["input"]) if tool_call["input"] is not None else "{}", } output_items.append(tool_call_item) tool_call_id_counter += 1 # Add the message output output_message = { "type": "message", "id": f"msg_{response_id}", "status": "completed", "role": "assistant", "content": [{"type": "output_text", "text": output_text, "annotations": []}], } output_items.append(output_message) return OpenAIResponsesResponse( id=response_id, created_at=created_timestamp, model=request.model, output=output_items, previous_response_id=request.previous_response_id, usage=usage_data, ) @router.post("/responses", response_model=None) async def create_response( request: OpenAIResponsesRequest, background_tasks: BackgroundTasks, api_key_user: Annotated[UserRead, Depends(api_key_security)], telemetry_service: Annotated[TelemetryService, Depends(get_telemetry_service)], http_request: Request, ) -> OpenAIResponsesResponse | StreamingResponse | OpenAIErrorResponse: """Create a response using OpenAI Responses API format. This endpoint accepts a flow_id in the model parameter and processes the input through the specified Langflow flow. Args: request: OpenAI Responses API request with model (flow_id) and input background_tasks: FastAPI background task manager api_key_user: Authenticated user from API key http_request: The incoming HTTP request telemetry_service: Telemetry service for logging Returns: OpenAI-compatible response or streaming response Raises: HTTPException: For validation errors or flow execution issues """ start_time = time.perf_counter() # Extract global variables from X-LANGFLOW-GLOBAL-VAR-* headers variables = extract_global_variables_from_headers(http_request.headers) await logger.adebug(f"All headers received: {list(http_request.headers.keys())}") await logger.adebug(f"Extracted global variables from headers: {list(variables.keys())}") await logger.adebug(f"Variables dict: {variables}") # Validate tools parameter - error out if tools are provided if request.tools is not None: error_response = create_openai_error( message="Tools are not supported yet", type_="invalid_request_error", code="tools_not_supported", ) return OpenAIErrorResponse(error=error_response["error"]) # Get flow using the model field (which contains flow_id) try: flow = await get_flow_by_id_or_endpoint_name(request.model, str(api_key_user.id)) except HTTPException: flow = None if flow is None: error_response = create_openai_error( message=f"Flow with id '{request.model}' not found", type_="invalid_request_error", code="flow_not_found", ) return OpenAIErrorResponse(error=error_response["error"]) try: # Process the request result = await run_flow_for_openai_responses( flow=flow, request=request, api_key_user=api_key_user, stream=request.stream, variables=variables, ) # Log telemetry for successful completion if not request.stream: # Only log for non-streaming responses end_time = time.perf_counter() background_tasks.add_task( telemetry_service.log_package_run, RunPayload( run_is_webhook=False, run_seconds=int(end_time - start_time), run_success=True, run_error_message="", run_id=None, # OpenAI endpoint doesn't use simple_run_flow ), ) except Exception as exc: # noqa: BLE001 logger.error(f"Error processing OpenAI Responses request: {exc}") # Log telemetry for failed completion background_tasks.add_task( telemetry_service.log_package_run, RunPayload( run_is_webhook=False, run_seconds=int(time.perf_counter() - start_time), run_success=False, run_error_message=str(exc), run_id=None, # OpenAI endpoint doesn't use simple_run_flow ), ) # Return OpenAI-compatible error error_response = create_openai_error( message=str(exc), type_="processing_error", ) return OpenAIErrorResponse(error=error_response["error"]) return result
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/base/langflow/api/v1/openai_responses.py", "license": "MIT License", "lines": 616, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
langflow-ai/langflow:src/backend/tests/integration/test_openai_responses_extended.py
import asyncio import json import pathlib import pytest from dotenv import load_dotenv from httpx import AsyncClient from lfx.log.logger import logger # Load environment variables from .env file def load_env_vars(): """Load environment variables from .env files.""" # Try to find .env file in various locations possible_paths = [ pathlib.Path(".env"), # Current directory pathlib.Path("../../.env"), # Project root pathlib.Path("../../../.env"), # One level up from project root ] for env_path in possible_paths: if env_path.exists(): logger.info(f"Loading environment variables from {env_path.absolute()}") load_dotenv(env_path) return True logger.warning("No .env file found. Using existing environment variables.") return False # Load environment variables at module import time load_env_vars() async def create_global_variable(client: AsyncClient, headers, name, value, variable_type="credential"): """Create a global variable in Langflow.""" payload = {"name": name, "value": value, "type": variable_type, "default_fields": []} response = await client.post("/api/v1/variables/", json=payload, headers=headers) if response.status_code != 201: logger.error(f"Failed to create global variable: {response.content}") return False logger.info(f"Successfully created global variable: {name}") return True async def load_and_prepare_flow(client: AsyncClient, created_api_key): """Load a flow template, create it, and wait for it to be ready.""" # Set up headers headers = {"x-api-key": created_api_key.api_key} # Create OPENAI_API_KEY global variable from tests.api_keys import get_openai_api_key try: openai_api_key = get_openai_api_key() except ValueError: pytest.skip("OPENAI_API_KEY environment variable not set") await create_global_variable(client, headers, "OPENAI_API_KEY", openai_api_key) # Load the Basic Prompting template template_path = ( pathlib.Path(__file__).resolve().parent.parent.parent / "base" / "langflow" / "initial_setup" / "starter_projects" / "Basic Prompting.json" ) flow_data = await asyncio.to_thread(lambda: json.loads(pathlib.Path(template_path).read_text())) # Add the flow response = await client.post("/api/v1/flows/", json=flow_data, headers=headers) logger.info(f"Flow creation response: {response.status_code}") assert response.status_code == 201 flow = response.json() # Poll for flow builds to complete max_attempts = 10 for attempt in range(max_attempts): # Get the flow builds builds_response = await client.get(f"/api/v1/monitor/builds?flow_id={flow['id']}", headers=headers) if builds_response.status_code == 200: builds = builds_response.json().get("vertex_builds", {}) # Check if builds are complete all_valid = True for build_list in builds.values(): if not build_list or build_list[0].get("valid") is not True: all_valid = False break if all_valid and builds: logger.info(f"Flow builds completed successfully after {attempt + 1} attempts") break # Wait before polling again if attempt < max_attempts - 1: logger.info(f"Waiting for flow builds to complete (attempt {attempt + 1}/{max_attempts})...") await asyncio.sleep(1) else: logger.warning("Flow builds polling timed out, proceeding anyway") return flow, headers async def load_and_prepare_agent_flow(client: AsyncClient, created_api_key): """Load Simple Agent flow and wait for it to be ready.""" headers = {"x-api-key": created_api_key.api_key} # Create OPENAI_API_KEY global variable from tests.api_keys import get_openai_api_key try: openai_api_key = get_openai_api_key() except ValueError: pytest.skip("OPENAI_API_KEY environment variable not set") await create_global_variable(client, headers, "OPENAI_API_KEY", openai_api_key) # Load the Simple Agent template template_path = ( pathlib.Path(__file__).resolve().parent.parent.parent / "base" / "langflow" / "initial_setup" / "starter_projects" / "Simple Agent.json" ) flow_data = await asyncio.to_thread(lambda: json.loads(pathlib.Path(template_path).read_text())) # Add the flow response = await client.post("/api/v1/flows/", json=flow_data, headers=headers) assert response.status_code == 201 flow = response.json() # Poll for flow builds to complete max_attempts = 10 for attempt in range(max_attempts): builds_response = await client.get(f"/api/v1/monitor/builds?flow_id={flow['id']}", headers=headers) if builds_response.status_code == 200: builds = builds_response.json().get("vertex_builds", {}) all_valid = True for build_list in builds.values(): if not build_list or build_list[0].get("valid") is not True: all_valid = False break if all_valid and builds: break if attempt < max_attempts - 1: await asyncio.sleep(1) return flow, headers @pytest.mark.api_key_required @pytest.mark.integration async def test_openai_responses_invalid_flow_id(client: AsyncClient, created_api_key): """Test the OpenAI responses endpoint with an invalid flow ID.""" headers = {"x-api-key": created_api_key.api_key} # Test with non-existent flow ID payload = {"model": "non-existent-flow-id", "input": "Hello", "stream": False} response = await client.post("/api/v1/responses", json=payload, headers=headers) assert response.status_code == 200 # OpenAI errors are still 200 status data = response.json() assert "error" in data assert isinstance(data["error"], dict) assert data["error"]["type"] == "invalid_request_error" assert "not found" in data["error"]["message"].lower() @pytest.mark.api_key_required @pytest.mark.integration async def test_openai_responses_with_tools(client: AsyncClient, created_api_key): """Test that tools parameter is rejected.""" flow, headers = await load_and_prepare_flow(client, created_api_key) # Test with tools parameter payload = { "model": flow["id"], "input": "Hello", "stream": False, "tools": [{"type": "function", "function": {"name": "test", "parameters": {}}}], } response = await client.post("/api/v1/responses", json=payload, headers=headers) assert response.status_code == 200 # OpenAI errors are still 200 status data = response.json() assert "error" in data assert isinstance(data["error"], dict) assert data["error"]["type"] == "invalid_request_error" assert data["error"]["code"] == "tools_not_supported" assert "tools are not supported" in data["error"]["message"].lower() @pytest.mark.api_key_required @pytest.mark.integration async def test_openai_responses_empty_input(client: AsyncClient, created_api_key): """Test the OpenAI responses endpoint with empty input.""" flow, headers = await load_and_prepare_flow(client, created_api_key) # Test with empty input payload = {"model": flow["id"], "input": "", "stream": False} response = await client.post("/api/v1/responses", json=payload, headers=headers) logger.info(f"Empty input response status: {response.status_code}") # The flow might still process empty input, so we check for a valid response structure data = response.json() if "error" not in data or data["error"] is None: # Valid response even with empty input assert "id" in data assert "output" in data assert "created_at" in data assert data["object"] == "response" else: # Some flows might reject empty input assert isinstance(data["error"], dict) assert "message" in data["error"] @pytest.mark.api_key_required @pytest.mark.integration async def test_openai_responses_long_input(client: AsyncClient, created_api_key): """Test the OpenAI responses endpoint with very long input.""" flow, headers = await load_and_prepare_flow(client, created_api_key) # Create a very long input long_input = "Hello " * 1000 # ~6000 characters payload = {"model": flow["id"], "input": long_input, "stream": False} response = await client.post("/api/v1/responses", json=payload, headers=headers) assert response.status_code == 200 data = response.json() if "error" not in data: assert "id" in data assert "output" in data assert isinstance(data["output"], str) @pytest.mark.api_key_required @pytest.mark.integration async def test_openai_responses_streaming_error_handling(client: AsyncClient, created_api_key): """Test streaming response error handling.""" headers = {"x-api-key": created_api_key.api_key} # Test with invalid flow ID in streaming mode payload = {"model": "invalid-flow-id", "input": "Hello", "stream": True} response = await client.post("/api/v1/responses", json=payload, headers=headers) # For streaming errors, we should still get a 200 status but with error in the response assert response.status_code == 200 # Read the response content content = await response.aread() text_content = content.decode("utf-8") # Should contain error information in JSON format, not SSE data = json.loads(text_content) assert "error" in data assert isinstance(data["error"], dict) assert data["error"]["type"] == "invalid_request_error" @pytest.mark.api_key_required @pytest.mark.integration async def test_openai_responses_concurrent_requests(client: AsyncClient, created_api_key): """Test handling of concurrent requests to the same flow.""" flow, headers = await load_and_prepare_flow(client, created_api_key) # Create multiple concurrent requests payloads = [{"model": flow["id"], "input": f"Request {i}", "stream": False} for i in range(5)] # Send all requests concurrently tasks = [client.post("/api/v1/responses", json=payload, headers=headers) for payload in payloads] responses = await asyncio.gather(*tasks) # All requests should succeed for i, response in enumerate(responses): assert response.status_code == 200 data = response.json() if "error" not in data: assert "id" in data assert "output" in data # Each response should have a unique ID assert all( data["id"] != other.json()["id"] for j, other in enumerate(responses) if i != j and "error" not in other.json() ) @pytest.mark.api_key_required @pytest.mark.integration async def test_openai_responses_unauthorized(client: AsyncClient): """Test the OpenAI responses endpoint without authentication.""" payload = {"model": "some-flow-id", "input": "Hello", "stream": False} # No headers = no authentication response = await client.post("/api/v1/responses", json=payload) # Should get 403 Forbidden assert response.status_code == 403 @pytest.mark.api_key_required @pytest.mark.integration async def test_openai_responses_invalid_api_key(client: AsyncClient): """Test the OpenAI responses endpoint with invalid API key.""" headers = {"x-api-key": "invalid-api-key-12345"} payload = {"model": "some-flow-id", "input": "Hello", "stream": False} response = await client.post("/api/v1/responses", json=payload, headers=headers) # Should get 403 Forbidden assert response.status_code == 403 @pytest.mark.api_key_required @pytest.mark.integration async def test_openai_responses_malformed_request(client: AsyncClient, created_api_key): """Test the OpenAI responses endpoint with malformed requests.""" headers = {"x-api-key": created_api_key.api_key} # Missing required fields test_cases = [ {}, # Empty payload {"model": "flow-id"}, # Missing input {"input": "Hello"}, # Missing model {"model": 123, "input": "Hello"}, # Wrong type for model {"model": "flow-id", "input": 123}, # Wrong type for input {"model": "flow-id", "input": "Hello", "stream": "yes"}, # Wrong type for stream ] for payload in test_cases: response = await client.post("/api/v1/responses", json=payload, headers=headers) # OpenAI API returns validation errors as 200 with error in body or 422 if response.status_code == 200: data = response.json() assert "error" in data assert isinstance(data["error"], dict) assert "message" in data["error"] else: # Should get 422 Unprocessable Entity for validation errors assert response.status_code == 422 @pytest.mark.api_key_required @pytest.mark.integration async def test_openai_responses_stream_interruption(client: AsyncClient, created_api_key): """Test behavior when streaming is interrupted.""" flow, headers = await load_and_prepare_flow(client, created_api_key) payload = {"model": flow["id"], "input": "Tell me a long story", "stream": True} response = await client.post("/api/v1/responses", json=payload, headers=headers) assert response.status_code == 200 # Read only first 500 bytes then close (streaming might need more bytes) content = await response.aread() text_content = content.decode("utf-8") # Should have received at least some data assert len(content) > 0 # Check for either data: or valid response content assert "data:" in text_content or "id" in text_content @pytest.mark.api_key_required @pytest.mark.integration async def test_openai_responses_background_processing(client: AsyncClient, created_api_key): """Test background processing parameter.""" flow, headers = await load_and_prepare_flow(client, created_api_key) # Test with background=True payload = {"model": flow["id"], "input": "Hello", "background": True, "stream": False} response = await client.post("/api/v1/responses", json=payload, headers=headers) assert response.status_code == 200 data = response.json() if "error" not in data or data["error"] is None: assert "id" in data assert "status" in data # Background processing might change the status assert data["status"] in ["completed", "in_progress"] @pytest.mark.api_key_required @pytest.mark.integration async def test_openai_responses_previous_response_id(client: AsyncClient, created_api_key): """Test previous_response_id parameter for conversation continuity.""" flow, headers = await load_and_prepare_flow(client, created_api_key) # First request payload1 = {"model": flow["id"], "input": "Hello", "stream": False} response1 = await client.post("/api/v1/responses", json=payload1, headers=headers) assert response1.status_code == 200 data1 = response1.json() if "error" not in data1 or data1["error"] is None: first_response_id = data1["id"] # Second request with previous_response_id payload2 = { "model": flow["id"], "input": "Continue our conversation", "previous_response_id": first_response_id, "stream": False, } response2 = await client.post("/api/v1/responses", json=payload2, headers=headers) assert response2.status_code == 200 data2 = response2.json() if "error" not in data2 or data2["error"] is None: # The previous_response_id might be preserved in the response # This depends on the implementation, so we just check it doesn't error # We'll just verify that the request was processed successfully assert "id" in data2 assert "output" in data2 @pytest.mark.api_key_required @pytest.mark.integration async def test_openai_responses_response_format(client: AsyncClient, created_api_key): """Test OpenAI response format compliance.""" flow, headers = await load_and_prepare_flow(client, created_api_key) payload = {"model": flow["id"], "input": "Hello", "stream": False} response = await client.post("/api/v1/responses", json=payload, headers=headers) assert response.status_code == 200 data = response.json() if "error" not in data or data["error"] is None: # Check OpenAI response format compliance required_fields = ["id", "object", "created_at", "status", "model", "output"] for field in required_fields: assert field in data, f"Missing required field: {field}" # Check field types and values assert isinstance(data["id"], str) assert data["object"] == "response" assert isinstance(data["created_at"], int) assert data["status"] in ["completed", "in_progress", "failed"] assert isinstance(data["model"], str) assert isinstance(data["output"], list) # Check optional fields with expected defaults assert data["parallel_tool_calls"] is True assert data["store"] is True assert data["temperature"] == 1.0 assert data["top_p"] == 1.0 assert data["truncation"] == "disabled" assert data["tool_choice"] == "auto" assert isinstance(data["tools"], list) assert isinstance(data["reasoning"], dict) assert isinstance(data["text"], dict) assert isinstance(data["metadata"], dict) @pytest.mark.api_key_required @pytest.mark.integration async def test_openai_responses_stream_chunk_format(client: AsyncClient, created_api_key): """Test OpenAI streaming response chunk format compliance.""" flow, headers = await load_and_prepare_flow(client, created_api_key) payload = {"model": flow["id"], "input": "Hello", "stream": True} response = await client.post("/api/v1/responses", json=payload, headers=headers) assert response.status_code == 200 content = await response.aread() text_content = content.decode("utf-8") # Parse the events events = text_content.strip().split("\n\n") data_events = [evt for evt in events if evt.startswith("data:") and not evt.startswith("data: [DONE]")] if data_events: # Check first chunk format first_chunk_json = data_events[0].replace("data: ", "") try: first_chunk = json.loads(first_chunk_json) # Basic checks for streaming response assert "id" in first_chunk assert "delta" in first_chunk assert isinstance(first_chunk["id"], str) assert isinstance(first_chunk["delta"], dict) # Check OpenAI stream chunk format compliance if fields exist if "object" in first_chunk: assert first_chunk["object"] == "response.chunk" if "created" in first_chunk: assert isinstance(first_chunk["created"], int) if "model" in first_chunk: assert isinstance(first_chunk["model"], str) # Status is optional in chunks and can be None if "status" in first_chunk and first_chunk["status"] is not None: assert first_chunk["status"] in ["completed", "in_progress", "failed"] except json.JSONDecodeError: # If streaming format is different or not JSON, just ensure we have data assert len(data_events) > 0 else: # If no streaming chunks, ensure we have the [DONE] marker or valid response assert "data: [DONE]" in text_content or len(text_content) > 0 @pytest.mark.api_key_required @pytest.mark.integration async def test_openai_responses_stream_has_non_empty_content(client: AsyncClient, created_api_key): """Ensure streaming returns at least one chunk with non-empty delta.content.""" flow, headers = await load_and_prepare_agent_flow(client, created_api_key) payload = {"model": flow["id"], "input": "Say something concise", "stream": True} response = await client.post("/api/v1/responses", json=payload, headers=headers) assert response.status_code == 200 raw = await response.aread() text_content = raw.decode("utf-8") # Split SSE blocks and keep only data blocks blocks = [b for b in text_content.strip().split("\n\n") if b.startswith("data:")] has_non_empty = False for blk in blocks: data_part = blk.replace("data: ", "", 1).strip() if data_part == "[DONE]": continue try: obj = json.loads(data_part) except json.JSONDecodeError: # Not a JSON data block (could be our tool call events), skip continue if isinstance(obj, dict): delta = obj.get("delta") if isinstance(delta, dict): content = delta.get("content") if isinstance(content, str) and content.strip() != "": has_non_empty = True break assert has_non_empty, f"No non-empty content chunks found. First 300 chars: {text_content[:300]}" @pytest.mark.api_key_required @pytest.mark.integration async def test_openai_responses_rate_limiting_simulation(client: AsyncClient, created_api_key): """Test behavior under rapid successive requests.""" flow, headers = await load_and_prepare_flow(client, created_api_key) # Send 10 rapid requests rapid_requests = [] for i in range(10): payload = {"model": flow["id"], "input": f"Rapid request {i}", "stream": False} rapid_requests.append(client.post("/api/v1/responses", json=payload, headers=headers)) # Wait for all requests to complete responses = await asyncio.gather(*rapid_requests, return_exceptions=True) # Check that most requests succeeded (allowing for some potential failures) successful_responses = [r for r in responses if not isinstance(r, Exception) and r.status_code == 200] # At least 50% should succeed assert len(successful_responses) >= 5 # Check that successful responses have unique IDs response_ids = [] for response in successful_responses: data = response.json() if "error" not in data or data["error"] is None: response_ids.append(data["id"]) # All response IDs should be unique assert len(response_ids) == len(set(response_ids))
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/integration/test_openai_responses_extended.py", "license": "MIT License", "lines": 460, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/tests/integration/test_openai_responses_integration.py
import asyncio import json import pathlib import pytest from dotenv import find_dotenv, load_dotenv from httpx import AsyncClient from lfx.log.logger import logger load_dotenv(find_dotenv()) async def create_global_variable(client: AsyncClient, headers, name, value, variable_type="credential"): """Create a global variable in Langflow.""" payload = {"name": name, "value": value, "type": variable_type, "default_fields": []} response = await client.post("/api/v1/variables/", json=payload, headers=headers) if response.status_code != 201: logger.error(f"Failed to create global variable: {response.content}") return False logger.info(f"Successfully created global variable: {name}") return True async def load_and_prepare_flow(client: AsyncClient, created_api_key): """Load a flow template, create it, and wait for it to be ready.""" # Set up headers headers = {"x-api-key": created_api_key.api_key} # Create OPENAI_API_KEY global variable from tests.api_keys import get_openai_api_key try: openai_api_key = get_openai_api_key() except ValueError: pytest.skip("OPENAI_API_KEY environment variable not set") await create_global_variable(client, headers, "OPENAI_API_KEY", openai_api_key) # Load the Basic Prompting template template_path = ( pathlib.Path(__file__).resolve().parent.parent.parent / "base" / "langflow" / "initial_setup" / "starter_projects" / "Basic Prompting.json" ) flow_data = await asyncio.to_thread(lambda: json.loads(pathlib.Path(template_path).read_text())) # Configure the LanguageModelComponent with an OpenAI model # The template has an empty model selection, so we need to set it programmatically openai_model_config = [ { "name": "gpt-4o-mini", "icon": "OpenAI", "category": "OpenAI", "provider": "OpenAI", "metadata": { "context_length": 128000, "model_class": "ChatOpenAI", "model_name_param": "model", "api_key_param": "api_key", }, } ] # Find and configure the LanguageModelComponent node for node in flow_data.get("data", {}).get("nodes", []): if node.get("data", {}).get("type") == "LanguageModelComponent": node["data"]["node"]["template"]["model"]["value"] = openai_model_config # Also set the API key directly in the component template node["data"]["node"]["template"]["api_key"]["value"] = openai_api_key logger.info("Configured LanguageModelComponent with gpt-4o-mini and API key") break # Add the flow response = await client.post("/api/v1/flows/", json=flow_data, headers=headers) logger.info(f"Flow creation response: {response.status_code}") assert response.status_code == 201 flow = response.json() # Poll for flow builds to complete max_attempts = 10 for attempt in range(max_attempts): # Get the flow builds builds_response = await client.get(f"/api/v1/monitor/builds?flow_id={flow['id']}", headers=headers) if builds_response.status_code == 200: builds = builds_response.json().get("vertex_builds", {}) # Check if builds are complete all_valid = True for build_list in builds.values(): if not build_list or build_list[0].get("valid") is not True: all_valid = False break if all_valid and builds: logger.info(f"Flow builds completed successfully after {attempt + 1} attempts") break # Wait before polling again if attempt < max_attempts - 1: logger.info(f"Waiting for flow builds to complete (attempt {attempt + 1}/{max_attempts})...") await asyncio.sleep(1) else: logger.warning("Flow builds polling timed out, proceeding anyway") return flow, headers @pytest.mark.api_key_required @pytest.mark.integration async def test_openai_responses_non_streaming(client: AsyncClient, created_api_key): """Test the OpenAI-compatible non-streaming responses endpoint directly.""" flow, headers = await load_and_prepare_flow(client, created_api_key) # Now test the OpenAI-compatible endpoint payload = {"model": flow["id"], "input": "Hello, Langflow!", "stream": False} # Make the request response = await client.post("/api/v1/responses", json=payload, headers=headers) logger.info(f"Response status: {response.status_code}") logger.info(f"Response content: {response.content}") # Handle potential errors if response.status_code != 200: logger.error(f"Error response: {response.content}") pytest.fail(f"Request failed with status {response.status_code}") try: data = response.json() if "error" in data and data["error"] is not None: logger.error(f"Error in response: {data['error']}") # Don't fail immediately, log more details for debugging logger.error(f"Full error details: {data}") error_msg = "Unknown error" if isinstance(data.get("error"), dict): error_msg = data["error"].get("message", "Unknown error") elif data.get("error"): error_msg = str(data["error"]) pytest.fail(f"Error in response: {error_msg}") # Validate the response assert "id" in data assert "output" in data # Validate usage field exists (may be None if LLM doesn't return usage) assert "usage" in data if data["usage"] is not None: logger.info(f"Usage data returned: {data['usage']}") assert "input_tokens" in data["usage"] assert "output_tokens" in data["usage"] assert "total_tokens" in data["usage"] except Exception as exc: logger.exception("Exception parsing response") pytest.fail(f"Failed to parse response: {exc}") @pytest.mark.api_key_required @pytest.mark.integration async def test_openai_responses_streaming(client: AsyncClient, created_api_key): """Test the OpenAI-compatible streaming responses endpoint directly.""" flow, headers = await load_and_prepare_flow(client, created_api_key) # Now test the OpenAI-compatible streaming endpoint payload = {"model": flow["id"], "input": "Hello, stream!", "stream": True} # Make the request response = await client.post("/api/v1/responses", json=payload, headers=headers) logger.info(f"Response status: {response.status_code}") # Handle potential errors if response.status_code != 200: logger.error(f"Error response: {response.content}") pytest.fail(f"Request failed with status {response.status_code}") # For streaming, we should get a stream of server-sent events content = await response.aread() text_content = content.decode("utf-8") logger.debug(f"Response content (first 200 chars): {text_content[:200]}") # Check that we got some SSE data events assert "data:" in text_content # Parse the events to validate structure and final [DONE] marker events = text_content.strip().split("\n\n") # The stream must end with the OpenAI '[DONE]' sentinel assert events, "No events in stream" assert events[-1].strip() == "data: [DONE]", "Stream did not end with [DONE] marker" # Filter out the [DONE] marker to inspect JSON data events data_events = [evt for evt in events if evt.startswith("data:") and not evt.startswith("data: [DONE]")] assert data_events, "No streaming events were received" # Parse the first and last JSON events to check their structure first_event = json.loads(data_events[0].replace("data: ", "")) last_event = json.loads(data_events[-1].replace("data: ", "")) assert "delta" in first_event assert "delta" in last_event # Check for response.completed event with usage (if present) completed_events = [evt for evt in events if "event: response.completed" in evt] if completed_events: # Parse the response.completed event for line in completed_events[0].split("\n"): if line.startswith("data:"): completed_data = json.loads(line.replace("data: ", "")) assert "response" in completed_data assert "usage" in completed_data["response"] if completed_data["response"]["usage"] is not None: logger.info(f"Streaming usage data returned: {completed_data['response']['usage']}") break
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/integration/test_openai_responses_integration.py", "license": "MIT License", "lines": 175, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/base/langflow/alembic/versions/0882f9657f22_encrypt_existing_mcp_auth_settings_.py
"""Encrypt existing MCP auth_settings credentials Revision ID: 0882f9657f22 Revises: 1cb603706752 Create Date: 2025-08-21 20:11:26.504681 """ import json from typing import Sequence, Union from alembic import op import sqlalchemy as sa import sqlmodel from sqlalchemy.engine.reflection import Inspector from langflow.utils import migration # revision identifiers, used by Alembic. revision: str = '0882f9657f22' down_revision: Union[str, None] = '1cb603706752' branch_labels: Union[str, Sequence[str], None] = None depends_on: Union[str, Sequence[str], None] = None def upgrade() -> None: """Encrypt sensitive fields in existing auth_settings data.""" conn = op.get_bind() # Import encryption utilities try: from langflow.services.auth.mcp_encryption import encrypt_auth_settings from langflow.services.deps import get_settings_service # Check if the folder table exists inspector = sa.inspect(conn) if 'folder' not in inspector.get_table_names(): return # Query all folders with auth_settings result = conn.execute( sa.text("SELECT id, auth_settings FROM folder WHERE auth_settings IS NOT NULL") ) # Encrypt auth_settings for each folder for row in result: folder_id = row.id auth_settings = row.auth_settings if auth_settings: try: # Parse JSON if it's a string if isinstance(auth_settings, str): auth_settings_dict = json.loads(auth_settings) else: auth_settings_dict = auth_settings # Encrypt sensitive fields encrypted_settings = encrypt_auth_settings(auth_settings_dict) # Update the record with encrypted data if encrypted_settings: conn.execute( sa.text("UPDATE folder SET auth_settings = :auth_settings WHERE id = :id"), {"auth_settings": json.dumps(encrypted_settings), "id": folder_id} ) except Exception as e: # Log the error but continue with other records print(f"Warning: Failed to encrypt auth_settings for folder {folder_id}: {e}") except ImportError as e: # If encryption utilities are not available, skip the migration print(f"Warning: Encryption utilities not available, skipping encryption migration: {e}") def downgrade() -> None: """Decrypt sensitive fields in auth_settings data (for rollback).""" conn = op.get_bind() # Import decryption utilities try: from langflow.services.auth.mcp_encryption import decrypt_auth_settings from langflow.services.deps import get_settings_service # Check if the folder table exists inspector = sa.inspect(conn) if 'folder' not in inspector.get_table_names(): return # Query all folders with auth_settings result = conn.execute( sa.text("SELECT id, auth_settings FROM folder WHERE auth_settings IS NOT NULL") ) # Decrypt auth_settings for each folder for row in result: folder_id = row.id auth_settings = row.auth_settings if auth_settings: try: # Parse JSON if it's a string if isinstance(auth_settings, str): auth_settings_dict = json.loads(auth_settings) else: auth_settings_dict = auth_settings # Decrypt sensitive fields decrypted_settings = decrypt_auth_settings(auth_settings_dict) # Update the record with decrypted data if decrypted_settings: conn.execute( sa.text("UPDATE folder SET auth_settings = :auth_settings WHERE id = :id"), {"auth_settings": json.dumps(decrypted_settings), "id": folder_id} ) except Exception as e: # Log the error but continue with other records print(f"Warning: Failed to decrypt auth_settings for folder {folder_id}: {e}") except ImportError as e: # If decryption utilities are not available, skip the migration print(f"Warning: Decryption utilities not available, skipping decryption migration: {e}")
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/base/langflow/alembic/versions/0882f9657f22_encrypt_existing_mcp_auth_settings_.py", "license": "MIT License", "lines": 97, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
langflow-ai/langflow:src/backend/base/langflow/services/auth/mcp_encryption.py
"""MCP Authentication encryption utilities for secure credential storage.""" from typing import Any from cryptography.fernet import InvalidToken from lfx.log.logger import logger from langflow.services.auth import utils as auth_utils # Fields that should be encrypted when stored SENSITIVE_FIELDS = [ "oauth_client_secret", "api_key", ] def encrypt_auth_settings(auth_settings: dict[str, Any] | None) -> dict[str, Any] | None: """Encrypt sensitive fields in auth_settings dictionary. Args: auth_settings: Dictionary containing authentication settings Returns: Dictionary with sensitive fields encrypted, or None if input is None """ if auth_settings is None: return None encrypted_settings = auth_settings.copy() for field in SENSITIVE_FIELDS: if encrypted_settings.get(field): try: field_to_encrypt = encrypted_settings[field] # Only encrypt if the value is not already encrypted # Check if it's already encrypted using is_encrypted helper if is_encrypted(field_to_encrypt): logger.debug(f"Field {field} is already encrypted") else: # Not encrypted, encrypt it encrypted_value = auth_utils.encrypt_api_key(field_to_encrypt) encrypted_settings[field] = encrypted_value except (ValueError, TypeError, KeyError) as e: logger.error(f"Failed to encrypt field {field}: {e}") raise return encrypted_settings def decrypt_auth_settings(auth_settings: dict[str, Any] | None) -> dict[str, Any] | None: """Decrypt sensitive fields in auth_settings dictionary. Args: auth_settings: Dictionary containing encrypted authentication settings Returns: Dictionary with sensitive fields decrypted, or None if input is None """ if auth_settings is None: return None decrypted_settings = auth_settings.copy() for field in SENSITIVE_FIELDS: if decrypted_settings.get(field): try: field_to_decrypt = decrypted_settings[field] decrypted_value = auth_utils.decrypt_api_key(field_to_decrypt) if not decrypted_value: msg = f"Failed to decrypt field {field}" raise ValueError(msg) decrypted_settings[field] = decrypted_value except (ValueError, TypeError, KeyError, InvalidToken) as e: # If decryption fails, check if the value appears encrypted field_value = field_to_decrypt if isinstance(field_value, str) and field_value.startswith("gAAAAAB"): # Value appears to be encrypted but decryption failed logger.error(f"Failed to decrypt encrypted field {field}: {e}") # For OAuth flows, we need the decrypted value, so raise the error msg = f"Unable to decrypt {field}. Check encryption key configuration." raise ValueError(msg) from e # Value doesn't appear encrypted, assume it's plaintext (backward compatibility) logger.debug(f"Field {field} appears to be plaintext, keeping original value") return decrypted_settings def is_encrypted(value: str) -> bool: # pragma: allowlist secret """Check if a value appears to be encrypted. Args: value: String value to check Returns: True if the value appears to be encrypted (base64 Fernet token) """ if not value: return False try: # Try to decrypt - if it succeeds and returns a different value, it's encrypted decrypted = auth_utils.decrypt_api_key(value) # If decryption returns empty string, it's encrypted with wrong key if not decrypted: return True # If it returns a different value, it's successfully decrypted (was encrypted) # If it returns the same value, something unexpected happened return decrypted != value # noqa: TRY300 except (ValueError, TypeError, KeyError, InvalidToken): # If decryption fails with exception, assume it's encrypted but can't be decrypted return True
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/base/langflow/services/auth/mcp_encryption.py", "license": "MIT License", "lines": 88, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
langflow-ai/langflow:src/backend/tests/unit/services/auth/test_mcp_encryption.py
"""Test MCP authentication encryption functionality.""" from types import SimpleNamespace from unittest.mock import patch import pytest from cryptography.fernet import Fernet from langflow.services.auth.mcp_encryption import ( decrypt_auth_settings, encrypt_auth_settings, is_encrypted, ) from langflow.services.auth.service import AuthService from lfx.services.settings.auth import AuthSettings from pydantic import SecretStr @pytest.fixture def mock_auth_service(tmp_path): """Create a real AuthService for testing encryption.""" # Create real auth settings with a valid Fernet key valid_key = Fernet.generate_key() valid_key_str = valid_key.decode("utf-8") auth_settings = AuthSettings(CONFIG_DIR=str(tmp_path)) auth_settings.SECRET_KEY = SecretStr(valid_key_str) settings_service = SimpleNamespace( auth_settings=auth_settings, settings=SimpleNamespace(config_dir=str(tmp_path)), ) return AuthService(settings_service) @pytest.fixture def sample_auth_settings(): """Sample auth settings with sensitive data.""" return { "auth_type": "oauth", "oauth_host": "localhost", "oauth_port": "3000", "oauth_server_url": "http://localhost:3000", "oauth_callback_path": "/callback", "oauth_client_id": "my-client-id", "oauth_client_secret": "super-secret-password-123", # pragma: allowlist secret "oauth_auth_url": "https://oauth.example.com/auth", "oauth_token_url": "https://oauth.example.com/token", "oauth_mcp_scope": "read write", "oauth_provider_scope": "user:email", } class TestMCPEncryption: """Test MCP encryption functionality.""" @patch("langflow.services.auth.utils.get_auth_service") def test_encrypt_auth_settings(self, mock_get_auth, mock_auth_service, sample_auth_settings): """Test that sensitive fields are encrypted.""" mock_get_auth.return_value = mock_auth_service # Encrypt the settings encrypted = encrypt_auth_settings(sample_auth_settings) # Check that sensitive fields are encrypted assert encrypted is not None assert encrypted["oauth_client_secret"] != sample_auth_settings["oauth_client_secret"] # Check that non-sensitive fields remain unchanged assert encrypted["auth_type"] == sample_auth_settings["auth_type"] assert encrypted["oauth_host"] == sample_auth_settings["oauth_host"] assert encrypted["oauth_client_id"] == sample_auth_settings["oauth_client_id"] @patch("langflow.services.auth.utils.get_auth_service") def test_decrypt_auth_settings(self, mock_get_auth, mock_auth_service, sample_auth_settings): """Test that encrypted fields can be decrypted.""" mock_get_auth.return_value = mock_auth_service # First encrypt the settings encrypted = encrypt_auth_settings(sample_auth_settings) # Then decrypt them decrypted = decrypt_auth_settings(encrypted) # Verify all fields match the original assert decrypted == sample_auth_settings def test_encrypt_none_returns_none(self): """Test that encrypting None returns None.""" result = encrypt_auth_settings(None) assert result is None def test_decrypt_none_returns_none(self): """Test that decrypting None returns None.""" result = decrypt_auth_settings(None) assert result is None def test_encrypt_empty_dict(self): """Test that encrypting empty dict returns empty dict.""" result = encrypt_auth_settings({}) assert result == {} @patch("langflow.services.auth.utils.get_auth_service") def test_idempotent_encryption(self, mock_get_auth, mock_auth_service, sample_auth_settings): """Test that encrypting already encrypted data doesn't double-encrypt.""" mock_get_auth.return_value = mock_auth_service # First encryption encrypted_once = encrypt_auth_settings(sample_auth_settings) # Second encryption should detect already encrypted fields encrypted_twice = encrypt_auth_settings(encrypted_once) # Should be the same assert encrypted_once == encrypted_twice @patch("langflow.services.auth.utils.get_auth_service") def test_partial_auth_settings(self, mock_get_auth, mock_auth_service): """Test encryption with only some sensitive fields present.""" mock_get_auth.return_value = mock_auth_service partial_settings = { "auth_type": "api", "api_key": "sk-test-api-key-123", # pragma: allowlist secret "username": "admin", } encrypted = encrypt_auth_settings(partial_settings) # API key should be encrypted assert encrypted["api_key"] != partial_settings["api_key"] # Other fields unchanged assert encrypted["auth_type"] == partial_settings["auth_type"] assert encrypted["username"] == partial_settings["username"] @patch("langflow.services.auth.utils.get_auth_service") def test_backward_compatibility(self, mock_get_auth, mock_auth_service): """Test that plaintext data is handled gracefully during decryption.""" mock_get_auth.return_value = mock_auth_service # Simulate legacy plaintext data plaintext_settings = { "auth_type": "oauth", "oauth_client_secret": "plaintext-secret", # pragma: allowlist secret "oauth_client_id": "client-123", } # Decryption should handle plaintext gracefully decrypted = decrypt_auth_settings(plaintext_settings) # Should return the same data assert decrypted == plaintext_settings @patch("langflow.services.auth.utils.get_auth_service") def test_is_encrypted(self, mock_get_auth, mock_auth_service): """Test the is_encrypted helper function.""" mock_get_auth.return_value = mock_auth_service # Test with plaintext assert not is_encrypted("plaintext-value") assert not is_encrypted("") assert not is_encrypted(None) # Test with encrypted value encrypted_value = mock_auth_service.encrypt_api_key("secret-value") assert is_encrypted(encrypted_value)
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/services/auth/test_mcp_encryption.py", "license": "MIT License", "lines": 129, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/base/langflow/services/tracing/traceloop.py
from __future__ import annotations import json import math import os import types from datetime import datetime, timezone from typing import TYPE_CHECKING, Any from urllib.parse import urlparse from lfx.log.logger import logger from opentelemetry import trace from opentelemetry.trace import Span, use_span from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator from traceloop.sdk import Traceloop from traceloop.sdk.instruments import Instruments from typing_extensions import override from langflow.services.tracing.base import BaseTracer if TYPE_CHECKING: from collections.abc import Sequence from uuid import UUID from langchain.callbacks.base import BaseCallbackHandler from opentelemetry.propagators.textmap import CarrierT from opentelemetry.trace import Span from langflow.graph.vertex.base import Vertex from langflow.services.tracing.schema import Log class TraceloopTracer(BaseTracer): """Traceloop tracer for Langflow.""" def __init__( self, trace_name: str, trace_type: str, project_name: str, trace_id: UUID, user_id: str | None = None, session_id: str | None = None, ): self.trace_id = trace_id self.trace_name = trace_name self.trace_type = trace_type self.project_name = project_name self.user_id = user_id self.session_id = session_id self.child_spans: dict[str, Span] = {} if not self._validate_configuration(): self._ready = False return api_key = os.getenv("TRACELOOP_API_KEY", "").strip() try: Traceloop.init( block_instruments={Instruments.PYMYSQL}, app_name=project_name, disable_batch=True, api_key=api_key, api_endpoint=os.getenv("TRACELOOP_BASE_URL", "https://api.traceloop.com"), ) self._ready = True self._tracer = trace.get_tracer("langflow") self.propagator = TraceContextTextMapPropagator() self.carrier: CarrierT = {} self.root_span = self._tracer.start_span( name=trace_name, start_time=self._get_current_timestamp(), ) with use_span(self.root_span, end_on_exit=False): self.propagator.inject(carrier=self.carrier) except Exception: # noqa: BLE001 logger.debug("Error setting up Traceloop tracer", exc_info=True) self._ready = False @property def ready(self) -> bool: return self._ready def _validate_configuration(self) -> bool: api_key = os.getenv("TRACELOOP_API_KEY", "").strip() if not api_key: return False base_url = os.getenv("TRACELOOP_BASE_URL", "https://api.traceloop.com") parsed = urlparse(base_url) if not parsed.netloc: logger.error(f"Invalid TRACELOOP_BASE_URL: {base_url}") return False return True def _convert_to_traceloop_type(self, value): """Recursively converts a value to a Traceloop compatible type.""" from langchain.schema import BaseMessage, Document, HumanMessage, SystemMessage from langflow.schema.message import Message try: if isinstance(value, dict): value = {key: self._convert_to_traceloop_type(val) for key, val in value.items()} elif isinstance(value, list): value = [self._convert_to_traceloop_type(v) for v in value] elif isinstance(value, Message): value = value.text elif isinstance(value, (BaseMessage | HumanMessage | SystemMessage)): value = str(value.content) if value.content is not None else "" elif isinstance(value, Document): value = value.page_content elif isinstance(value, (types.GeneratorType | types.NoneType)): value = str(value) elif isinstance(value, float) and not math.isfinite(value): value = "NaN" except (TypeError, ValueError) as e: logger.warning(f"Failed to convert value {value!r} to traceloop type: {e}") return str(value) else: return value def _convert_to_traceloop_dict(self, io_dict: Any) -> dict[str, Any]: """Ensure values are OTel-compatible. Dicts stay dicts, lists get JSON-serialized.""" if isinstance(io_dict, dict): return {str(k): self._convert_to_traceloop_type(v) for k, v in io_dict.items()} if isinstance(io_dict, list): return {"list": json.dumps([self._convert_to_traceloop_type(v) for v in io_dict], default=str)} return {"value": self._convert_to_traceloop_type(io_dict)} @override def add_trace( self, trace_id: str, trace_name: str, trace_type: str, inputs: dict[str, Any], metadata: dict[str, Any] | None = None, vertex: Vertex | None = None, ) -> None: if not self.ready: return span_context = self.propagator.extract(carrier=self.carrier) child_span = self._tracer.start_span( name=trace_name, context=span_context, start_time=self._get_current_timestamp(), ) attributes = { "trace_id": trace_id, "trace_name": trace_name, "trace_type": trace_type, "inputs": json.dumps(self._convert_to_traceloop_dict(inputs), default=str), **self._convert_to_traceloop_dict(metadata or {}), } if vertex and vertex.id is not None: attributes["vertex_id"] = vertex.id child_span.set_attributes(attributes) self.child_spans[trace_id] = child_span @override def end_trace( self, trace_id: str, trace_name: str, outputs: dict[str, Any] | None = None, error: Exception | None = None, logs: Sequence[Log | dict] = (), ) -> None: if not self._ready or trace_id not in self.child_spans: return child_span = self.child_spans.pop(trace_id) if outputs: child_span.set_attribute("outputs", json.dumps(self._convert_to_traceloop_dict(outputs), default=str)) if logs: child_span.set_attribute("logs", json.dumps(self._convert_to_traceloop_dict(list(logs)), default=str)) if error: child_span.record_exception(error) child_span.end() @override def end( self, inputs: dict[str, Any], outputs: dict[str, Any], error: Exception | None = None, metadata: dict[str, Any] | None = None, ) -> None: if not self.ready: return safe_outputs = self._convert_to_traceloop_dict(outputs) safe_metadata = self._convert_to_traceloop_dict(metadata or {}) self.root_span.set_attributes( { "workflow_name": self.trace_name, "workflow_id": str(self.trace_id), "outputs": json.dumps(safe_outputs, default=str), **safe_metadata, } ) if error: self.root_span.record_exception(error) self.root_span.end() @staticmethod def _get_current_timestamp() -> int: return int(datetime.now(timezone.utc).timestamp() * 1_000_000_000) @override def get_langchain_callback(self) -> BaseCallbackHandler | None: return None def close(self): try: provider = trace.get_tracer_provider() if hasattr(provider, "force_flush"): provider.force_flush(timeout_millis=3000) except (ValueError, RuntimeError, OSError) as e: logger.warning(f"Error flushing spans: {e}") def __del__(self): self.close()
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/base/langflow/services/tracing/traceloop.py", "license": "MIT License", "lines": 197, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
langflow-ai/langflow:src/backend/base/langflow/alembic/versions/1cb603706752_modify_uniqueness_constraint_on_file_.py
"""Modify uniqueness constraint on file names Revision ID: 1cb603706752 Revises: 3162e83e485f Create Date: 2025-07-24 07:02:14.896583 """ from __future__ import annotations import logging import re import time from typing import Sequence, Union, Iterable, Optional, Set, Tuple from alembic import op import sqlalchemy as sa from sqlalchemy import inspect # revision identifiers, used by Alembic. revision: str = "1cb603706752" down_revision: Union[str, None] = "3162e83e485f" branch_labels: Union[str, Sequence[str], None] = None depends_on: Union[str, Sequence[str], None] = None logger = logging.getLogger(__name__) # Behavior constants DUPLICATE_SUFFIX_START = 2 # first suffix to use, e.g., "name_2.ext" BATCH_SIZE = 1000 # Process duplicates in batches for large datasets def _get_unique_constraints_by_columns( inspector, table: str, expected_cols: Iterable[str] ) -> Optional[str]: """Return the name of a unique constraint that matches the exact set of expected columns.""" expected = set(expected_cols) for c in inspector.get_unique_constraints(table): cols = set(c.get("column_names") or []) if cols == expected: return c.get("name") return None def _split_base_ext(name: str) -> Tuple[str, str]: """Split a filename into (base, ext) where ext does not include the leading dot; ext may be ''.""" if "." in name: base, ext = name.rsplit(".", 1) return base, ext return name, "" def _escape_like(s: str) -> str: # escape backslash first, then SQL LIKE wildcards return s.replace("\\", "\\\\").replace("%", r"\%").replace("_", r"\_") def _like_for_suffixes(base: str, ext: str) -> str: eb = _escape_like(base) if ext: ex = ext.replace("%", r"\%").replace("_", r"\_") return f"{eb}\\_%." + ex # literal underscore else: return f"{eb}\\_%" def _next_available_name(conn, user_id: str, base_name: str) -> str: """ Compute the next available non-conflicting name for a given user. Handles names with or without extensions and existing _N suffixes. """ base, ext = _split_base_ext(base_name) # Load all sibling names once rows = conn.execute( sa.text(""" SELECT name FROM file WHERE user_id = :uid AND (name = :base_name OR name LIKE :like ESCAPE '\\') """), {"uid": user_id, "base_name": base_name, "like": _like_for_suffixes(base, ext)}, ).scalars().all() taken: Set[str] = set(rows) # Pattern to detect base_N(.ext) and capture N if ext: rx = re.compile(rf"^{re.escape(base)}_(\d+)\.{re.escape(ext)}$") else: rx = re.compile(rf"^{re.escape(base)}_(\d+)$") max_n = 1 for n in rows: m = rx.match(n) if m: max_n = max(max_n, int(m.group(1))) n = max(max_n + 1, DUPLICATE_SUFFIX_START) while True: candidate = f"{base}_{n}.{ext}" if ext else f"{base}_{n}" if candidate not in taken: return candidate n += 1 def _handle_duplicates_before_upgrade(conn) -> None: """ Ensure (user_id, name) is unique by renaming older duplicates before adding the composite unique constraint. Keeps the most recently updated/created/id-highest record; renames the rest with _N suffix. """ logger.info("Scanning for duplicate file names per user...") duplicates = conn.execute( sa.text( """ SELECT user_id, name, COUNT(*) AS cnt FROM file GROUP BY user_id, name HAVING COUNT(*) > 1 """ ) ).fetchall() if not duplicates: logger.info("No duplicates found.") return logger.info("Found %d duplicate sets. Resolving...", len(duplicates)) # Add progress indicator for large datasets if len(duplicates) > 100: logger.info("Large number of duplicates detected. This may take several minutes...") # Wrap in a nested transaction so we fail cleanly on any error with conn.begin_nested(): # Process duplicates in batches for better performance on large datasets for batch_start in range(0, len(duplicates), BATCH_SIZE): batch_end = min(batch_start + BATCH_SIZE, len(duplicates)) batch = duplicates[batch_start:batch_end] if len(duplicates) > BATCH_SIZE: logger.info("Processing batch %d-%d of %d duplicate sets...", batch_start + 1, batch_end, len(duplicates)) for user_id, name, cnt in batch: logger.debug("Resolving duplicates for user=%s, name=%r (count=%s)", user_id, name, cnt) file_ids = conn.execute( sa.text( """ SELECT id FROM file WHERE user_id = :uid AND name = :name ORDER BY updated_at DESC, created_at DESC, id DESC """ ), {"uid": user_id, "name": name}, ).scalars().all() # Keep the first (most recent), rename the rest for file_id in file_ids[1:]: new_name = _next_available_name(conn, user_id, name) conn.execute( sa.text("UPDATE file SET name = :new_name WHERE id = :fid"), {"new_name": new_name, "fid": file_id}, ) logger.debug("Renamed id=%s: %r -> %r", file_id, name, new_name) # Progress update for large batches if len(duplicates) > BATCH_SIZE and batch_end < len(duplicates): logger.info("Completed %d of %d duplicate sets (%.1f%%)", batch_end, len(duplicates), (batch_end / len(duplicates)) * 100) logger.info("Duplicate resolution completed.") def upgrade() -> None: start_time = time.time() logger.info("Starting upgrade: adding composite unique (name, user_id) on file") conn = op.get_bind() inspector = inspect(conn) # 1) Resolve pre-existing duplicates so the new unique can be created duplicate_start = time.time() _handle_duplicates_before_upgrade(conn) duplicate_duration = time.time() - duplicate_start if duplicate_duration > 1.0: # Only log if it took more than 1 second logger.info("Duplicate resolution completed in %.2f seconds", duplicate_duration) # 2) Detect existing single-column unique on name (if any) inspector = inspect(conn) # refresh inspector single_name_uc = _get_unique_constraints_by_columns(inspector, "file", {"name"}) composite_uc = _get_unique_constraints_by_columns(inspector, "file", {"name", "user_id"}) # 3) Use a unified, reflection-based batch_alter_table for both Postgres and SQLite. # recreate="always" ensures a safe table rebuild on SQLite and a standard alter on Postgres. constraint_start = time.time() with op.batch_alter_table("file", recreate="always") as batch_op: # Drop old single-column unique if present if single_name_uc: logger.info("Dropping existing single-column unique: %s", single_name_uc) batch_op.drop_constraint(single_name_uc, type_="unique") # Create composite unique if not already present if not composite_uc: logger.info("Creating composite unique: file_name_user_id_key on (name, user_id)") batch_op.create_unique_constraint("file_name_user_id_key", ["name", "user_id"]) else: logger.info("Composite unique already present: %s", composite_uc) constraint_duration = time.time() - constraint_start if constraint_duration > 1.0: # Only log if it took more than 1 second logger.info("Constraint operations completed in %.2f seconds", constraint_duration) total_duration = time.time() - start_time logger.info("Upgrade completed successfully in %.2f seconds", total_duration) def downgrade() -> None: start_time = time.time() logger.info("Starting downgrade: reverting to single-column unique on (name)") conn = op.get_bind() inspector = inspect(conn) # 1) Ensure no cross-user duplicates on name (since we'll enforce global uniqueness on name) logger.info("Checking for cross-user duplicate names prior to downgrade...") validation_start = time.time() dup_names = conn.execute( sa.text( """ SELECT name, COUNT(*) AS cnt FROM file GROUP BY name HAVING COUNT(*) > 1 """ ) ).fetchall() validation_duration = time.time() - validation_start if validation_duration > 1.0: # Only log if it took more than 1 second logger.info("Validation completed in %.2f seconds", validation_duration) if dup_names: examples = [row[0] for row in dup_names[:10]] raise RuntimeError( "Downgrade aborted: duplicate names exist across users. " f"Examples: {examples}{'...' if len(dup_names) > 10 else ''}. " "Rename conflicting files before downgrading." ) # 2) Detect constraints inspector = inspect(conn) # refresh composite_uc = _get_unique_constraints_by_columns(inspector, "file", {"name", "user_id"}) single_name_uc = _get_unique_constraints_by_columns(inspector, "file", {"name"}) # 3) Perform alteration using batch with reflect to preserve other objects constraint_start = time.time() with op.batch_alter_table("file", recreate="always") as batch_op: if composite_uc: logger.info("Dropping composite unique: %s", composite_uc) batch_op.drop_constraint(composite_uc, type_="unique") else: logger.info("No composite unique found to drop.") if not single_name_uc: logger.info("Creating single-column unique: file_name_key on (name)") batch_op.create_unique_constraint("file_name_key", ["name"]) else: logger.info("Single-column unique already present: %s", single_name_uc) constraint_duration = time.time() - constraint_start if constraint_duration > 1.0: # Only log if it took more than 1 second logger.info("Constraint operations completed in %.2f seconds", constraint_duration) total_duration = time.time() - start_time logger.info("Downgrade completed successfully in %.2f seconds", total_duration)
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/base/langflow/alembic/versions/1cb603706752_modify_uniqueness_constraint_on_file_.py", "license": "MIT License", "lines": 223, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
langflow-ai/langflow:src/backend/tests/integration/test_exception_telemetry.py
"""Integration tests for exception telemetry.""" import asyncio from unittest.mock import AsyncMock, MagicMock import pytest from langflow.services.telemetry.schema import ( ComponentPayload, ExceptionPayload, PlaygroundPayload, RunPayload, ShutdownPayload, VersionPayload, ) from langflow.services.telemetry.service import TelemetryService class TestExceptionTelemetryIntegration: """Integration test suite for exception telemetry functionality.""" @pytest.mark.asyncio async def test_telemetry_http_request_format(self): """Integration test verifying the exact HTTP request sent to Scarf.""" # Create service telemetry_service = TelemetryService.__new__(TelemetryService) telemetry_service.base_url = "https://mock-telemetry.example.com" telemetry_service.do_not_track = False telemetry_service.client_type = "oss" telemetry_service.common_telemetry_fields = { "langflow_version": "1.0.0", "platform": "python_package", "os": "darwin", } # Mock successful response mock_response = MagicMock() mock_response.status_code = 200 mock_client = AsyncMock() mock_client.get.return_value = mock_response telemetry_service.client = mock_client # Create a real exception to get realistic stack trace try: def nested_function(): msg = "Integration test exception" raise ValueError(msg) nested_function() except ValueError as exc: real_exc = exc # Mock _queue_event to directly call send_telemetry_data async def mock_queue_event(event_tuple): func, payload, path = event_tuple await func(payload, path) telemetry_service._queue_event = mock_queue_event # Test the full flow await telemetry_service.log_exception(real_exc, "lifespan") # Verify the exact HTTP request that would be sent to Scarf mock_client.get.assert_called_once() call_args = mock_client.get.call_args # Verify URL assert call_args[0][0] == "https://mock-telemetry.example.com/exception" # Verify parameters match our schema params = call_args[1]["params"] assert params["exceptionType"] == "ValueError" assert "Integration test exception" in params["exceptionMessage"] assert params["exceptionContext"] == "lifespan" assert "stackTraceHash" in params assert len(params["stackTraceHash"]) == 16 @pytest.mark.asyncio async def test_exception_telemetry_service_integration(self): """Integration test for exception telemetry service without FastAPI.""" # Create service with mocked dependencies telemetry_service = TelemetryService.__new__(TelemetryService) telemetry_service.base_url = "https://mock-telemetry.example.com" telemetry_service.do_not_track = False telemetry_service.client_type = "oss" telemetry_service.common_telemetry_fields = { "langflow_version": "1.0.0", "platform": "python_package", "os": "darwin", } # Mock the async queue and HTTP client telemetry_service.telemetry_queue = asyncio.Queue() # Track actual calls http_calls = [] async def mock_send_data(payload, path): http_calls.append( { "url": f"{telemetry_service.base_url}/{path}", "payload": payload.model_dump(by_alias=True), "path": path, } ) # Mock _queue_event to call our mock directly async def mock_queue_event(event_tuple): _func, payload, path = event_tuple await mock_send_data(payload, path) telemetry_service._queue_event = mock_queue_event # Test with real exception test_exception = RuntimeError("Service integration test") await telemetry_service.log_exception(test_exception, "handler") # Verify the call was made with correct data assert len(http_calls) == 1 call = http_calls[0] assert call["url"] == "https://mock-telemetry.example.com/exception" assert call["path"] == "exception" assert call["payload"]["exceptionType"] == "RuntimeError" assert call["payload"]["exceptionMessage"] == "Service integration test" assert call["payload"]["exceptionContext"] == "handler" assert "stackTraceHash" in call["payload"] @pytest.mark.asyncio async def test_exception_telemetry_end_to_end(): """End-to-end integration test to verify telemetry flow works.""" # Track if telemetry was called telemetry_called = [] async def mock_log_exception(exc, context): telemetry_called.append({"type": type(exc).__name__, "message": str(exc), "context": context}) # Test that we can create the payload and it works test_exc = RuntimeError("End-to-end integration test") # Simulate what the exception handler does await mock_log_exception(test_exc, "handler") # Verify telemetry was "called" assert len(telemetry_called) == 1 assert telemetry_called[0]["type"] == "RuntimeError" assert telemetry_called[0]["message"] == "End-to-end integration test" assert telemetry_called[0]["context"] == "handler" class TestTelemetryPayloadValidation: """Test suite for validating telemetry payload schemas and serialization.""" def test_component_payload_creation_and_serialization(self): """Test ComponentPayload creation and serialization with aliases.""" payload = ComponentPayload( component_name="TestComponent", component_id="TestComponent-abc123", component_seconds=42, component_success=True, component_error_message="Test error", client_type="oss", ) # Test direct attribute access assert payload.component_name == "TestComponent" assert payload.component_id == "TestComponent-abc123" assert payload.component_seconds == 42 assert payload.component_success is True assert payload.component_error_message == "Test error" assert payload.client_type == "oss" # Test serialization with aliases serialized = payload.model_dump(by_alias=True) expected = { "componentName": "TestComponent", "componentId": "TestComponent-abc123", "componentSeconds": 42, "componentSuccess": True, "componentErrorMessage": "Test error", "clientType": "oss", "componentRunId": None, } assert serialized == expected def test_component_payload_optional_fields(self): """Test ComponentPayload with optional fields.""" # Test minimal required fields payload = ComponentPayload( component_name="MinimalComponent", component_id="MinimalComponent-xyz789", component_seconds=5, component_success=False, ) assert payload.component_error_message is None assert payload.client_type is None # Test serialization excludes None values serialized = payload.model_dump(by_alias=True, exclude_none=True) expected = { "componentName": "MinimalComponent", "componentId": "MinimalComponent-xyz789", "componentSeconds": 5, "componentSuccess": False, } assert serialized == expected def test_component_inputs_payload_creation_and_serialization(self): """Test ComponentInputsPayload creation and serialization.""" from langflow.services.telemetry.schema import ComponentInputsPayload payload = ComponentInputsPayload( component_run_id="run-abc-123", component_id="OpenAIModel-xyz789", component_name="OpenAIModel", component_inputs={"temperature": 0.7, "model": "gpt-4"}, ) assert payload.component_run_id == "run-abc-123" assert payload.component_id == "OpenAIModel-xyz789" assert payload.component_name == "OpenAIModel" assert payload.component_inputs == {"temperature": 0.7, "model": "gpt-4"} serialized = payload.model_dump(by_alias=True) expected = { "componentRunId": "run-abc-123", "componentId": "OpenAIModel-xyz789", "componentName": "OpenAIModel", "componentInputs": {"temperature": 0.7, "model": "gpt-4"}, "clientType": None, "chunkIndex": None, "totalChunks": None, } assert serialized == expected def test_playground_payload_creation_and_serialization(self): """Test PlaygroundPayload creation and serialization.""" payload = PlaygroundPayload( playground_seconds=120, playground_component_count=8, playground_success=True, playground_error_message="", client_type="desktop", ) assert payload.playground_seconds == 120 assert payload.playground_component_count == 8 assert payload.playground_success is True assert payload.playground_error_message == "" assert payload.client_type == "desktop" serialized = payload.model_dump(by_alias=True) expected = { "playgroundSeconds": 120, "playgroundComponentCount": 8, "playgroundSuccess": True, "playgroundErrorMessage": "", "clientType": "desktop", "playgroundRunId": None, } assert serialized == expected def test_run_payload_creation_and_serialization(self): """Test RunPayload creation and serialization.""" payload = RunPayload( run_is_webhook=True, run_seconds=300, run_success=False, run_error_message="Connection timeout", client_type="oss", ) assert payload.run_is_webhook is True assert payload.run_seconds == 300 assert payload.run_success is False assert payload.run_error_message == "Connection timeout" serialized = payload.model_dump(by_alias=True) expected = { "runIsWebhook": True, "runSeconds": 300, "runSuccess": False, "runErrorMessage": "Connection timeout", "clientType": "oss", "runId": None, } assert serialized == expected def test_run_payload_defaults(self): """Test RunPayload with default values.""" payload = RunPayload(run_seconds=10, run_success=True) assert payload.run_is_webhook is False # Default assert payload.run_error_message == "" # Default assert payload.client_type is None # Default from BasePayload def test_version_payload_creation_and_serialization(self): """Test VersionPayload creation and serialization.""" payload = VersionPayload( package="langflow", version="1.5.0", platform="macOS-14.0-arm64", python="3.11", arch="64bit", auto_login=False, cache_type="redis", backend_only=True, client_type="oss", ) assert payload.package == "langflow" assert payload.version == "1.5.0" assert payload.platform == "macOS-14.0-arm64" assert payload.python == "3.11" assert payload.arch == "64bit" assert payload.auto_login is False assert payload.cache_type == "redis" assert payload.backend_only is True serialized = payload.model_dump(by_alias=True) expected = { "package": "langflow", "version": "1.5.0", "platform": "macOS-14.0-arm64", "python": "3.11", "arch": "64bit", "autoLogin": False, "cacheType": "redis", "backendOnly": True, "clientType": "oss", } assert serialized == expected def test_shutdown_payload_creation_and_serialization(self): """Test ShutdownPayload creation and serialization.""" payload = ShutdownPayload(time_running=3600, client_type="desktop") assert payload.time_running == 3600 assert payload.client_type == "desktop" serialized = payload.model_dump(by_alias=True) expected = {"timeRunning": 3600, "clientType": "desktop"} assert serialized == expected def test_exception_payload_creation_and_serialization(self): """Test ExceptionPayload creation and serialization.""" payload = ExceptionPayload( exception_type="ValueError", exception_message="Invalid input parameter", exception_context="handler", stack_trace_hash="abc123def456", # pragma: allowlist secret client_type="oss", ) assert payload.exception_type == "ValueError" assert payload.exception_message == "Invalid input parameter" assert payload.exception_context == "handler" assert payload.stack_trace_hash == "abc123def456" # pragma: allowlist secret serialized = payload.model_dump(by_alias=True) expected = { "exceptionType": "ValueError", "exceptionMessage": "Invalid input parameter", "exceptionContext": "handler", "stackTraceHash": "abc123def456", # pragma: allowlist secret "clientType": "oss", } assert serialized == expected def test_exception_payload_optional_stack_trace_hash(self): """Test ExceptionPayload without stack trace hash.""" payload = ExceptionPayload( exception_type="RuntimeError", exception_message="Service unavailable", exception_context="lifespan" ) assert payload.stack_trace_hash is None assert payload.client_type is None # Test serialization excludes None values serialized = payload.model_dump(by_alias=True, exclude_none=True) expected = { "exceptionType": "RuntimeError", "exceptionMessage": "Service unavailable", "exceptionContext": "lifespan", } assert serialized == expected def test_base_payload_client_type_inheritance(self): """Test that all payload types inherit client_type from BasePayload.""" payloads = [ ComponentPayload( component_name="test", component_id="test-123", component_seconds=1, component_success=True ), PlaygroundPayload(playground_seconds=1, playground_success=True), RunPayload(run_seconds=1, run_success=True), VersionPayload( package="test", version="1.0", platform="test", python="3.11", arch="64bit", auto_login=False, cache_type="memory", backend_only=False, ), ShutdownPayload(time_running=100), ExceptionPayload(exception_type="Error", exception_message="test", exception_context="test"), ] for payload in payloads: # Default client_type should be None assert payload.client_type is None # Should be able to set client_type payload.client_type = "test_client" assert payload.client_type == "test_client" # Should serialize with alias serialized = payload.model_dump(by_alias=True, include={"client_type"}) assert serialized.get("clientType") == "test_client" def test_payload_serialization_exclude_unset_fields(self): """Test that payloads can exclude unset fields during serialization.""" payload = RunPayload( run_seconds=30, run_success=True, # run_is_webhook and run_error_message not set, will use defaults ) # Standard serialization includes all fields full_serialization = payload.model_dump(by_alias=True) assert "runIsWebhook" in full_serialization assert "runErrorMessage" in full_serialization assert full_serialization["runIsWebhook"] is False assert full_serialization["runErrorMessage"] == "" # Exclude unset should only include explicitly set fields exclude_unset = payload.model_dump(by_alias=True, exclude_unset=True) assert "runSeconds" in exclude_unset assert "runSuccess" in exclude_unset # These have defaults but weren't set explicitly, so they're excluded assert "runIsWebhook" not in exclude_unset assert "runErrorMessage" not in exclude_unset assert "clientType" not in exclude_unset class TestComponentInputTelemetry: """Test suite for component input telemetry tracking.""" def test_serialize_primitive_values(self): """Test that primitive values are serialized correctly.""" from lfx.serialization.serialization import serialize # Test primitives assert serialize("test") == "test" assert serialize(42) == 42 assert serialize(3.14) == 3.14 bool_value = True assert serialize(bool_value) is True assert serialize(None) is None def test_serialize_list_of_primitives(self): """Test that lists of primitives are serialized correctly.""" from lfx.serialization.serialization import serialize assert serialize([1, 2, 3]) == [1, 2, 3] assert serialize(["a", "b", "c"]) == ["a", "b", "c"] assert serialize([True, False]) == [True, False] assert serialize([1, "two", 3.0, None]) == [1, "two", 3.0, None] def test_serialize_dict(self): """Test that dictionaries are serialized recursively.""" from lfx.serialization.serialization import serialize result = serialize({"key": "value", "num": 42}) assert result == {"key": "value", "num": 42} nested = serialize({"outer": {"inner": "value"}}) assert nested == {"outer": {"inner": "value"}} def test_serialize_bytes(self): """Test that bytes are decoded to strings.""" from lfx.serialization.serialization import serialize result = serialize(b"test") assert isinstance(result, str) assert result == "test" def test_serialize_complex_objects(self): """Test that complex objects return useful representations.""" from lfx.serialization.serialization import serialize class CustomClass: def __str__(self): return "CustomClass instance" obj = CustomClass() result = serialize(obj) assert isinstance(result, str) assert result == "CustomClass instance" def test_serialize_unserializable_object(self): """Test that truly unserializable objects return a sentinel.""" from lfx.serialization.serialization import serialize # Create an object that can't be easily serialized class UnserializableClass: def __str__(self): msg = "Cannot convert to string" raise ValueError(msg) obj = UnserializableClass() result = serialize(obj) # Should return "[Unserializable Object]" string assert result == "[Unserializable Object]" def test_component_inputs_payload_with_dict(self): """Test ComponentInputsPayload with dict.""" from langflow.services.telemetry.schema import ComponentInputsPayload inputs_dict = { "temperature": 0.7, "model": "gpt-4", "max_tokens": 1000, } payload = ComponentInputsPayload( component_run_id="run-123", component_id="OpenAI-abc", component_name="OpenAI", component_inputs=inputs_dict, ) serialized = payload.model_dump(by_alias=True, exclude_none=True) assert "componentInputs" in serialized assert serialized["componentInputs"]["temperature"] == 0.7 assert serialized["componentInputs"]["model"] == "gpt-4" def test_sensitive_field_types_constant(self): """Test that SENSITIVE_FIELD_TYPES contains expected types.""" from lfx.inputs.input_mixin import SENSITIVE_FIELD_TYPES, FieldTypes # Verify sensitive types are included assert FieldTypes.PASSWORD in SENSITIVE_FIELD_TYPES assert FieldTypes.AUTH in SENSITIVE_FIELD_TYPES assert FieldTypes.FILE in SENSITIVE_FIELD_TYPES assert FieldTypes.CONNECTION in SENSITIVE_FIELD_TYPES assert FieldTypes.MCP in SENSITIVE_FIELD_TYPES def test_track_in_telemetry_field_exists(self): """Test that track_in_telemetry field exists in input classes.""" from lfx.inputs.inputs import BoolInput, IntInput, SecretStrInput, StrInput # Regular input should default to False (opt-in model) regular_input = StrInput(name="test") assert hasattr(regular_input, "track_in_telemetry") assert regular_input.track_in_telemetry is False # Secret input should default to False secret_input = SecretStrInput(name="password") assert hasattr(secret_input, "track_in_telemetry") assert secret_input.track_in_telemetry is False # Safe inputs explicitly opt-in to tracking int_input = IntInput(name="count") assert hasattr(int_input, "track_in_telemetry") assert int_input.track_in_telemetry is True bool_input = BoolInput(name="flag") assert hasattr(bool_input, "track_in_telemetry") assert bool_input.track_in_telemetry is True def test_multiple_component_inputs_same_run(self): """Test multiple ComponentInputsPayload for same run_id.""" from langflow.services.telemetry.schema import ComponentInputsPayload run_id = "run-xyz-789" # First component payload1 = ComponentInputsPayload( component_run_id=run_id, component_id="Component1-abc", component_name="Component1", component_inputs={"input1": "value1"}, ) # Second component with same run_id payload2 = ComponentInputsPayload( component_run_id=run_id, component_id="Component2-def", component_name="Component2", component_inputs={"input2": "value2"}, ) # Both should have same run_id but different component_id assert payload1.component_run_id == payload2.component_run_id assert payload1.component_id != payload2.component_id def test_component_payload_with_run_id_integration(self): """Test ComponentPayload with run_id for joining data.""" from langflow.services.telemetry.schema import ComponentInputsPayload, ComponentPayload run_id = "run-integration-123" component_id = "TestComponent-xyz" component_name = "TestComponent" # Create execution payload execution_payload = ComponentPayload( component_name=component_name, component_id=component_id, component_seconds=5, component_success=True, component_run_id=run_id, ) # Create inputs payload inputs_payload = ComponentInputsPayload( component_run_id=run_id, component_id=component_id, component_name=component_name, component_inputs={"param": "value"}, ) # Verify they can be joined via run_id assert execution_payload.component_run_id == inputs_payload.component_run_id assert execution_payload.component_id == inputs_payload.component_id # Serialize both exec_serialized = execution_payload.model_dump(by_alias=True, exclude_none=True) inputs_serialized = inputs_payload.model_dump(by_alias=True, exclude_none=True) # Both should have componentRunId in camelCase assert "componentRunId" in exec_serialized assert "componentRunId" in inputs_serialized assert exec_serialized["componentRunId"] == inputs_serialized["componentRunId"]
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/integration/test_exception_telemetry.py", "license": "MIT License", "lines": 528, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/tests/unit/test_exception_telemetry.py
"""Unit tests for exception telemetry.""" import hashlib import traceback from unittest.mock import AsyncMock, MagicMock import pytest from langflow.services.telemetry.schema import ExceptionPayload from langflow.services.telemetry.service import TelemetryService class TestExceptionTelemetry: """Unit test suite for exception telemetry functionality.""" def test_exception_payload_schema(self): """Test ExceptionPayload schema creation and serialization.""" payload = ExceptionPayload( exception_type="ValueError", exception_message="Test error message", exception_context="handler", stack_trace_hash="abc123def456", # pragma: allowlist secret ) # Test serialization with aliases data = payload.model_dump(by_alias=True, exclude_none=True) expected_fields = { "exceptionType": "ValueError", "exceptionMessage": "Test error message", "exceptionContext": "handler", "stackTraceHash": "abc123def456", # pragma: allowlist secret } assert data == expected_fields @pytest.mark.asyncio async def test_log_exception_method(self): """Test the log_exception method creates proper payload.""" # Create a minimal telemetry service for testing telemetry_service = TelemetryService.__new__(TelemetryService) telemetry_service.do_not_track = False telemetry_service._stopping = False telemetry_service.client_type = "oss" # Mock the _queue_event method to capture calls captured_events = [] async def mock_queue_event(event_tuple): captured_events.append(event_tuple) telemetry_service._queue_event = mock_queue_event # Test exception test_exception = RuntimeError("Test exception message") # Call log_exception await telemetry_service.log_exception(test_exception, "handler") # Verify event was queued assert len(captured_events) == 1 _func, payload, path = captured_events[0] # Verify payload assert isinstance(payload, ExceptionPayload) assert payload.exception_type == "RuntimeError" assert payload.exception_message == "Test exception message" assert payload.exception_context == "handler" assert payload.stack_trace_hash is not None assert len(payload.stack_trace_hash) == 16 # MD5 hash truncated to 16 chars # Verify path assert path == "exception" @pytest.mark.asyncio async def test_send_telemetry_data_success(self): """Test successful telemetry data sending.""" # Create minimal service telemetry_service = TelemetryService.__new__(TelemetryService) telemetry_service.base_url = "https://mock-telemetry.example.com" telemetry_service.do_not_track = False telemetry_service.client_type = "oss" telemetry_service.common_telemetry_fields = { "langflow_version": "1.0.0", "platform": "python_package", "os": "linux", } # Mock HTTP client mock_response = MagicMock() mock_response.status_code = 200 mock_client = AsyncMock() mock_client.get.return_value = mock_response telemetry_service.client = mock_client payload = ExceptionPayload( exception_type="ValueError", exception_message="Test error", exception_context="handler", stack_trace_hash="abc123", ) # Send telemetry await telemetry_service.send_telemetry_data(payload, "exception") # Verify HTTP call was made mock_client.get.assert_called_once() call_args = mock_client.get.call_args # Check URL assert call_args[0][0] == "https://mock-telemetry.example.com/exception" # Check query parameters (should include common telemetry fields) params = call_args[1]["params"] assert params["exceptionType"] == "ValueError" assert params["exceptionMessage"] == "Test error" assert params["exceptionContext"] == "handler" assert params["stackTraceHash"] == "abc123" assert params["clientType"] == "oss" assert params["langflow_version"] == "1.0.0" assert params["platform"] == "python_package" assert params["os"] == "linux" assert "timestamp" in params @pytest.mark.asyncio async def test_send_telemetry_data_respects_do_not_track(self): """Test that do_not_track setting prevents telemetry.""" # Create service with do_not_track enabled telemetry_service = TelemetryService.__new__(TelemetryService) telemetry_service.base_url = "https://mock-telemetry.example.com" telemetry_service.do_not_track = True telemetry_service.client_type = "oss" telemetry_service.common_telemetry_fields = { "langflow_version": "1.0.0", "platform": "python_package", "os": "linux", } # Mock HTTP client mock_client = AsyncMock() telemetry_service.client = mock_client payload = ExceptionPayload( exception_type="ValueError", exception_message="Test error", exception_context="handler", stack_trace_hash="abc123", ) # Send telemetry - should be blocked await telemetry_service.send_telemetry_data(payload, "exception") # Verify no HTTP call was made mock_client.get.assert_not_called() def test_stack_trace_hash_consistency(self): """Test that same exceptions produce same hash.""" def create_test_exception(): try: msg = "Consistent test message" raise ValueError(msg) except ValueError as e: return e exc1 = create_test_exception() exc2 = create_test_exception() # Generate hashes the same way as log_exception def get_hash(exc): stack_trace = traceback.format_exception(type(exc), exc, exc.__traceback__) stack_trace_str = "".join(stack_trace) return hashlib.sha256(stack_trace_str.encode()).hexdigest()[:16] hash1 = get_hash(exc1) hash2 = get_hash(exc2) # Hashes should be the same for same exception type and location assert hash1 == hash2 @pytest.mark.asyncio async def test_query_params_url_length_limit(self): """Test that query parameters don't exceed URL length limits.""" telemetry_service = TelemetryService.__new__(TelemetryService) telemetry_service.base_url = "https://mock-telemetry.example.com" telemetry_service.do_not_track = False telemetry_service.client_type = "oss" telemetry_service.common_telemetry_fields = { "langflow_version": "1.0.0", "platform": "python_package", "os": "linux", } # Create payload with very long message long_message = "A" * 2000 # Very long message payload = ExceptionPayload( exception_type="ValueError", exception_message=long_message, exception_context="handler", stack_trace_hash="abc123", ) mock_client = AsyncMock() telemetry_service.client = mock_client await telemetry_service.send_telemetry_data(payload, "exception") # Verify HTTP call was made mock_client.get.assert_called_once() call_args = mock_client.get.call_args # Check that URL doesn't exceed reasonable length (typically 2048 chars) full_url = call_args[0][0] assert len(full_url) < 2048, f"URL too long: {len(full_url)} characters" @pytest.mark.asyncio async def test_query_params_special_characters(self): """Test that special characters in query parameters are properly encoded.""" telemetry_service = TelemetryService.__new__(TelemetryService) telemetry_service.base_url = "https://mock-telemetry.example.com" telemetry_service.do_not_track = False telemetry_service.client_type = "oss" telemetry_service.common_telemetry_fields = { "langflow_version": "1.0.0", "platform": "python_package", "os": "linux", } # Create payload with special characters special_message = "Error with special chars: &?=#@!$%^&*()" payload = ExceptionPayload( exception_type="ValueError", exception_message=special_message, exception_context="handler", stack_trace_hash="abc123", ) mock_client = AsyncMock() telemetry_service.client = mock_client await telemetry_service.send_telemetry_data(payload, "exception") # Verify HTTP call was made mock_client.get.assert_called_once() call_args = mock_client.get.call_args # Check that special characters are properly encoded full_url = call_args[0][0] assert "&" not in full_url or "%26" in full_url, "Ampersand not properly encoded" assert "?" not in full_url or "%3F" in full_url, "Question mark not properly encoded" assert "=" not in full_url or "%3D" in full_url, "Equals sign not properly encoded" @pytest.mark.asyncio async def test_query_params_sensitive_data_exposure(self): """Test that sensitive data is not exposed in query parameters.""" telemetry_service = TelemetryService.__new__(TelemetryService) telemetry_service.base_url = "https://mock-telemetry.example.com" telemetry_service.do_not_track = False telemetry_service.client_type = "oss" telemetry_service.common_telemetry_fields = { "langflow_version": "1.0.0", "platform": "python_package", "os": "linux", } # Create payload with potentially sensitive data sensitive_message = "Password: secret123, API Key: sk-abc123, Token: xyz789" payload = ExceptionPayload( exception_type="ValueError", exception_message=sensitive_message, exception_context="handler", stack_trace_hash="abc123", ) mock_client = AsyncMock() telemetry_service.client = mock_client await telemetry_service.send_telemetry_data(payload, "exception") # Verify HTTP call was made mock_client.get.assert_called_once() call_args = mock_client.get.call_args # Check that sensitive data is not in URL (should be in request body instead) full_url = call_args[0][0] sensitive_patterns = ["secret123", "sk-abc123", "xyz789"] for pattern in sensitive_patterns: assert pattern not in full_url, f"Sensitive data '{pattern}' found in URL" @pytest.mark.asyncio async def test_query_params_unicode_characters(self): """Test that unicode characters in query parameters are handled correctly.""" telemetry_service = TelemetryService.__new__(TelemetryService) telemetry_service.base_url = "https://mock-telemetry.example.com" telemetry_service.do_not_track = False telemetry_service.client_type = "oss" telemetry_service.common_telemetry_fields = { "langflow_version": "1.0.0", "platform": "python_package", "os": "linux", } # Create payload with unicode characters unicode_message = "Error with unicode: 世界, 🚀, émojis" payload = ExceptionPayload( exception_type="ValueError", exception_message=unicode_message, exception_context="handler", stack_trace_hash="abc123", ) mock_client = AsyncMock() telemetry_service.client = mock_client await telemetry_service.send_telemetry_data(payload, "exception") # Verify HTTP call was made mock_client.get.assert_called_once() call_args = mock_client.get.call_args # Check that unicode characters are properly handled full_url = call_args[0][0] # URL should be valid and not cause encoding issues assert len(full_url) > 0, "URL should not be empty" # Should not contain raw unicode characters that could cause issues assert "世界" not in full_url or "%E4%B8%96%E7%95%8C" in full_url
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/test_exception_telemetry.py", "license": "MIT License", "lines": 266, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/tests/unit/interface/initialize/test_loading.py
import os from unittest.mock import AsyncMock, MagicMock, patch import pytest from lfx.interface.initialize.loading import ( update_params_with_load_from_db_fields, update_table_params_with_load_from_db_fields, ) @pytest.mark.asyncio async def test_update_params_fallback_to_env_when_variable_not_found(): """Test that when a variable is not found in database and fallback_to_env_vars is True. It falls back to environment variables. This specifically tests the fix for the bug where 'variable not found.' error would always raise, even with fallback enabled. """ # Set up environment variable os.environ["TEST_API_KEY"] = "test-secret-key-123" # Create mock custom component custom_component = MagicMock() # Use "variable not found." error to specifically test the fix # Previously this would always raise, even with fallback_to_env_vars=True custom_component.get_variable = AsyncMock(side_effect=ValueError("TEST_API_KEY variable not found.")) # Set up params with a field that should load from db params = {"api_key": "TEST_API_KEY"} load_from_db_fields = ["api_key"] # Call the function with fallback enabled with patch("lfx.interface.initialize.loading.session_scope") as mock_session_scope: mock_session_scope.return_value.__aenter__.return_value = MagicMock() result = await update_params_with_load_from_db_fields( custom_component, params, load_from_db_fields, fallback_to_env_vars=True ) # Should have fallen back to environment variable assert result["api_key"] == "test-secret-key-123" # Clean up del os.environ["TEST_API_KEY"] @pytest.mark.asyncio async def test_update_params_raises_when_variable_not_found_and_no_fallback(): """Test that when a variable is not found and fallback_to_env_vars is False. It raises the error. """ # Create mock custom component custom_component = MagicMock() custom_component.get_variable = AsyncMock(side_effect=ValueError("TEST_API_KEY variable not found.")) # Set up params params = {"api_key": "TEST_API_KEY"} load_from_db_fields = ["api_key"] # Call the function with fallback disabled with patch("lfx.interface.initialize.loading.session_scope") as mock_session_scope: mock_session_scope.return_value.__aenter__.return_value = MagicMock() with pytest.raises(ValueError, match="TEST_API_KEY variable not found"): await update_params_with_load_from_db_fields( custom_component, params, load_from_db_fields, fallback_to_env_vars=False ) @pytest.mark.asyncio async def test_update_params_uses_database_variable_when_found(): """Test that when a variable is found in database, it uses that value. It doesn't check environment variables. """ # Set up environment variable (should not be used) os.environ["TEST_API_KEY"] = "env-value" # Create mock custom component custom_component = MagicMock() custom_component.get_variable = AsyncMock(return_value="db-value") # Set up params params = {"api_key": "TEST_API_KEY"} load_from_db_fields = ["api_key"] # Call the function with patch("lfx.interface.initialize.loading.session_scope") as mock_session_scope: mock_session_scope.return_value.__aenter__.return_value = MagicMock() result = await update_params_with_load_from_db_fields( custom_component, params, load_from_db_fields, fallback_to_env_vars=True ) # Should use database value, not environment value assert result["api_key"] == "db-value" # Clean up del os.environ["TEST_API_KEY"] @pytest.mark.asyncio async def test_update_params_sets_none_when_no_env_var_and_fallback_enabled(): """Test that when variable not found in db and env var doesn't exist. The field is set to None. """ # Make sure env var doesn't exist if "NONEXISTENT_KEY" in os.environ: del os.environ["NONEXISTENT_KEY"] # Create mock custom component custom_component = MagicMock() # Change this error message to avoid triggering re-raise custom_component.get_variable = AsyncMock(side_effect=ValueError("Database connection failed")) # Set up params params = {"api_key": "NONEXISTENT_KEY"} load_from_db_fields = ["api_key"] # Call the function with fallback enabled with patch("lfx.interface.initialize.loading.session_scope") as mock_session_scope: mock_session_scope.return_value.__aenter__.return_value = MagicMock() result = await update_params_with_load_from_db_fields( custom_component, params, load_from_db_fields, fallback_to_env_vars=True ) # Should be set to None assert result["api_key"] is None @pytest.mark.asyncio async def test_update_params_raises_on_user_id_not_set(): """Test that 'User id is not set' error is always raised regardless of fallback setting.""" # Create mock custom component custom_component = MagicMock() custom_component.get_variable = AsyncMock(side_effect=ValueError("User id is not set")) # Set up params params = {"api_key": "SOME_KEY"} load_from_db_fields = ["api_key"] # Should raise with fallback enabled with patch("lfx.interface.initialize.loading.session_scope") as mock_session_scope: mock_session_scope.return_value.__aenter__.return_value = MagicMock() with pytest.raises(ValueError, match="User id is not set"): await update_params_with_load_from_db_fields( custom_component, params, load_from_db_fields, fallback_to_env_vars=True ) # Should also raise with fallback disabled with patch("lfx.interface.initialize.loading.session_scope") as mock_session_scope: mock_session_scope.return_value.__aenter__.return_value = MagicMock() with pytest.raises(ValueError, match="User id is not set"): await update_params_with_load_from_db_fields( custom_component, params, load_from_db_fields, fallback_to_env_vars=False ) @pytest.mark.asyncio async def test_update_params_skips_empty_fields(): """Test that empty or None fields in params are skipped.""" # Create mock custom component custom_component = MagicMock() custom_component.get_variable = AsyncMock(return_value="some-value") # Set up params with empty and None values params = {"api_key": "", "another_key": None, "valid_key": "VALID_KEY"} load_from_db_fields = ["api_key", "another_key", "valid_key"] # Call the function with patch("lfx.interface.initialize.loading.session_scope") as mock_session_scope: mock_session = MagicMock() mock_session_scope.return_value.__aenter__.return_value = mock_session result = await update_params_with_load_from_db_fields( custom_component, params, load_from_db_fields, fallback_to_env_vars=True ) # Only valid_key should have been processed assert result["api_key"] == "" assert result["another_key"] is None assert result["valid_key"] == "some-value" # get_variable should only be called once for valid_key # Use ANY to match any session object instead of the specific mock from unittest.mock import ANY custom_component.get_variable.assert_called_once_with(name="VALID_KEY", field="valid_key", session=ANY) @pytest.mark.asyncio async def test_update_params_handles_multiple_fields(): """Test that multiple fields are processed correctly with mixed results.""" # Set up environment variables os.environ["ENV_KEY"] = "env-value" # Create mock custom component custom_component = MagicMock() # Set up different responses for different fields async def mock_get_variable(name, **_kwargs): if name == "DB_KEY": return "db-value" # Use error messages that won't trigger the re-raise condition if name == "ENV_KEY": error_msg = "Database connection failed" # This won't trigger re-raise raise ValueError(error_msg) error_msg = "Database unavailable" # This won't trigger re-raise raise ValueError(error_msg) custom_component.get_variable = AsyncMock(side_effect=mock_get_variable) # Set up params params = {"field1": "DB_KEY", "field2": "ENV_KEY", "field3": "MISSING_KEY"} load_from_db_fields = ["field1", "field2", "field3"] # Call the function with proper mocking - NOTICE THE CORRECT PATCH PATH with ( patch("lfx.interface.initialize.loading.session_scope") as mock_session_scope, patch("lfx.services.deps.get_settings_service") as mock_get_settings, ): # Create a proper mock session that won't be detected as NoopSession mock_session = MagicMock() mock_session.__aenter__ = AsyncMock(return_value=mock_session) mock_session.__aexit__ = AsyncMock(return_value=None) mock_session_scope.return_value = mock_session # Mock settings service to ensure it doesn't use noop database mock_settings_service = MagicMock() mock_settings_service.settings.use_noop_database = False mock_get_settings.return_value = mock_settings_service result = await update_params_with_load_from_db_fields( custom_component, params, load_from_db_fields, fallback_to_env_vars=True ) # Check results assert result["field1"] == "db-value" # From database assert result["field2"] == "env-value" # From environment (fallback) assert result["field3"] is None # Not found anywhere # Clean up del os.environ["ENV_KEY"] # ===================================================================================== # TABLE LOAD_FROM_DB TESTS # ===================================================================================== @pytest.mark.asyncio async def test_update_table_params_with_load_from_db_fields_basic(): """Test basic table load_from_db functionality.""" # Create mock custom component custom_component = MagicMock() # Mock database values async def mock_get_variable(name, **_kwargs): mock_values = { "ADMIN_USER": "actual_admin_user", "ADMIN_EMAIL": "admin@company.com", } if name in mock_values: return mock_values[name] msg = f"{name} variable not found." raise ValueError(msg) custom_component.get_variable = AsyncMock(side_effect=mock_get_variable) # Set up table params params = { "table_data": [ {"username": "ADMIN_USER", "email": "ADMIN_EMAIL", "role": "admin"}, {"username": "static_user", "email": "static@example.com", "role": "user"}, ], "table_data_load_from_db_columns": ["username", "email"], } # Call the function with patch("lfx.interface.initialize.loading.session_scope") as mock_session_scope: mock_session_scope.return_value.__aenter__.return_value = MagicMock() result = await update_table_params_with_load_from_db_fields( custom_component, params, "table_data", fallback_to_env_vars=False ) # Check results table_data = result["table_data"] assert len(table_data) == 2 # First row should have resolved values assert table_data[0]["username"] == "actual_admin_user" assert table_data[0]["email"] == "admin@company.com" assert table_data[0]["role"] == "admin" # unchanged # Second row should have None for variables not found assert table_data[1]["username"] is None # static_user not in mock DB assert table_data[1]["email"] is None # static@example.com not in mock DB assert table_data[1]["role"] == "user" # unchanged # Metadata should be removed assert "table_data_load_from_db_columns" not in result @pytest.mark.asyncio async def test_update_table_params_with_fallback_to_env(): """Test table load_from_db with environment variable fallback.""" # Set up environment variables os.environ["DB_USERNAME"] = "env_username" os.environ["DB_EMAIL"] = "env@example.com" # Create mock custom component custom_component = MagicMock() custom_component.get_variable = AsyncMock(side_effect=ValueError("variable not found.")) # Set up table params params = { "table_data": [ {"username": "DB_USERNAME", "email": "DB_EMAIL", "active": True}, ], "table_data_load_from_db_columns": ["username", "email"], } # Call the function with fallback enabled with patch("lfx.interface.initialize.loading.session_scope") as mock_session_scope: mock_session_scope.return_value.__aenter__.return_value = MagicMock() result = await update_table_params_with_load_from_db_fields( custom_component, params, "table_data", fallback_to_env_vars=True ) # Check results - should use environment variables table_data = result["table_data"] assert table_data[0]["username"] == "env_username" assert table_data[0]["email"] == "env@example.com" assert table_data[0]["active"] is True # unchanged # Clean up del os.environ["DB_USERNAME"] del os.environ["DB_EMAIL"] @pytest.mark.asyncio async def test_update_table_params_mixed_db_and_env(): """Test table with some values from DB and some from environment.""" # Set up environment variables os.environ["ENV_KEY"] = "from_environment" # Create mock custom component custom_component = MagicMock() async def mock_get_variable(name, **_kwargs): if name == "DB_KEY": return "from_database" msg = f"{name} variable not found." raise ValueError(msg) custom_component.get_variable = AsyncMock(side_effect=mock_get_variable) # Set up table params params = { "table_data": [ {"field1": "DB_KEY", "field2": "ENV_KEY", "field3": "static_value"}, ], "table_data_load_from_db_columns": ["field1", "field2"], } # Call the function with fallback enabled with patch("lfx.interface.initialize.loading.session_scope") as mock_session_scope: mock_session_scope.return_value.__aenter__.return_value = MagicMock() result = await update_table_params_with_load_from_db_fields( custom_component, params, "table_data", fallback_to_env_vars=True ) # Check results table_data = result["table_data"] assert table_data[0]["field1"] == "from_database" # From DB assert table_data[0]["field2"] == "from_environment" # From env fallback assert table_data[0]["field3"] == "static_value" # Not in load_from_db_columns # Clean up del os.environ["ENV_KEY"] @pytest.mark.asyncio async def test_update_table_params_empty_table(): """Test table load_from_db with empty table data.""" custom_component = MagicMock() params = { "table_data": [], "table_data_load_from_db_columns": ["username", "email"], } result = await update_table_params_with_load_from_db_fields( custom_component, params, "table_data", fallback_to_env_vars=False ) # Should return empty table and remove metadata assert result["table_data"] == [] assert "table_data_load_from_db_columns" not in result @pytest.mark.asyncio async def test_update_table_params_no_load_from_db_columns(): """Test table with no load_from_db columns.""" custom_component = MagicMock() params = { "table_data": [{"field1": "value1", "field2": "value2"}], "table_data_load_from_db_columns": [], } result = await update_table_params_with_load_from_db_fields( custom_component, params, "table_data", fallback_to_env_vars=False ) # Should return unchanged table and remove metadata assert result["table_data"] == [{"field1": "value1", "field2": "value2"}] assert "table_data_load_from_db_columns" not in result @pytest.mark.asyncio async def test_update_table_params_non_dict_rows(): """Test table with non-dictionary rows (should be left unchanged).""" custom_component = MagicMock() custom_component.get_variable = AsyncMock(return_value="resolved_value") params = { "table_data": [ {"username": "DB_USER"}, # dict row "string_row", # non-dict row 123, # non-dict row ], "table_data_load_from_db_columns": ["username"], } with patch("lfx.interface.initialize.loading.session_scope") as mock_session_scope: mock_session_scope.return_value.__aenter__.return_value = MagicMock() result = await update_table_params_with_load_from_db_fields( custom_component, params, "table_data", fallback_to_env_vars=False ) # Check results table_data = result["table_data"] assert len(table_data) == 3 assert table_data[0]["username"] == "resolved_value" # dict row processed assert table_data[1] == "string_row" # non-dict row unchanged assert table_data[2] == 123 # non-dict row unchanged @pytest.mark.asyncio async def test_update_params_with_table_fields(): """Test the main update_params function with table: prefix fields.""" # Set up environment variable os.environ["TABLE_VAR"] = "table_env_value" # Create mock custom component custom_component = MagicMock() async def mock_get_variable(name, **_kwargs): if name == "REGULAR_VAR": return "regular_db_value" if name == "TABLE_VAR": return "table_db_value" msg = f"{name} variable not found." raise ValueError(msg) custom_component.get_variable = AsyncMock(side_effect=mock_get_variable) # Set up params with both regular and table fields params = { "regular_field": "REGULAR_VAR", "table_data": [ {"username": "TABLE_VAR", "role": "admin"}, ], "table_data_load_from_db_columns": ["username"], } load_from_db_fields = ["regular_field", "table:table_data"] # Call the main function (lfx version with table support) with patch("lfx.interface.initialize.loading.session_scope") as mock_session_scope: mock_session_scope.return_value.__aenter__.return_value = MagicMock() result = await update_params_with_load_from_db_fields( custom_component, params, load_from_db_fields, fallback_to_env_vars=False ) # Check results assert result["regular_field"] == "regular_db_value" # Regular field from DB table_data = result["table_data"] assert table_data[0]["username"] == "table_db_value" # Table field from DB assert table_data[0]["role"] == "admin" # Unchanged # Metadata should be removed assert "table_data_load_from_db_columns" not in result # Clean up del os.environ["TABLE_VAR"] @pytest.mark.asyncio async def test_update_table_params_handles_user_id_not_set_error(): """Test that 'User id is not set' error is properly raised for table fields.""" custom_component = MagicMock() custom_component.get_variable = AsyncMock(side_effect=ValueError("User id is not set")) params = { "table_data": [{"username": "SOME_VAR"}], "table_data_load_from_db_columns": ["username"], } with patch("lfx.interface.initialize.loading.session_scope") as mock_session_scope: mock_session_scope.return_value.__aenter__.return_value = MagicMock() with pytest.raises(ValueError, match="User id is not set"): await update_table_params_with_load_from_db_fields( custom_component, params, "table_data", fallback_to_env_vars=True )
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/interface/initialize/test_loading.py", "license": "MIT License", "lines": 403, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/base/langflow/api/v1/knowledge_bases.py
import asyncio import gc import json import shutil import uuid from datetime import datetime, timezone from http import HTTPStatus from pathlib import Path from typing import Annotated, Any import chromadb.errors from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, UploadFile from langchain_chroma import Chroma from langchain_text_splitters import RecursiveCharacterTextSplitter from lfx.log import logger from langflow.api.utils import CurrentActiveUser from langflow.api.utils.kb_helpers import KBAnalysisHelper, KBIngestionHelper, KBStorageHelper from langflow.api.v1.schemas import TaskResponse from langflow.schema.knowledge_base import ( BulkDeleteRequest, ChunkInfo, CreateKnowledgeBaseRequest, KnowledgeBaseInfo, PaginatedChunkResponse, ) from langflow.services.database.models.jobs.model import JobStatus, JobType from langflow.services.deps import get_job_service, get_settings_service, get_task_service from langflow.services.jobs.service import JobService from langflow.services.task.service import TaskService from langflow.utils.kb_constants import ( CHUNK_PREVIEW_MULTIPLIER, MIN_KB_NAME_LENGTH, ) router = APIRouter(tags=["Knowledge Bases"], prefix="/knowledge_bases", include_in_schema=False) def _resolve_kb_path(kb_name: str, current_user: CurrentActiveUser) -> Path: """Resolve and validate KB path, raising 404 if not found.""" kb_root_path = KBStorageHelper.get_root_path() if not kb_root_path: raise HTTPException(status_code=500, detail="Knowledge base root path not configured") kb_user = current_user.username kb_path = kb_root_path / kb_user / kb_name if not kb_path.exists() or not kb_path.is_dir(): raise HTTPException(status_code=404, detail=f"Knowledge base '{kb_name}' not found") return kb_path @router.post("", status_code=HTTPStatus.CREATED) @router.post("/", status_code=HTTPStatus.CREATED) async def create_knowledge_base( request: CreateKnowledgeBaseRequest, current_user: CurrentActiveUser, ) -> KnowledgeBaseInfo: """Create a new knowledge base with embedding configuration.""" try: kb_root_path = KBStorageHelper.get_root_path() kb_user = current_user.username kb_name = request.name.strip().replace(" ", "_") kb_path = kb_root_path / kb_user / kb_name # Validate KB name if not kb_name or len(kb_name) < MIN_KB_NAME_LENGTH: raise HTTPException(status_code=400, detail="Knowledge base name must be at least 3 characters") # Check if KB already exists if kb_path.exists(): raise HTTPException(status_code=409, detail=f"Knowledge base '{kb_name}' already exists") # Create KB directory kb_path.mkdir(parents=True, exist_ok=True) kb_id = uuid.uuid4() # Initialize Chroma storage and collection immediately # This ensures files exist for read operations and avoids 'readonly' errors later try: client = KBStorageHelper.get_fresh_chroma_client(kb_path) client.create_collection(name=kb_name) # Explicitly delete reference to help release handle client = None gc.collect() except (OSError, ValueError, chromadb.errors.ChromaError) as e: logger.warning("Initial Chroma setup for %s failed: %s", kb_name, e) # Serialize column_config for persistence column_config_dicts = None if request.column_config: column_config_dicts = [item.model_dump() for item in request.column_config] # Save full embedding metadata to prevent immediate backfill embedding_metadata = { "id": str(kb_id), "embedding_provider": request.embedding_provider, "embedding_model": request.embedding_model, "created_at": datetime.now(timezone.utc).isoformat(), "chunks": 0, "words": 0, "characters": 0, "avg_chunk_size": 0.0, "size": 0, "column_config": column_config_dicts, } metadata_path = kb_path / "embedding_metadata.json" metadata_path.write_text(json.dumps(embedding_metadata, indent=2)) # Write schema.json for text-metric helpers (get_text_columns) if column_config_dicts: schema_data = [{**col, "data_type": "string"} for col in column_config_dicts] schema_path = kb_path / "schema.json" schema_path.write_text(json.dumps(schema_data, indent=2)) return KnowledgeBaseInfo( id=str(kb_id), dir_name=kb_name, name=kb_name.replace("_", " "), embedding_provider=request.embedding_provider, embedding_model=request.embedding_model, size=0, words=0, characters=0, chunks=0, avg_chunk_size=0.0, column_config=column_config_dicts, ) except HTTPException: raise except Exception as e: # Clean up if something went wrong if kb_path.exists(): shutil.rmtree(kb_path) await logger.aerror("Error creating knowledge base: %s", e) raise HTTPException(status_code=500, detail="Internal error creating knowledge base") from e @router.post("/preview-chunks", status_code=HTTPStatus.OK) async def preview_chunks( _current_user: CurrentActiveUser, files: Annotated[list[UploadFile], File(description="Files to preview chunking for")], chunk_size: Annotated[int, Form()] = 1000, chunk_overlap: Annotated[int, Form()] = 200, separator: Annotated[str, Form()] = "\n", max_chunks: Annotated[int, Form()] = 5, ) -> dict[str, object]: """Preview how files will be chunked without storing anything. Uses the same RecursiveCharacterTextSplitter as the ingest endpoint so the preview accurately reflects what will be stored. """ try: if not files: raise HTTPException(status_code=400, detail="No files provided") # Build separators list: user separator first, then defaults separators = None if separator: # Unescape common escape sequences actual_separator = separator.replace("\\n", "\n").replace("\\t", "\t") separators = [actual_separator, "\n\n", "\n", " ", ""] text_splitter = RecursiveCharacterTextSplitter( chunk_size=chunk_size, chunk_overlap=chunk_overlap, separators=separators, ) file_previews: list[dict[str, Any]] = [] for uploaded_file in files: try: file_content = await uploaded_file.read() file_name = uploaded_file.filename or "unknown" text_content = file_content.decode("utf-8", errors="ignore") if not text_content.strip(): file_previews.append( { "file_name": file_name, "total_chunks": 0, "preview_chunks": [], } ) continue # Only process enough text for the requested preview chunks # to avoid splitting the entire file (which is slow for large files) preview_text_limit = max_chunks * chunk_size * CHUNK_PREVIEW_MULTIPLIER preview_text = text_content[:preview_text_limit] chunks = text_splitter.split_text(preview_text) # Estimate total chunks from full text length effective_step = max(chunk_size - chunk_overlap, 1) estimated_total = max( len(chunks), int((len(text_content) - chunk_overlap) / effective_step), ) # Track character positions for metadata preview_chunks = [] position = 0 for i, chunk in enumerate(chunks[:max_chunks]): # Find the actual position of this chunk in the original text chunk_start = text_content.find(chunk, position) if chunk_start == -1: chunk_start = position chunk_end = chunk_start + len(chunk) preview_chunks.append( { "content": chunk, "index": i, "char_count": len(chunk), "start": chunk_start, "end": chunk_end, } ) position = chunk_start + 1 file_previews.append( { "file_name": file_name, "total_chunks": estimated_total, "preview_chunks": preview_chunks, } ) except (OSError, ValueError, TypeError) as file_error: logger.warning("Error previewing file %s: %s", uploaded_file.filename, file_error) file_previews.append( { "file_name": uploaded_file.filename or "unknown", "total_chunks": 0, "preview_chunks": [], } ) except HTTPException: raise except Exception as e: await logger.aerror("Error previewing chunks: %s", e) raise HTTPException(status_code=500, detail="Error previewing chunks.") from e else: return {"files": file_previews} @router.post("/{kb_name}/ingest", status_code=HTTPStatus.OK) async def ingest_files_to_knowledge_base( kb_name: str, current_user: CurrentActiveUser, files: Annotated[list[UploadFile], File(description="Files to ingest into the knowledge base")], source_name: Annotated[str, Form()] = "", chunk_size: Annotated[int, Form()] = 1000, chunk_overlap: Annotated[int, Form()] = 200, separator: Annotated[str, Form()] = "", column_config: Annotated[str, Form()] = "", ) -> dict[str, object] | TaskResponse: """Upload and ingest files directly into a knowledge base. This endpoint: 1. Accepts file uploads 2. Extracts text and chunks the content 3. Creates embeddings using the KB's configured embedding model 4. Stores the vectors in the knowledge base """ try: settings = get_settings_service().settings max_file_size_upload = settings.max_file_size_upload files_data = [] for uploaded_file in files: file_size = uploaded_file.size if file_size > max_file_size_upload * 1024 * 1024: raise HTTPException( status_code=413, detail=f"File {uploaded_file.filename} exceeds the maximum upload size of {max_file_size_upload}MB", ) content = await uploaded_file.read() files_data.append((uploaded_file.filename or "unknown", content)) kb_path = _resolve_kb_path(kb_name, current_user) # Parse and persist column_config from FormData if provided if column_config: try: column_config_parsed = json.loads(column_config) if isinstance(column_config_parsed, list): # Update embedding_metadata.json cc_metadata_path = kb_path / "embedding_metadata.json" if cc_metadata_path.exists(): existing_meta = json.loads(cc_metadata_path.read_text()) existing_meta["column_config"] = column_config_parsed cc_metadata_path.write_text(json.dumps(existing_meta, indent=2)) # Write schema.json for text-metric helpers schema_data = [{**col, "data_type": "string"} for col in column_config_parsed] schema_path = kb_path / "schema.json" schema_path.write_text(json.dumps(schema_data, indent=2)) except (json.JSONDecodeError, TypeError): await logger.awarning("Malformed column_config received, using existing schema") # Read embedding metadata (Pass fast=False to ensure legacy KBs are migrated/detected) metadata = KBAnalysisHelper.get_metadata(kb_path, fast=False) if not metadata: raise HTTPException( status_code=400, detail="Knowledge base missing embedding configuration. Please create a new KB or reconfigure it.", ) embedding_provider = metadata.get("embedding_provider") embedding_model = metadata.get("embedding_model") # Handle backward compatibility: generate asset_id if not present asset_id_str = metadata.get("id") if not asset_id_str: # Generate new UUID for older KBs without asset_id asset_id = uuid.uuid4() # Persist the new ID to metadata metadata_path = kb_path / "embedding_metadata.json" if metadata_path.exists(): try: embedding_metadata = json.loads(metadata_path.read_text()) embedding_metadata["id"] = str(asset_id) metadata_path.write_text(json.dumps(embedding_metadata, indent=2)) except (OSError, json.JSONDecodeError): await logger.awarning("Could not update metadata with asset_id") else: asset_id = uuid.UUID(asset_id_str) if not embedding_provider or not embedding_model: raise HTTPException(status_code=400, detail="Invalid embedding configuration") # Get services and create job before async/sync split job_service = get_job_service() job_id = uuid.uuid4() # Create job record in database for both async and sync paths await job_service.create_job( job_id=job_id, flow_id=job_id, job_type=JobType.INGESTION, asset_id=asset_id, asset_type="knowledge_base" ) # Always use async path: fire and forget the ingestion logic wrapped in status updates task_service = get_task_service() await task_service.fire_and_forget_task( job_service.execute_with_status, job_id=job_id, run_coro_func=KBIngestionHelper.perform_ingestion, kb_name=kb_name, kb_path=kb_path, files_data=files_data, chunk_size=chunk_size, chunk_overlap=chunk_overlap, separator=separator, source_name=source_name, current_user=current_user, embedding_provider=embedding_provider, embedding_model=embedding_model, task_job_id=job_id, job_service=job_service, ) return TaskResponse(id=str(job_id), href=f"/task/{job_id}") except HTTPException: raise except Exception as e: await logger.aerror("Error ingesting files to knowledge base: %s", e) raise HTTPException(status_code=500, detail="Error ingesting files to knowledge base.") from e @router.get("", status_code=HTTPStatus.OK) @router.get("/", status_code=HTTPStatus.OK) async def list_knowledge_bases( current_user: CurrentActiveUser, job_service: Annotated[JobService, Depends(get_job_service)], ) -> list[KnowledgeBaseInfo]: """List all available knowledge bases.""" try: kb_root_path = KBStorageHelper.get_root_path() kb_path = kb_root_path / current_user.username if not kb_path.exists(): return [] knowledge_bases = [] kb_ids_to_fetch = [] # Collect KB IDs for batch fetching # First pass: Load all KBs into memory for kb_dir in kb_path.iterdir(): if not kb_dir.is_dir() or kb_dir.name.startswith("."): continue try: # Use deep update (fast=False) to ensure legacy KBs are migrated on first view metadata = KBAnalysisHelper.get_metadata(kb_dir, fast=False) # Extract KB ID from metadata (stored as string, convert to UUID) kb_id_str = metadata.get("id") if kb_id_str: try: kb_id_uuid = uuid.UUID(kb_id_str) kb_ids_to_fetch.append(kb_id_uuid) except (ValueError, AttributeError): # If ID is invalid, skip job status lookup for this KB kb_id_str = None chunks_count = metadata["chunks"] status = "ready" if chunks_count > 0 else "empty" failure_reason = None kb_info = KnowledgeBaseInfo( id=kb_id_str or kb_dir.name, # Fallback to directory name if no ID dir_name=kb_dir.name, name=kb_dir.name.replace("_", " "), embedding_provider=metadata["embedding_provider"], embedding_model=metadata["embedding_model"], size=metadata["size"], words=metadata["words"], characters=metadata["characters"], chunks=chunks_count, avg_chunk_size=metadata["avg_chunk_size"], chunk_size=metadata.get("chunk_size"), chunk_overlap=metadata.get("chunk_overlap"), separator=metadata.get("separator"), status=status, failure_reason=failure_reason, last_job_id=None, source_types=metadata.get("source_types", []), column_config=metadata.get("column_config"), ) knowledge_bases.append(kb_info) except OSError as _: # Log the exception and skip directories that can't be read await logger.aexception("Error reading knowledge base directory '%s'", kb_dir) continue # Second pass: Batch fetch all job statuses in a single query if kb_ids_to_fetch: latest_jobs = await job_service.get_latest_jobs_by_asset_ids(kb_ids_to_fetch) # Map job statuses back to knowledge bases # Normalize to frontend-expected values: ready, ingesting, failed, empty job_status_map = { "queued": "ingesting", "in_progress": "ingesting", "failed": "failed", "cancelled": "failed", "timed_out": "failed", } for kb_info in knowledge_bases: try: kb_uuid = uuid.UUID(kb_info.id) if kb_uuid in latest_jobs: job = latest_jobs[kb_uuid] raw_status = job.status.value if hasattr(job.status, "value") else str(job.status) mapped = job_status_map.get(raw_status) if mapped: kb_info.status = mapped # For "completed", keep the file-marker / chunk-count status already set kb_info.last_job_id = str(job.job_id) except (ValueError, AttributeError): # If KB ID is not a valid UUID, skip job status update pass except Exception as e: await logger.aerror("Error listing knowledge bases: %s", e) raise HTTPException(status_code=500, detail="Error listing knowledge bases.") from e else: return knowledge_bases @router.get("/{kb_name}", status_code=HTTPStatus.OK) async def get_knowledge_base(kb_name: str, current_user: CurrentActiveUser) -> KnowledgeBaseInfo: """Get detailed information about a specific knowledge base.""" try: kb_path = _resolve_kb_path(kb_name, current_user) # Get size of the directory size = KBStorageHelper.get_directory_size(kb_path) # Get metadata from KB files metadata = KBAnalysisHelper.get_metadata(kb_path) chunks_count = metadata["chunks"] status = "ready" if chunks_count > 0 else "empty" return KnowledgeBaseInfo( id=kb_name, dir_name=kb_name, name=kb_name.replace("_", " "), embedding_provider=metadata["embedding_provider"], embedding_model=metadata["embedding_model"], size=size, words=metadata["words"], characters=metadata["characters"], chunks=chunks_count, avg_chunk_size=metadata["avg_chunk_size"], chunk_size=metadata.get("chunk_size"), chunk_overlap=metadata.get("chunk_overlap"), separator=metadata.get("separator"), status=status, source_types=metadata.get("source_types", []), column_config=metadata.get("column_config"), ) except HTTPException: raise except Exception as e: await logger.aerror("Error getting knowledge base '%s': %s", kb_name, e) raise HTTPException(status_code=500, detail="Error getting knowledge base.") from e @router.get("/{kb_name}/chunks", status_code=HTTPStatus.OK) async def get_knowledge_base_chunks( kb_name: str, current_user: CurrentActiveUser, page: Annotated[int, Query(ge=1)] = 1, limit: Annotated[int, Query(ge=1, le=100)] = 50, search: Annotated[str, Query(description="Filter chunks whose text contains this substring")] = "", ) -> PaginatedChunkResponse: """Get chunks from a specific knowledge base with pagination.""" try: kb_path = _resolve_kb_path(kb_name, current_user) # Guard: If no physical chroma data exists, return empty response immediately # This prevents 'readonly database' errors when trying to initialize Chroma on an empty directory has_data = any((kb_path / m).exists() for m in ["chroma", "chroma.sqlite3", "index"]) if not has_data: return PaginatedChunkResponse( chunks=[], total=0, page=page, limit=limit, total_pages=0, ) # Create vector store client = KBStorageHelper.get_fresh_chroma_client(kb_path) chroma = Chroma( client=client, collection_name=kb_name, ) # Access the raw collection collection = chroma._collection # noqa: SLF001 search_term = search.strip() if search_term: # When searching, fetch all matching docs then paginate in-memory where_doc = {"$contains": search_term} all_results = collection.get( include=["documents", "metadatas"], where_document=where_doc, ) total_count = len(all_results["ids"]) offset = (page - 1) * limit sliced_ids = all_results["ids"][offset : offset + limit] sliced_docs = all_results["documents"][offset : offset + limit] sliced_metas = all_results["metadatas"][offset : offset + limit] else: # No search - use Chroma's native pagination total_count = collection.count() offset = (page - 1) * limit results = collection.get( include=["documents", "metadatas"], limit=limit, offset=offset, ) sliced_ids = results["ids"] sliced_docs = results["documents"] sliced_metas = results["metadatas"] chunks = [] for doc_id, document, metadata in zip(sliced_ids, sliced_docs, sliced_metas, strict=False): content = document or "" chunks.append( ChunkInfo( id=doc_id, content=content, char_count=len(content), metadata=metadata, ) ) return PaginatedChunkResponse( chunks=chunks, total=total_count, page=page, limit=limit, total_pages=(total_count + limit - 1) // limit if total_count > 0 else 0, ) except HTTPException: raise except Exception as e: await logger.aerror("Error getting chunks for '%s': %s", kb_name, e) raise HTTPException(status_code=500, detail="Error getting chunks.") from e finally: chroma = None gc.collect() @router.delete("/{kb_name}", status_code=HTTPStatus.OK) async def delete_knowledge_base(kb_name: str, current_user: CurrentActiveUser) -> dict[str, str]: """Delete a specific knowledge base.""" try: kb_path = _resolve_kb_path(kb_name, current_user) # Explicitly teardown KB storage to flush Chroma handles before directory deletion KBStorageHelper.teardown_storage(kb_path, kb_name) # Delete the entire knowledge base directory shutil.rmtree(kb_path) except HTTPException: raise except Exception as e: await logger.aerror("Error deleting knowledge base '%s': %s", kb_name, e) raise HTTPException(status_code=500, detail="Error deleting knowledge base.") from e else: return {"message": f"Knowledge base '{kb_name}' deleted successfully"} @router.delete("", status_code=HTTPStatus.OK) @router.delete("/", status_code=HTTPStatus.OK) async def delete_knowledge_bases_bulk(request: BulkDeleteRequest, current_user: CurrentActiveUser) -> dict[str, object]: """Delete multiple knowledge bases.""" try: kb_root_path = KBStorageHelper.get_root_path() kb_user_path = kb_root_path / current_user.username deleted_count = 0 not_found_kbs = [] for kb_name in request.kb_names: kb_path = kb_user_path / kb_name if not kb_path.exists() or not kb_path.is_dir(): not_found_kbs.append(kb_name) continue try: # Explicitly teardown KB storage to flush Chroma handles before directory deletion KBStorageHelper.teardown_storage(kb_path, kb_name) # Delete the entire knowledge base directory shutil.rmtree(kb_path) deleted_count += 1 except (OSError, PermissionError) as e: await logger.aexception("Error deleting knowledge base '%s': %s", kb_name, e) # Continue with other deletions even if one fails if not_found_kbs and deleted_count == 0: raise HTTPException( status_code=404, detail="Knowledge bases not found: {}".format(", ".join(not_found_kbs)) ) result = { "message": f"Successfully deleted {deleted_count} knowledge base(s)", "deleted_count": deleted_count, } if not_found_kbs: result["not_found"] = ", ".join(not_found_kbs) except HTTPException: raise except Exception as e: await logger.aerror("Error deleting knowledge bases: %s", e) raise HTTPException(status_code=500, detail="Error deleting knowledge bases.") from e else: return result @router.post("/{kb_name}/cancel", status_code=HTTPStatus.OK) async def cancel_ingestion( kb_name: str, current_user: CurrentActiveUser, job_service: Annotated[JobService, Depends(get_job_service)], task_service: Annotated[TaskService, Depends(get_task_service)], ) -> dict[str, str]: """Cancel the ongoing ingestion task for a knowledge base.""" try: kb_path = _resolve_kb_path(kb_name, current_user) # Get KB metadata to extract asset_id metadata = KBAnalysisHelper.get_metadata(kb_path, fast=True) asset_id_str = metadata.get("id") if not asset_id_str: raise HTTPException(status_code=400, detail="Knowledge base missing asset ID") try: asset_id = uuid.UUID(asset_id_str) except (ValueError, AttributeError) as e: raise HTTPException(status_code=400, detail="Invalid asset ID") from e # Fetch the latest ingestion job for this KB latest_jobs = await job_service.get_latest_jobs_by_asset_ids([asset_id]) if asset_id not in latest_jobs: raise HTTPException(status_code=404, detail=f"No ingestion job found for the knowledge base {kb_name}") job = latest_jobs[asset_id] job_status = job.status.value if hasattr(job.status, "value") else str(job.status) # Check if job is already completed or failed if job_status in ["completed", "failed", "cancelled", "timed_out"]: raise HTTPException(status_code=400, detail=f"Cannot cancel job with status '{job_status}'") revoked = await task_service.revoke_task(job.job_id) # Update status immediately so background task can see it await job_service.update_job_status(job.job_id, JobStatus.CANCELLED) # Clean up any partially ingested chunks from this job await KBIngestionHelper.cleanup_chroma_chunks_by_job(job.job_id, kb_path, kb_name) if revoked: message = f"Ingestion job for {job.job_id} cancelled successfully." else: message = f"Job {job.job_id} is already cancelled." except asyncio.CancelledError: raise except HTTPException: raise except Exception as e: await logger.aerror("Error cancelling ingestion: %s", e) raise HTTPException(status_code=500, detail="Error cancelling ingestion.") from e else: return {"message": message}
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/base/langflow/api/v1/knowledge_bases.py", "license": "MIT License", "lines": 628, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
langflow-ai/langflow:src/backend/tests/unit/base/data/test_kb_utils.py
import pytest from langflow.base.knowledge_bases.knowledge_base_utils import compute_bm25, compute_tfidf class TestKBUtils: """Test suite for knowledge base utility functions.""" # Test data for TF-IDF and BM25 tests @pytest.fixture def sample_documents(self): """Sample documents for testing.""" return ["the cat sat on the mat", "the dog ran in the park", "cats and dogs are pets", "birds fly in the sky"] @pytest.fixture def query_terms(self): """Sample query terms for testing.""" return ["cat", "dog"] @pytest.fixture def empty_documents(self): """Empty documents for edge case testing.""" return ["", "", ""] @pytest.fixture def single_document(self): """Single document for testing.""" return ["hello world"] def test_compute_tfidf_basic(self, sample_documents, query_terms): """Test basic TF-IDF computation.""" scores = compute_tfidf(sample_documents, query_terms) # Should return a score for each document assert len(scores) == len(sample_documents) # All scores should be floats assert all(isinstance(score, float) for score in scores) # First document contains "cat", should have non-zero score assert scores[0] > 0.0 # Second document contains "dog", should have non-zero score assert scores[1] > 0.0 # Third document contains both "cats" and "dogs", but case-insensitive matching should work # Note: "cats" != "cat" exactly, so this tests the term matching behavior assert scores[2] >= 0.0 # Fourth document contains neither term, should have zero score assert scores[3] == 0.0 def test_compute_tfidf_case_insensitive(self): """Test that TF-IDF computation is case insensitive.""" documents = ["The CAT sat", "the dog RAN", "CATS and DOGS"] query_terms = ["cat", "DOG"] scores = compute_tfidf(documents, query_terms) # First document should match "cat" (case insensitive) assert scores[0] > 0.0 # Second document should match "dog" (case insensitive) assert scores[1] > 0.0 def test_compute_tfidf_empty_documents(self, empty_documents, query_terms): """Test TF-IDF with empty documents.""" scores = compute_tfidf(empty_documents, query_terms) # Should return scores for all documents assert len(scores) == len(empty_documents) # All scores should be zero since documents are empty assert all(score == 0.0 for score in scores) def test_compute_tfidf_empty_query_terms(self, sample_documents): """Test TF-IDF with empty query terms.""" scores = compute_tfidf(sample_documents, []) # Should return scores for all documents assert len(scores) == len(sample_documents) # All scores should be zero since no query terms assert all(score == 0.0 for score in scores) def test_compute_tfidf_single_document(self, single_document): """Test TF-IDF with single document.""" query_terms = ["hello", "world"] scores = compute_tfidf(single_document, query_terms) assert len(scores) == 1 # With only one document, IDF = log(1/1) = 0, so TF-IDF score is always 0 # This is correct mathematical behavior - TF-IDF is designed to discriminate between documents assert scores[0] == 0.0 def test_compute_tfidf_two_documents_positive_scores(self): """Test TF-IDF with two documents to ensure positive scores are possible.""" documents = ["hello world", "goodbye earth"] query_terms = ["hello", "world"] scores = compute_tfidf(documents, query_terms) assert len(scores) == 2 # First document contains both terms, should have positive score assert scores[0] > 0.0 # Second document contains neither term, should have zero score assert scores[1] == 0.0 def test_compute_tfidf_no_documents(self): """Test TF-IDF with no documents.""" scores = compute_tfidf([], ["cat", "dog"]) assert scores == [] def test_compute_tfidf_term_frequency_calculation(self): """Test TF-IDF term frequency calculation.""" # Documents with different term frequencies for the same term documents = ["rare word text", "rare rare word", "other content"] query_terms = ["rare"] scores = compute_tfidf(documents, query_terms) # "rare" appears in documents 0 and 1, but with different frequencies # Document 1 has higher TF (2/3 vs 1/3), so should score higher assert scores[0] > 0.0 # Contains "rare" once assert scores[1] > scores[0] # Contains "rare" twice, should score higher assert scores[2] == 0.0 # Doesn't contain "rare" def test_compute_tfidf_idf_calculation(self): """Test TF-IDF inverse document frequency calculation.""" # "rare" appears in only one document, "common" appears in both documents = ["rare term", "common term", "common word"] query_terms = ["rare", "common"] scores = compute_tfidf(documents, query_terms) # First document should have higher score due to rare term having higher IDF assert scores[0] > scores[1] # rare term gets higher IDF assert scores[0] > scores[2] def test_compute_bm25_basic(self, sample_documents, query_terms): """Test basic BM25 computation.""" scores = compute_bm25(sample_documents, query_terms) # Should return a score for each document assert len(scores) == len(sample_documents) # All scores should be floats assert all(isinstance(score, float) for score in scores) # First document contains "cat", should have non-zero score assert scores[0] > 0.0 # Second document contains "dog", should have non-zero score assert scores[1] > 0.0 # Fourth document contains neither term, should have zero score assert scores[3] == 0.0 def test_compute_bm25_parameters(self, sample_documents, query_terms): """Test BM25 with different k1 and b parameters.""" # Test with default parameters scores_default = compute_bm25(sample_documents, query_terms) # Test with different k1 scores_k1 = compute_bm25(sample_documents, query_terms, k1=2.0) # Test with different b scores_b = compute_bm25(sample_documents, query_terms, b=0.5) # Test with both different scores_both = compute_bm25(sample_documents, query_terms, k1=2.0, b=0.5) # All should return valid scores assert len(scores_default) == len(sample_documents) assert len(scores_k1) == len(sample_documents) assert len(scores_b) == len(sample_documents) assert len(scores_both) == len(sample_documents) # Scores should be different with different parameters assert scores_default != scores_k1 assert scores_default != scores_b def test_compute_bm25_case_insensitive(self): """Test that BM25 computation is case insensitive.""" documents = ["The CAT sat", "the dog RAN", "CATS and DOGS"] query_terms = ["cat", "DOG"] scores = compute_bm25(documents, query_terms) # First document should match "cat" (case insensitive) assert scores[0] > 0.0 # Second document should match "dog" (case insensitive) assert scores[1] > 0.0 def test_compute_bm25_empty_documents(self, empty_documents, query_terms): """Test BM25 with empty documents.""" scores = compute_bm25(empty_documents, query_terms) # Should return scores for all documents assert len(scores) == len(empty_documents) # All scores should be zero since documents are empty assert all(score == 0.0 for score in scores) def test_compute_bm25_empty_query_terms(self, sample_documents): """Test BM25 with empty query terms.""" scores = compute_bm25(sample_documents, []) # Should return scores for all documents assert len(scores) == len(sample_documents) # All scores should be zero since no query terms assert all(score == 0.0 for score in scores) def test_compute_bm25_single_document(self, single_document): """Test BM25 with single document.""" query_terms = ["hello", "world"] scores = compute_bm25(single_document, query_terms) assert len(scores) == 1 # With only one document, IDF = log(1/1) = 0, so BM25 score is always 0 # This is correct mathematical behavior - both TF-IDF and BM25 are designed to discriminate between documents assert scores[0] == 0.0 def test_compute_bm25_two_documents_positive_scores(self): """Test BM25 with two documents to ensure positive scores are possible.""" documents = ["hello world", "goodbye earth"] query_terms = ["hello", "world"] scores = compute_bm25(documents, query_terms) assert len(scores) == 2 # First document contains both terms, should have positive score assert scores[0] > 0.0 # Second document contains neither term, should have zero score assert scores[1] == 0.0 def test_compute_bm25_no_documents(self): """Test BM25 with no documents.""" scores = compute_bm25([], ["cat", "dog"]) assert scores == [] def test_compute_bm25_document_length_normalization(self): """Test BM25 document length normalization.""" # Test with documents where some terms appear in subset of documents documents = [ "cat unique1", # Short document with unique term "cat dog bird mouse elephant tiger lion bear wolf unique2", # Long document with unique term "other content", # Document without query terms ] query_terms = ["unique1", "unique2"] scores = compute_bm25(documents, query_terms) # Documents with unique terms should have positive scores assert scores[0] > 0.0 # Contains "unique1" assert scores[1] > 0.0 # Contains "unique2" assert scores[2] == 0.0 # Contains neither term # Document length normalization affects scores assert len(scores) == 3 def test_compute_bm25_term_frequency_saturation(self): """Test BM25 term frequency saturation behavior.""" # Test with documents where term frequencies can be meaningfully compared documents = [ "rare word text", # TF = 1 for "rare" "rare rare word", # TF = 2 for "rare" "rare rare rare rare rare word", # TF = 5 for "rare" "other content", # No "rare" term ] query_terms = ["rare"] scores = compute_bm25(documents, query_terms) # Documents with the term should have positive scores assert scores[0] > 0.0 # TF=1 assert scores[1] > 0.0 # TF=2 assert scores[2] > 0.0 # TF=5 assert scores[3] == 0.0 # TF=0 # Scores should increase with term frequency, but with diminishing returns assert scores[1] > scores[0] # TF=2 > TF=1 assert scores[2] > scores[1] # TF=5 > TF=2 # Check that increases demonstrate saturation effect increase_1_to_2 = scores[1] - scores[0] increase_2_to_5 = scores[2] - scores[1] assert increase_1_to_2 > 0 assert increase_2_to_5 > 0 def test_compute_bm25_idf_calculation(self): """Test BM25 inverse document frequency calculation.""" # "rare" appears in only one document, "common" appears in multiple documents = ["rare term", "common term", "common word"] query_terms = ["rare", "common"] scores = compute_bm25(documents, query_terms) # First document should have higher score due to rare term having higher IDF assert scores[0] > scores[1] # rare term gets higher IDF assert scores[0] > scores[2] def test_compute_bm25_zero_parameters(self, sample_documents, query_terms): """Test BM25 with edge case parameters.""" # Test with k1=0 (no term frequency scaling) scores_k1_zero = compute_bm25(sample_documents, query_terms, k1=0.0) assert len(scores_k1_zero) == len(sample_documents) # Test with b=0 (no document length normalization) scores_b_zero = compute_bm25(sample_documents, query_terms, b=0.0) assert len(scores_b_zero) == len(sample_documents) # Test with b=1 (full document length normalization) scores_b_one = compute_bm25(sample_documents, query_terms, b=1.0) assert len(scores_b_one) == len(sample_documents) def test_tfidf_vs_bm25_comparison(self, sample_documents, query_terms): """Test that TF-IDF and BM25 produce different but related scores.""" tfidf_scores = compute_tfidf(sample_documents, query_terms) bm25_scores = compute_bm25(sample_documents, query_terms) # Both should return same number of scores assert len(tfidf_scores) == len(bm25_scores) == len(sample_documents) # For documents that match, both should be positive for i in range(len(sample_documents)): if tfidf_scores[i] > 0: assert bm25_scores[i] > 0, f"Document {i} has TF-IDF score but zero BM25 score" if bm25_scores[i] > 0: assert tfidf_scores[i] > 0, f"Document {i} has BM25 score but zero TF-IDF score" def test_compute_tfidf_special_characters(self): """Test TF-IDF with documents containing special characters.""" documents = ["hello, world!", "world... hello?", "no match here"] query_terms = ["hello", "world"] scores = compute_tfidf(documents, query_terms) # Should handle punctuation and still match terms assert len(scores) == 3 # Note: Current implementation does simple split(), so punctuation stays attached # This tests the current behavior - may need updating if tokenization improves def test_compute_bm25_special_characters(self): """Test BM25 with documents containing special characters.""" documents = ["hello, world!", "world... hello?", "no match here"] query_terms = ["hello", "world"] scores = compute_bm25(documents, query_terms) # Should handle punctuation and still match terms assert len(scores) == 3 # Same tokenization behavior as TF-IDF def test_compute_tfidf_whitespace_handling(self): """Test TF-IDF with various whitespace scenarios.""" documents = [ " hello world ", # Extra spaces "\thello\tworld\t", # Tabs "hello\nworld", # Newlines "", # Empty string ] query_terms = ["hello", "world"] scores = compute_tfidf(documents, query_terms) assert len(scores) == 4 # First three should have positive scores (they contain the terms) assert scores[0] > 0.0 assert scores[1] > 0.0 assert scores[2] > 0.0 # Last should be zero (empty document) assert scores[3] == 0.0 def test_compute_bm25_whitespace_handling(self): """Test BM25 with various whitespace scenarios.""" documents = [ " hello world ", # Extra spaces "\thello\tworld\t", # Tabs "hello\nworld", # Newlines "", # Empty string ] query_terms = ["hello", "world"] scores = compute_bm25(documents, query_terms) assert len(scores) == 4 # First three should have positive scores (they contain the terms) assert scores[0] > 0.0 assert scores[1] > 0.0 assert scores[2] > 0.0 # Last should be zero (empty document) assert scores[3] == 0.0 def test_compute_tfidf_mathematical_properties(self): """Test mathematical properties of TF-IDF scores.""" documents = ["cat dog", "cat", "dog"] query_terms = ["cat"] scores = compute_tfidf(documents, query_terms) # All scores should be non-negative assert all(score >= 0.0 for score in scores) # Documents containing the term should have positive scores assert scores[0] > 0.0 # contains "cat" assert scores[1] > 0.0 # contains "cat" assert scores[2] == 0.0 # doesn't contain "cat" def test_compute_bm25_mathematical_properties(self): """Test mathematical properties of BM25 scores.""" documents = ["cat dog", "cat", "dog"] query_terms = ["cat"] scores = compute_bm25(documents, query_terms) # All scores should be non-negative assert all(score >= 0.0 for score in scores) # Documents containing the term should have positive scores assert scores[0] > 0.0 # contains "cat" assert scores[1] > 0.0 # contains "cat" assert scores[2] == 0.0 # doesn't contain "cat" def test_compute_tfidf_duplicate_terms_in_query(self): """Test TF-IDF with duplicate terms in query.""" documents = ["cat dog bird", "cat cat dog", "bird bird bird"] query_terms = ["cat", "cat", "dog"] # "cat" appears twice scores = compute_tfidf(documents, query_terms) # Should handle duplicate query terms gracefully assert len(scores) == 3 assert all(isinstance(score, float) for score in scores) # First two documents should have positive scores assert scores[0] > 0.0 assert scores[1] > 0.0 # Third document only contains "bird", so should have zero score assert scores[2] == 0.0 def test_compute_bm25_duplicate_terms_in_query(self): """Test BM25 with duplicate terms in query.""" documents = ["cat dog bird", "cat cat dog", "bird bird bird"] query_terms = ["cat", "cat", "dog"] # "cat" appears twice scores = compute_bm25(documents, query_terms) # Should handle duplicate query terms gracefully assert len(scores) == 3 assert all(isinstance(score, float) for score in scores) # First two documents should have positive scores assert scores[0] > 0.0 assert scores[1] > 0.0 # Third document only contains "bird", so should have zero score assert scores[2] == 0.0
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/base/data/test_kb_utils.py", "license": "MIT License", "lines": 349, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/tests/integration/components/mcp/test_mcp_memory_leak.py
"""Integration tests for MCP memory leak fix. These tests verify that the MCP session manager properly handles session reuse and cleanup to prevent subprocess leaks. """ import asyncio import contextlib import os import platform import shutil import time import psutil import pytest from lfx.base.mcp.util import MCPSessionManager from lfx.log.logger import logger from mcp import StdioServerParameters pytestmark = [ pytest.mark.timeout(300, method="thread"), pytest.mark.skip(reason="Skipping all MCP memory leak integration tests for now."), ] async def wait_tools(session, t=20): return await asyncio.wait_for(session.list_tools(), timeout=t) async def wait_no_children(proc, max_wait=10, target=None): deadline = time.monotonic() + max_wait while time.monotonic() < deadline: children = proc.children(recursive=True) if target is not None and len(children) <= target: return True if not children: return True await asyncio.sleep(0.2) return False @pytest.fixture def mcp_server_params(): """Create MCP server parameters for testing.""" command = ["npx", "-y", "@modelcontextprotocol/server-everything"] env_data = {"DEBUG": "true", "PATH": os.environ["PATH"]} if platform.system() == "Windows": return StdioServerParameters( command="cmd", args=["/c", f"{command[0]} {' '.join(command[1:])}"], env=env_data, ) return StdioServerParameters( command="bash", args=["-c", f"exec {' '.join(command)}"], env=env_data, ) @pytest.fixture def process_tracker(): """Track subprocess count for memory leak detection.""" process = psutil.Process() initial_count = len(process.children(recursive=True)) yield process, initial_count # Give some time for cleanup to complete before checking for leftover processes # Collect child processes that we expect to wait for try: children = process.children(recursive=True) if not children: return gone, alive = psutil.wait_procs(children, timeout=2) if gone: logger.debug("Processes exited naturally: %s", [p.pid for p in gone]) if alive: logger.debug("Processes still alive after 2s: %s", [p.pid for p in alive]) for p in alive: with contextlib.suppress(psutil.NoSuchProcess): p.terminate() gone2, alive2 = psutil.wait_procs(alive, timeout=5) if gone2: logger.debug("Processes terminated gracefully: %s", [p.pid for p in gone2]) for p in alive2: with contextlib.suppress(psutil.NoSuchProcess): p.kill() _ = psutil.wait_procs(alive2, timeout=2) leftover = process.children(recursive=True) assert not leftover, f"Leftover child processes: {[p.pid for p in leftover]}" except Exception as e: logger.exception("Error cleaning up child processes: %s", e) @pytest.mark.asyncio @pytest.mark.skipif(not shutil.which("npx"), reason="Node.js not available") async def test_session_reuse_prevents_subprocess_leak(mcp_server_params, process_tracker): """Test that session reuse prevents subprocess proliferation.""" process, initial_count = process_tracker session_manager = MCPSessionManager() try: # Create multiple sessions with different context IDs but same server sessions = [] for i in range(3): context_id = f"test_context_{i}" session = await session_manager.get_session(context_id, mcp_server_params, "stdio") sessions.append(session) # Verify session is working tools_response = await wait_tools(session) assert len(tools_response.tools) > 0 # Check subprocess count after creating sessions current_count = len(process.children(recursive=True)) subprocess_increase = current_count - initial_count # With the fix, we should have minimal subprocess increase # (ideally 2 subprocesses max for the MCP server) assert subprocess_increase <= 4, f"Too many subprocesses created: {subprocess_increase}" # Verify all sessions are functional for session in sessions: tools_response = await wait_tools(session) assert len(tools_response.tools) > 0 finally: await session_manager.cleanup_all() await wait_no_children(process, max_wait=10, target=initial_count) await asyncio.sleep(2) # Allow cleanup to complete @pytest.mark.asyncio @pytest.mark.skipif(not shutil.which("npx"), reason="Node.js not available") async def test_session_cleanup_removes_subprocesses(mcp_server_params, process_tracker): """Test that session cleanup properly removes subprocesses.""" process, initial_count = process_tracker session_manager = MCPSessionManager() try: # Create a session session = await session_manager.get_session("cleanup_test", mcp_server_params, "stdio") tools_response = await wait_tools(session) assert len(tools_response.tools) > 0 # Verify subprocess was created after_creation_count = len(process.children(recursive=True)) assert after_creation_count > initial_count finally: # Clean up session await session_manager.cleanup_all() await wait_no_children(process, max_wait=10, target=initial_count) await asyncio.sleep(2) # Allow cleanup to complete # Verify subprocess was cleaned up after_cleanup_count = len(process.children(recursive=True)) # Allow some tolerance for cleanup timing and system processes assert after_cleanup_count <= initial_count + 1, ( f"Subprocesses not cleaned up properly: {after_cleanup_count} vs {initial_count}" ) @pytest.mark.asyncio @pytest.mark.skipif(not shutil.which("npx"), reason="Node.js not available") async def test_session_health_check_and_recovery(mcp_server_params, process_tracker): """Test that unhealthy sessions are properly detected and recreated.""" process, initial_count = process_tracker session_manager = MCPSessionManager() try: # Create a session session1 = await session_manager.get_session("health_test", mcp_server_params, "stdio") tools_response = await wait_tools(session1) assert len(tools_response.tools) > 0 # Simulate session becoming unhealthy by accessing internal state # This is a bit of a hack but necessary for testing server_key = session_manager._get_server_key(mcp_server_params, "stdio") if hasattr(session_manager, "sessions_by_server"): # For the fixed version sessions = session_manager.sessions_by_server.get(server_key, {}) if sessions: session_id = next(iter(sessions.keys())) session_info = sessions[session_id] if "task" in session_info: task = session_info["task"] if not task.done(): task.cancel() with contextlib.suppress(asyncio.CancelledError): await task elif hasattr(session_manager, "sessions"): # For the original version for session_info in session_manager.sessions.values(): if "task" in session_info: task = session_info["task"] if not task.done(): task.cancel() with contextlib.suppress(asyncio.CancelledError): await task # Wait a bit for the task to be cancelled await asyncio.sleep(1) # Try to get a session again - should create a new healthy one session2 = await session_manager.get_session("health_test_2", mcp_server_params, "stdio") tools_response = await wait_tools(session2) assert len(tools_response.tools) > 0 finally: await session_manager.cleanup_all() await wait_no_children(process, max_wait=10, target=initial_count) await asyncio.sleep(2) @pytest.mark.asyncio @pytest.mark.skipif(not shutil.which("npx"), reason="Node.js not available") async def test_multiple_servers_isolation(process_tracker): """Test that different servers get separate sessions.""" process, initial_count = process_tracker session_manager = MCPSessionManager() # Create parameters for different servers server1_params = StdioServerParameters( command="bash", args=["-c", "exec npx -y @modelcontextprotocol/server-everything"], env={"DEBUG": "true", "PATH": os.environ["PATH"]}, ) server2_params = StdioServerParameters( command="bash", args=["-c", "exec npx -y @modelcontextprotocol/server-everything"], env={"DEBUG": "false", "PATH": os.environ["PATH"]}, # Different env ) try: # Create sessions for different servers session1 = await session_manager.get_session("server1_test", server1_params, "stdio") session2 = await session_manager.get_session("server2_test", server2_params, "stdio") # Verify both sessions work tools1 = await session1.list_tools() tools2 = await session2.list_tools() assert len(tools1.tools) > 0 assert len(tools2.tools) > 0 # Sessions should be different objects for different servers (different environments) # Since the servers have different environments, they should get different server keys server_key1 = session_manager._get_server_key(server1_params, "stdio") server_key2 = session_manager._get_server_key(server2_params, "stdio") assert server_key1 != server_key2, "Different server environments should generate different keys" assert session1 is not session2 finally: await session_manager.cleanup_all() await wait_no_children(process, max_wait=10, target=initial_count) await asyncio.sleep(2) @pytest.mark.asyncio async def test_session_manager_server_key_generation(): """Test that server key generation works correctly.""" session_manager = MCPSessionManager() # Test stdio server key stdio_params = StdioServerParameters( command="test_command", args=["arg1", "arg2"], env={"TEST": "value"}, ) key1 = session_manager._get_server_key(stdio_params, "stdio") key2 = session_manager._get_server_key(stdio_params, "stdio") # Same parameters should generate same key assert key1 == key2 assert key1.startswith("stdio_") # Different parameters should generate different keys stdio_params2 = StdioServerParameters( command="different_command", args=["arg1", "arg2"], env={"TEST": "value"}, ) key3 = session_manager._get_server_key(stdio_params2, "stdio") assert key1 != key3 # Test SSE server key sse_params = { "url": "http://example.com/sse", "headers": {"Authorization": "Bearer token"}, "timeout_seconds": 30, "sse_read_timeout_seconds": 30, } sse_key1 = session_manager._get_server_key(sse_params, "sse") sse_key2 = session_manager._get_server_key(sse_params, "sse") assert sse_key1 == sse_key2 assert sse_key1.startswith("sse_") # Different URL should generate different key sse_params2 = sse_params.copy() sse_params2["url"] = "http://different.com/sse" sse_key3 = session_manager._get_server_key(sse_params2, "sse") assert sse_key1 != sse_key3 @pytest.mark.asyncio async def test_session_manager_connectivity_validation(): """Test session connectivity validation.""" session_manager = MCPSessionManager() # Mock a session that responds to list_tools class MockSession: def __init__(self, should_fail=False): # noqa: FBT002 self.should_fail = should_fail async def list_tools(self): if self.should_fail: msg = "Connection failed" raise Exception(msg) # noqa: TRY002 class MockResponse: def __init__(self): self.tools = ["tool1", "tool2"] return MockResponse() # Test healthy session healthy_session = MockSession(should_fail=False) is_healthy = await session_manager._validate_session_connectivity(healthy_session) assert is_healthy is True # Test unhealthy session unhealthy_session = MockSession(should_fail=True) is_healthy = await session_manager._validate_session_connectivity(unhealthy_session) assert is_healthy is False # Test session that returns None class MockNoneSession: async def list_tools(self): return None none_session = MockNoneSession() is_healthy = await session_manager._validate_session_connectivity(none_session) assert is_healthy is False @pytest.mark.asyncio async def test_session_manager_cleanup_all(process_tracker): """Test that cleanup_all properly cleans up all sessions.""" process, initial_count = process_tracker session_manager = MCPSessionManager() # Mock some sessions using the correct structure session_manager.sessions_by_server = { "server1": { "sessions": { "session1": { "session": "mock_session", "task": asyncio.create_task(asyncio.sleep(10)), "type": "stdio", "last_used": asyncio.get_event_loop().time(), } } }, "server2": { "sessions": { "session2": { "session": "mock_session", "task": asyncio.create_task(asyncio.sleep(10)), "type": "sse", "last_used": asyncio.get_event_loop().time(), } } }, } # Add some background tasks task1 = asyncio.create_task(asyncio.sleep(10)) task2 = asyncio.create_task(asyncio.sleep(10)) session_manager._background_tasks = {task1, task2} # Cleanup all await session_manager.cleanup_all() await wait_no_children(process, max_wait=10, target=initial_count) # Verify cleanup if hasattr(session_manager, "sessions_by_server"): # For fixed version assert len(session_manager.sessions_by_server) == 0 elif hasattr(session_manager, "sessions"): # For original version assert len(session_manager.sessions) == 0 # Verify background tasks were cancelled assert task1.done() assert task2.done()
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/integration/components/mcp/test_mcp_memory_leak.py", "license": "MIT License", "lines": 329, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/tests/unit/base/mcp/test_mcp_util.py
"""Unit tests for MCP utility functions. This test suite validates the MCP utility functions including: - Session management - Header validation and processing - Utility functions for name sanitization and schema conversion """ import re import shutil import sys from unittest.mock import AsyncMock, MagicMock, patch import pytest from lfx.base.mcp import util from lfx.base.mcp.util import ( MCPSessionManager, MCPSseClient, MCPStdioClient, MCPStreamableHttpClient, _process_headers, update_tools, validate_headers, ) class TestMCPSessionManager: @pytest.fixture async def session_manager(self): """Create a session manager and clean it up after the test.""" manager = MCPSessionManager() yield manager # Clean up after test await manager.cleanup_all() async def test_session_caching(self, session_manager): """Test that sessions are properly cached and reused.""" context_id = "test_context" connection_params = MagicMock() transport_type = "stdio" # Create a mock session that will appear healthy mock_session = AsyncMock() mock_session._write_stream = MagicMock() mock_session._write_stream._closed = False # Create a mock task that appears to be running mock_task = AsyncMock() mock_task.done = MagicMock(return_value=False) with ( patch.object(session_manager, "_create_stdio_session") as mock_create, patch.object(session_manager, "_validate_session_connectivity", return_value=True), ): mock_create.return_value = (mock_session, mock_task) # First call should create session session1 = await session_manager.get_session(context_id, connection_params, transport_type) # Second call should return cached session without creating new one session2 = await session_manager.get_session(context_id, connection_params, transport_type) assert session1 == session2 assert session1 == mock_session # Should only create once since the second call should use the cached session mock_create.assert_called_once() async def test_session_cleanup(self, session_manager): """Test session cleanup functionality.""" context_id = "test_context" server_key = "test_server" session_id = "test_session" # Add a session to the manager with proper mock setup using new structure mock_task = AsyncMock() mock_task.done = MagicMock(return_value=False) # Use MagicMock for sync method mock_task.cancel = MagicMock() # Use MagicMock for sync method # Set up the new session structure session_manager.sessions_by_server[server_key] = { "sessions": {session_id: {"session": AsyncMock(), "task": mock_task, "type": "stdio", "last_used": 0}}, "last_cleanup": 0, } # Set up mapping for backwards compatibility session_manager._context_to_session[context_id] = (server_key, session_id) await session_manager._cleanup_session(context_id) # Should cancel the task and remove from sessions mock_task.cancel.assert_called_once() assert session_id not in session_manager.sessions_by_server[server_key]["sessions"] async def test_server_switch_detection(self, session_manager): """Test that server switches are properly detected and handled.""" context_id = "test_context" # First server server1_params = MagicMock() server1_params.command = "server1" # Second server server2_params = MagicMock() server2_params.command = "server2" with ( patch.object(session_manager, "_create_stdio_session") as mock_create, patch.object(session_manager, "_validate_session_connectivity", return_value=True), ): mock_session1 = AsyncMock() mock_session2 = AsyncMock() mock_task1 = AsyncMock() mock_task2 = AsyncMock() mock_create.side_effect = [(mock_session1, mock_task1), (mock_session2, mock_task2)] # First connection session1 = await session_manager.get_session(context_id, server1_params, "stdio") # Switch to different server should create new session session2 = await session_manager.get_session(context_id, server2_params, "stdio") assert session1 != session2 assert mock_create.call_count == 2 class TestHeaderValidation: """Test the header validation functionality.""" def test_validate_headers_valid_input(self): """Test header validation with valid headers.""" headers = {"Authorization": "Bearer token123", "Content-Type": "application/json", "X-API-Key": "secret-key"} result = validate_headers(headers) # Headers should be normalized to lowercase expected = {"authorization": "Bearer token123", "content-type": "application/json", "x-api-key": "secret-key"} assert result == expected def test_validate_headers_empty_input(self): """Test header validation with empty/None input.""" assert validate_headers({}) == {} assert validate_headers(None) == {} def test_validate_headers_invalid_names(self): """Test header validation with invalid header names.""" headers = { "Invalid Header": "value", # spaces not allowed "Header@Name": "value", # @ not allowed "Header Name": "value", # spaces not allowed "Valid-Header": "value", # this should pass } result = validate_headers(headers) # Only the valid header should remain assert result == {"valid-header": "value"} def test_validate_headers_sanitize_values(self): """Test header value sanitization.""" headers = { "Authorization": "Bearer \x00token\x1f with\r\ninjection", "Clean-Header": " clean value ", "Empty-After-Clean": "\x00\x01\x02", "Tab-Header": "value\twith\ttabs", # tabs should be preserved } result = validate_headers(headers) # Control characters should be removed, whitespace trimmed # Header with injection attempts should be skipped expected = {"clean-header": "clean value", "tab-header": "value\twith\ttabs"} assert result == expected def test_validate_headers_non_string_values(self): """Test header validation with non-string values.""" headers = {"String-Header": "valid", "Number-Header": 123, "None-Header": None, "List-Header": ["value"]} result = validate_headers(headers) # Only string headers should remain assert result == {"string-header": "valid"} def test_validate_headers_injection_attempts(self): """Test header validation against injection attempts.""" headers = { "Injection1": "value\r\nInjected-Header: malicious", "Injection2": "value\nX-Evil: attack", "Safe-Header": "safe-value", } result = validate_headers(headers) # Injection attempts should be filtered out assert result == {"safe-header": "safe-value"} class TestGlobalVariableResolution: """Test global variable resolution in headers.""" def test_resolve_global_variables_basic(self): """Test basic global variable resolution in headers.""" from lfx.base.mcp.util import _resolve_global_variables_in_headers headers = {"x-api-key": "MY_API_KEY", "authorization": "MY_TOKEN"} request_variables = {"MY_API_KEY": "secret-key-123", "MY_TOKEN": "token-456"} # pragma: allowlist secret result = _resolve_global_variables_in_headers(headers, request_variables) assert result == {"x-api-key": "secret-key-123", "authorization": "token-456"} def test_resolve_global_variables_no_variables(self): """Test header resolution when no request_variables provided.""" from lfx.base.mcp.util import _resolve_global_variables_in_headers headers = {"x-api-key": "MY_API_KEY", "content-type": "application/json"} # No request_variables result = _resolve_global_variables_in_headers(headers, None) assert result == headers # Empty request_variables result = _resolve_global_variables_in_headers(headers, {}) assert result == headers def test_resolve_global_variables_partial_match(self): """Test resolution when only some headers match variables.""" from lfx.base.mcp.util import _resolve_global_variables_in_headers headers = { "x-api-key": "MY_API_KEY", # matches "authorization": "static-token", # no match "x-custom": "MY_CUSTOM", # matches } request_variables = {"MY_API_KEY": "resolved-key", "MY_CUSTOM": "custom-value"} # pragma: allowlist secret result = _resolve_global_variables_in_headers(headers, request_variables) assert result == { "x-api-key": "resolved-key", "authorization": "static-token", "x-custom": "custom-value", } def test_resolve_global_variables_non_string_values(self): """Test that non-string header values are preserved.""" from lfx.base.mcp.util import _resolve_global_variables_in_headers headers = {"x-api-key": "MY_KEY", "x-number": 123, "x-none": None} request_variables = {"MY_KEY": "resolved"} result = _resolve_global_variables_in_headers(headers, request_variables) assert result == {"x-api-key": "resolved", "x-number": 123, "x-none": None} def test_process_headers_with_request_variables_dict(self): """Test _process_headers with dict input and request_variables.""" headers = {"x-api-key": "MY_API_KEY", "content-type": "application/json"} request_variables = {"MY_API_KEY": "secret-123"} # pragma: allowlist secret result = _process_headers(headers, request_variables) # Should resolve variable and normalize to lowercase assert result == {"x-api-key": "secret-123", "content-type": "application/json"} def test_process_headers_with_request_variables_list(self): """Test _process_headers with list input and request_variables.""" headers = [ {"key": "x-api-key", "value": "MY_API_KEY"}, {"key": "Content-Type", "value": "application/json"}, ] request_variables = {"MY_API_KEY": "secret-123"} # pragma: allowlist secret result = _process_headers(headers, request_variables) # Should resolve variable and normalize to lowercase assert result == {"x-api-key": "secret-123", "content-type": "application/json"} def test_process_headers_without_request_variables(self): """Test _process_headers maintains backward compatibility without request_variables.""" headers = {"X-API-Key": "static-value", "Content-Type": "application/json"} result = _process_headers(headers) # Should just normalize without resolution assert result == {"x-api-key": "static-value", "content-type": "application/json"} def test_resolve_global_variables_case_sensitive_matching(self): """Test that variable name matching is case-sensitive.""" from lfx.base.mcp.util import _resolve_global_variables_in_headers headers = {"x-api-key": "my_api_key", "x-token": "MY_API_KEY"} request_variables = {"MY_API_KEY": "resolved-uppercase"} # pragma: allowlist secret result = _resolve_global_variables_in_headers(headers, request_variables) # Only exact match should be resolved assert result == {"x-api-key": "my_api_key", "x-token": "resolved-uppercase"} def test_resolve_global_variables_empty_headers(self): """Test resolution with empty headers.""" from lfx.base.mcp.util import _resolve_global_variables_in_headers result = _resolve_global_variables_in_headers({}, {"VAR": "value"}) assert result == {} def test_resolve_global_variables_special_characters(self): """Test resolution with special characters in values.""" from lfx.base.mcp.util import _resolve_global_variables_in_headers headers = {"authorization": "MY_TOKEN"} request_variables = {"MY_TOKEN": "Bearer token-with-special!@#$%^&*()_+-=[]{}|;:,.<>?"} result = _resolve_global_variables_in_headers(headers, request_variables) assert result["authorization"] == "Bearer token-with-special!@#$%^&*()_+-=[]{}|;:,.<>?" class TestStreamableHTTPHeaderIntegration: """Integration test to verify headers are properly passed through the entire StreamableHTTP flow.""" async def test_headers_processing(self): """Test that headers flow properly from server config through to StreamableHTTP client connection.""" # Test the header processing function directly headers_input = [ {"key": "Authorization", "value": "Bearer test-token"}, {"key": "X-API-Key", "value": "secret-key"}, ] expected_headers = { "authorization": "Bearer test-token", # normalized to lowercase "x-api-key": "secret-key", } # Test _process_headers function with validation processed_headers = _process_headers(headers_input) assert processed_headers == expected_headers # Test different input formats # Test dict input with validation dict_headers = {"Authorization": "Bearer dict-token", "Invalid Header": "bad"} result = _process_headers(dict_headers) # Invalid header should be filtered out, valid header normalized assert result == {"authorization": "Bearer dict-token"} # Test None input assert _process_headers(None) == {} # Test empty list assert _process_headers([]) == {} # Test malformed list malformed_headers = [{"key": "Auth"}, {"value": "token"}] # Missing value/key assert _process_headers(malformed_headers) == {} # Test list with invalid header names invalid_headers = [ {"key": "Valid-Header", "value": "good"}, {"key": "Invalid Header", "value": "bad"}, # spaces not allowed ] result = _process_headers(invalid_headers) assert result == {"valid-header": "good"} async def test_streamable_http_client_header_storage(self): """Test that SSE client properly stores headers in connection params.""" streamable_http_client = MCPStreamableHttpClient() test_url = "http://test.url" test_headers = {"Authorization": "Bearer test123", "Custom": "value"} # Test that headers are properly stored in connection params # Set connection params as a dict like the implementation expects streamable_http_client._connection_params = { "url": test_url, "headers": test_headers, "timeout_seconds": 30, "sse_read_timeout_seconds": 30, } # Verify headers are stored assert streamable_http_client._connection_params["url"] == test_url assert streamable_http_client._connection_params["headers"] == test_headers class TestUpdateToolsStdioHeaders: """Test that update_tools injects component headers into stdio args.""" @pytest.mark.asyncio async def test_stdio_headers_injected_with_existing_headers_flag(self): """Headers should be injected as --headers key value before the existing --headers flag.""" mock_stdio = AsyncMock(spec=MCPStdioClient) mock_stdio.connect_to_server.return_value = [] mock_stdio._connected = True server_config = { "command": "uvx", "args": [ "mcp-proxy", "--transport", "streamablehttp", "--headers", "x-api-key", "sk-existing", "http://localhost:7860/api/v1/mcp/project/test/streamable", ], "headers": {"Authorization": "Bearer token123"}, } await update_tools("test-server", server_config, mcp_stdio_client=mock_stdio) mock_stdio.connect_to_server.assert_called_once() full_command = mock_stdio.connect_to_server.call_args[0][0] # The injected --headers should appear before the existing --headers assert "--headers authorization 'Bearer token123' --headers x-api-key sk-existing" in full_command # URL should still be at the end assert full_command.endswith("http://localhost:7860/api/v1/mcp/project/test/streamable") @pytest.mark.asyncio async def test_stdio_headers_injected_without_existing_headers_flag(self): """When no --headers flag exists, headers should be inserted before the last positional arg.""" mock_stdio = AsyncMock(spec=MCPStdioClient) mock_stdio.connect_to_server.return_value = [] mock_stdio._connected = True server_config = { "command": "uvx", "args": [ "mcp-proxy", "--transport", "streamablehttp", "http://localhost:7860/streamable", ], "headers": {"X-Api-Key": "my-key"}, } await update_tools("test-server", server_config, mcp_stdio_client=mock_stdio) full_command = mock_stdio.connect_to_server.call_args[0][0] # --headers should be inserted before the URL assert "--headers x-api-key my-key http://localhost:7860/streamable" in full_command @pytest.mark.asyncio async def test_stdio_multiple_headers_each_get_own_flag(self): """Each header should get its own --headers key value triplet.""" mock_stdio = AsyncMock(spec=MCPStdioClient) mock_stdio.connect_to_server.return_value = [] mock_stdio._connected = True server_config = { "command": "uvx", "args": [ "mcp-proxy", "--transport", "streamablehttp", "--headers", "x-api-key", "sk-existing", "http://localhost/streamable", ], "headers": {"X-Custom-One": "val1", "X-Custom-Two": "val2"}, } await update_tools("test-server", server_config, mcp_stdio_client=mock_stdio) full_command = mock_stdio.connect_to_server.call_args[0][0] # Each header gets its own --headers flag assert "--headers x-custom-one val1" in full_command assert "--headers x-custom-two val2" in full_command # Original header still present assert "--headers x-api-key sk-existing" in full_command @pytest.mark.asyncio async def test_stdio_no_headers_leaves_args_unchanged(self): """When no component headers are set, args should not be modified.""" mock_stdio = AsyncMock(spec=MCPStdioClient) mock_stdio.connect_to_server.return_value = [] mock_stdio._connected = True server_config = { "command": "uvx", "args": ["mcp-proxy", "--transport", "streamablehttp", "http://localhost/streamable"], } await update_tools("test-server", server_config, mcp_stdio_client=mock_stdio) full_command = mock_stdio.connect_to_server.call_args[0][0] assert full_command == "uvx mcp-proxy --transport streamablehttp http://localhost/streamable" @pytest.mark.asyncio async def test_stdio_multiword_command_with_empty_args(self): """A multi-word command string (e.g. 'uvx mcp-server-fetch') with empty args should be split correctly. Regression test: shlex.join(["uvx mcp-server-fetch"]) used to produce a single-quoted token that bash treated as one binary name, causing 'exec: uvx mcp-server-fetch: not found'. """ mock_stdio = AsyncMock(spec=MCPStdioClient) mock_stdio.connect_to_server.return_value = [] mock_stdio._connected = True server_config = { "command": "uvx mcp-server-fetch", "args": [], } await update_tools("test-server", server_config, mcp_stdio_client=mock_stdio) full_command = mock_stdio.connect_to_server.call_args[0][0] assert full_command == "uvx mcp-server-fetch" @pytest.mark.asyncio async def test_stdio_multiword_command_with_args(self): """A multi-word command string combined with additional args should produce correct tokens.""" mock_stdio = AsyncMock(spec=MCPStdioClient) mock_stdio.connect_to_server.return_value = [] mock_stdio._connected = True server_config = { "command": "uvx mcp-server-fetch", "args": ["--timeout", "30"], } await update_tools("test-server", server_config, mcp_stdio_client=mock_stdio) full_command = mock_stdio.connect_to_server.call_args[0][0] assert full_command == "uvx mcp-server-fetch --timeout 30" @pytest.mark.asyncio async def test_stdio_headers_appended_when_all_args_are_flags(self): """When all args are flags (no positional URL), headers should be appended.""" mock_stdio = AsyncMock(spec=MCPStdioClient) mock_stdio.connect_to_server.return_value = [] mock_stdio._connected = True server_config = { "command": "some-tool", "args": ["--verbose", "--debug"], "headers": {"Authorization": "Bearer tok"}, } await update_tools("test-server", server_config, mcp_stdio_client=mock_stdio) full_command = mock_stdio.connect_to_server.call_args[0][0] assert full_command == "some-tool --verbose --debug --headers authorization 'Bearer tok'" @pytest.mark.asyncio async def test_stdio_headers_appended_when_last_token_is_flag_value(self): """When the last token is a flag's value, headers should be appended, not inserted before it.""" mock_stdio = AsyncMock(spec=MCPStdioClient) mock_stdio.connect_to_server.return_value = [] mock_stdio._connected = True server_config = { "command": "some-tool", "args": ["--port", "8080"], "headers": {"Authorization": "Bearer tok"}, } await update_tools("test-server", server_config, mcp_stdio_client=mock_stdio) full_command = mock_stdio.connect_to_server.call_args[0][0] # 8080 is a value for --port, not a positional arg, so headers go at the end assert full_command == "some-tool --port 8080 --headers authorization 'Bearer tok'" @pytest.mark.asyncio async def test_stdio_headers_inserted_before_positional_with_flag_value_pairs(self): """Headers should be inserted before the last positional arg even when flag+value pairs precede it.""" mock_stdio = AsyncMock(spec=MCPStdioClient) mock_stdio.connect_to_server.return_value = [] mock_stdio._connected = True server_config = { "command": "uvx", "args": ["mcp-proxy", "--port", "8080", "http://localhost/streamable"], "headers": {"X-Api-Key": "my-key"}, } await update_tools("test-server", server_config, mcp_stdio_client=mock_stdio) full_command = mock_stdio.connect_to_server.call_args[0][0] # --port 8080 is a flag pair; http://localhost/streamable is the positional arg assert full_command == "uvx mcp-proxy --port 8080 --headers x-api-key my-key http://localhost/streamable" @pytest.mark.asyncio async def test_stdio_headers_inserted_before_last_positional_with_multiple_positionals(self): """When multiple positional args exist, headers are inserted before the last one.""" mock_stdio = AsyncMock(spec=MCPStdioClient) mock_stdio.connect_to_server.return_value = [] mock_stdio._connected = True server_config = { "command": "uvx", "args": ["mcp-proxy", "--transport", "streamablehttp", "extra-pos-arg", "http://localhost/streamable"], "headers": {"X-Key": "val"}, } await update_tools("test-server", server_config, mcp_stdio_client=mock_stdio) full_command = mock_stdio.connect_to_server.call_args[0][0] # Should insert before the last positional (the URL), not before "extra-pos-arg" assert "--headers x-key val http://localhost/streamable" in full_command assert "extra-pos-arg --headers" in full_command @pytest.mark.asyncio async def test_stdio_does_not_mutate_original_config(self): """The original server_config args list should not be mutated.""" mock_stdio = AsyncMock(spec=MCPStdioClient) mock_stdio.connect_to_server.return_value = [] mock_stdio._connected = True original_args = ["mcp-proxy", "--headers", "x-api-key", "sk-orig", "http://localhost/s"] server_config = { "command": "uvx", "args": original_args, "headers": {"X-Extra": "val"}, } await update_tools("test-server", server_config, mcp_stdio_client=mock_stdio) # Original list should be unchanged assert original_args == ["mcp-proxy", "--headers", "x-api-key", "sk-orig", "http://localhost/s"] class TestFieldNameConversion: """Test camelCase to snake_case field name conversion functionality.""" def test_camel_to_snake_basic(self): """Test basic camelCase to snake_case conversion.""" assert util._camel_to_snake("weatherMain") == "weather_main" assert util._camel_to_snake("topN") == "top_n" assert util._camel_to_snake("firstName") == "first_name" assert util._camel_to_snake("lastName") == "last_name" def test_camel_to_snake_edge_cases(self): """Test edge cases for camelCase conversion.""" # Already snake_case should remain unchanged assert util._camel_to_snake("snake_case") == "snake_case" assert util._camel_to_snake("already_snake") == "already_snake" # Single word should remain unchanged assert util._camel_to_snake("simple") == "simple" assert util._camel_to_snake("UPPER") == "upper" # Multiple consecutive capitals assert util._camel_to_snake("XMLHttpRequest") == "xmlhttp_request" assert util._camel_to_snake("HTTPSConnection") == "httpsconnection" # Numbers assert util._camel_to_snake("version2Beta") == "version2_beta" assert util._camel_to_snake("test123Value") == "test123_value" def test_convert_field_names_exact_match(self): """Test field name conversion when fields already match schema.""" from pydantic import Field, create_model # Create test schema with snake_case fields test_schema = create_model( "TestSchema", weather_main=(str, Field(..., description="Main weather condition")), top_n=(int, Field(..., description="Number of results")), ) # Input with exact field names should pass through unchanged input_args = {"weather_main": "Snow", "top_n": 6} result = util._convert_camel_case_to_snake_case(input_args, test_schema) assert result == {"weather_main": "Snow", "top_n": 6} def test_convert_field_names_camel_to_snake(self): """Test field name conversion from camelCase to snake_case.""" from pydantic import Field, create_model # Create test schema with snake_case fields test_schema = create_model( "TestSchema", weather_main=(str, Field(..., description="Main weather condition")), top_n=(int, Field(..., description="Number of results")), user_id=(str, Field(..., description="User identifier")), ) # Input with camelCase field names input_args = {"weatherMain": "Snow", "topN": 6, "userId": "user123"} result = util._convert_camel_case_to_snake_case(input_args, test_schema) assert result == {"weather_main": "Snow", "top_n": 6, "user_id": "user123"} def test_convert_field_names_mixed_case(self): """Test field name conversion with mixed naming conventions.""" from pydantic import Field, create_model # Create test schema with mixed field names test_schema = create_model( "TestSchema", weather_main=(str, Field(..., description="Main weather condition")), topN=(int, Field(..., description="Number of results")), # Already camelCase in schema user_count=(int, Field(..., description="User count")), ) # Input with mixed naming input_args = {"weatherMain": "Snow", "topN": 6, "user_count": 42} result = util._convert_camel_case_to_snake_case(input_args, test_schema) # weather_main should be converted, topN should match exactly, user_count should match exactly assert result == {"weather_main": "Snow", "topN": 6, "user_count": 42} def test_convert_field_names_no_match(self): """Test field name conversion with fields that don't match schema.""" from pydantic import Field, create_model # Create test schema test_schema = create_model("TestSchema", expected_field=(str, Field(..., description="Expected field"))) # Input with unrecognized field names input_args = {"unknownField": "value", "anotherField": "value2"} result = util._convert_camel_case_to_snake_case(input_args, test_schema) # Fields that don't match should be kept as-is (validation will catch errors) assert result == {"unknownField": "value", "anotherField": "value2"} def test_convert_field_names_empty_input(self): """Test field name conversion with empty input.""" from pydantic import Field, create_model test_schema = create_model("TestSchema", test_field=(str, Field(..., description="Test field"))) # Empty input should return empty result result = util._convert_camel_case_to_snake_case({}, test_schema) assert result == {} def test_field_conversion_in_tool_validation(self): """Test that field conversion works end-to-end with Pydantic validation.""" from pydantic import Field, create_model # Create test schema matching the original error case test_schema = create_model( "TestSchema", weather_main=(str, Field(..., description="Main weather condition")), top_n=(int, Field(..., description="Number of top results")), ) # Original error case: camelCase input input_args = {"weatherMain": "Snow", "topN": 6} converted_args = util._convert_camel_case_to_snake_case(input_args, test_schema) # Should validate successfully with converted field names validated = test_schema.model_validate(converted_args) assert validated.weather_main == "Snow" assert validated.top_n == 6 assert validated.model_dump() == {"weather_main": "Snow", "top_n": 6} def test_field_conversion_preserves_values(self): """Test that field conversion preserves all value types correctly.""" from pydantic import Field, create_model test_schema = create_model( "TestSchema", string_field=(str, Field(...)), int_field=(int, Field(...)), bool_field=(bool, Field(...)), list_field=(list, Field(...)), dict_field=(dict, Field(...)), ) input_args = { "stringField": "test_string", "intField": 42, "boolField": True, "listField": [1, 2, 3], "dictField": {"nested": "value"}, } result = util._convert_camel_case_to_snake_case(input_args, test_schema) expected = { "string_field": "test_string", "int_field": 42, "bool_field": True, "list_field": [1, 2, 3], "dict_field": {"nested": "value"}, } assert result == expected def test_json_schema_alias_functionality(self): """Test that JSON schema creation includes aliases for camelCase field names.""" from lfx.schema.json_schema import create_input_schema_from_json_schema from pydantic import ValidationError # Create a JSON schema with snake_case field names test_schema = { "type": "object", "properties": { "weather_main": {"type": "string", "description": "Main weather condition"}, "top_n": {"type": "integer", "description": "Number of results"}, "user_id": {"type": "string", "description": "User identifier"}, }, "required": ["weather_main", "top_n"], } # Create the Pydantic model using our function input_schema = create_input_schema_from_json_schema(test_schema) # Test with snake_case field names (should work) result1 = input_schema(weather_main="Rain", top_n=8) assert result1.weather_main == "Rain" assert result1.top_n == 8 # Test with camelCase field names (should also work due to aliases) result2 = input_schema(weatherMain="Rain", topN=8) assert result2.weather_main == "Rain" assert result2.top_n == 8 # Test with mixed case field names (should work) result3 = input_schema(weatherMain="Rain", top_n=8, userId="user123") assert result3.weather_main == "Rain" assert result3.top_n == 8 assert result3.user_id == "user123" # Test validation error (should fail with missing required field) with pytest.raises(ValidationError): input_schema(weatherMain="Rain") # Missing topN/top_n @pytest.mark.asyncio async def test_tool_empty_arguments_error_handling(self): """Test that tools provide helpful error messages when called with no arguments.""" from unittest.mock import AsyncMock from lfx.schema.json_schema import create_input_schema_from_json_schema # Create a JSON schema with required fields test_schema = { "type": "object", "properties": { "weather_main": {"type": "string", "description": "Main weather condition"}, "top_n": {"type": "integer", "description": "Number of results"}, }, "required": ["weather_main", "top_n"], } # Create the Pydantic model using our function input_schema = create_input_schema_from_json_schema(test_schema) # Create a mock client mock_client = AsyncMock() mock_client.run_tool = AsyncMock(return_value="Success") # Create the tool coroutine tool_coroutine = util.create_tool_coroutine("test_tool", input_schema, mock_client) # Test that calling with no arguments gives a helpful error message with pytest.raises(ValueError, match="requires arguments but none were provided") as exc_info: await tool_coroutine() error_msg = str(exc_info.value) assert "test_tool" in error_msg assert "requires arguments but none were provided" in error_msg assert "weather_main" in error_msg assert "top_n" in error_msg # Test that calling with correct arguments works result = await tool_coroutine(weather_main="Rain", top_n=8) assert result == "Success" class TestToolExecutionWithFieldConversion: """Test that field name conversion works in actual tool execution.""" def test_create_tool_coroutine_with_camel_case_fields(self): """Test that create_tool_coroutine handles camelCase field conversion.""" from unittest.mock import AsyncMock from pydantic import Field, create_model # Create test schema with snake_case fields test_schema = create_model( "TestSchema", weather_main=(str, Field(..., description="Main weather condition")), top_n=(int, Field(..., description="Number of results")), ) # Mock client mock_client = AsyncMock() mock_client.run_tool = AsyncMock(return_value="tool_result") # Create tool coroutine tool_coroutine = util.create_tool_coroutine("test_tool", test_schema, mock_client) # Test that it's actually a coroutine function import asyncio assert asyncio.iscoroutinefunction(tool_coroutine) def test_create_tool_func_with_camel_case_fields(self): """Test that create_tool_func handles camelCase field conversion.""" from unittest.mock import AsyncMock from pydantic import Field, create_model # Create test schema with snake_case fields test_schema = create_model( "TestSchema", weather_main=(str, Field(..., description="Main weather condition")), top_n=(int, Field(..., description="Number of results")), ) # Mock client with async run_tool method mock_client = AsyncMock() mock_client.run_tool = AsyncMock(return_value="tool_result") # Create tool function tool_func = util.create_tool_func("test_tool", test_schema, mock_client) # Mock run_until_complete from async_helpers with patch("lfx.base.mcp.util.run_until_complete", return_value="tool_result") as mock_run_until_complete: # Test with camelCase arguments result = tool_func(weatherMain="Snow", topN=6) assert result == "tool_result" # Verify that run_until_complete was called mock_run_until_complete.assert_called_once() @pytest.mark.asyncio async def test_tool_coroutine_field_conversion_end_to_end(self): """Test end-to-end field conversion in tool coroutine.""" from unittest.mock import AsyncMock from pydantic import Field, create_model # Create test schema with snake_case fields (matching original error case) test_schema = create_model( "TestSchema", weather_main=(str, Field(..., description="Main weather condition")), top_n=(int, Field(..., description="Number of results")), ) # Mock client mock_client = AsyncMock() mock_client.run_tool = AsyncMock(return_value="success") # Create tool coroutine tool_coroutine = util.create_tool_coroutine("test_tool", test_schema, mock_client) # Test with camelCase keyword arguments (the problematic case) result = await tool_coroutine(weatherMain="Snow", topN=6) assert result == "success" # Verify client was called with converted field names mock_client.run_tool.assert_called_once_with("test_tool", arguments={"weather_main": "Snow", "top_n": 6}) @pytest.mark.asyncio async def test_tool_coroutine_positional_args_no_conversion(self): """Test that positional arguments work correctly without field conversion.""" from unittest.mock import AsyncMock from pydantic import Field, create_model test_schema = create_model( "TestSchema", weather_main=(str, Field(..., description="Main weather condition")), top_n=(int, Field(..., description="Number of results")), ) # Mock client mock_client = AsyncMock() mock_client.run_tool = AsyncMock(return_value="success") # Create tool coroutine tool_coroutine = util.create_tool_coroutine("test_tool", test_schema, mock_client) # Test with positional arguments result = await tool_coroutine("Snow", 6) assert result == "success" # Verify client was called with correct field mapping mock_client.run_tool.assert_called_once_with("test_tool", arguments={"weather_main": "Snow", "top_n": 6}) @pytest.mark.asyncio async def test_tool_coroutine_mixed_args_and_conversion(self): """Test mixed positional and keyword arguments with field conversion.""" from unittest.mock import AsyncMock from pydantic import Field, create_model test_schema = create_model( "TestSchema", weather_main=(str, Field(..., description="Main weather condition")), top_n=(int, Field(..., description="Number of results")), user_id=(str, Field(..., description="User ID")), ) # Mock client mock_client = AsyncMock() mock_client.run_tool = AsyncMock(return_value="success") # Create tool coroutine tool_coroutine = util.create_tool_coroutine("test_tool", test_schema, mock_client) # Test with one positional arg and camelCase keyword args result = await tool_coroutine("Snow", topN=6, userId="user123") assert result == "success" # Verify field names were properly converted mock_client.run_tool.assert_called_once_with( "test_tool", arguments={"weather_main": "Snow", "top_n": 6, "user_id": "user123"} ) @pytest.mark.asyncio async def test_tool_coroutine_validation_error_with_conversion(self): """Test that validation errors are properly handled after field conversion.""" from unittest.mock import AsyncMock from pydantic import Field, create_model test_schema = create_model( "TestSchema", weather_main=(str, Field(..., description="Required field")), top_n=(int, Field(..., description="Required field")), ) # Mock client mock_client = AsyncMock() # Create tool coroutine tool_coroutine = util.create_tool_coroutine("test_tool", test_schema, mock_client) # Test with missing required field (should fail validation even after conversion) with pytest.raises(ValueError, match="Invalid input"): await tool_coroutine(weatherMain="Snow") # Missing topN/top_n def test_tool_func_field_conversion_sync(self): """Test that create_tool_func handles field conversion in sync context.""" from unittest.mock import AsyncMock from pydantic import Field, create_model test_schema = create_model( "TestSchema", user_name=(str, Field(..., description="User name")), max_results=(int, Field(..., description="Maximum results")), ) # Mock client mock_client = AsyncMock() mock_client.run_tool = AsyncMock(return_value="sync_result") # Create tool function tool_func = util.create_tool_func("test_tool", test_schema, mock_client) # Mock run_until_complete from async_helpers with patch("lfx.base.mcp.util.run_until_complete", return_value="sync_result") as mock_run_until_complete: # Test with camelCase fields result = tool_func(userName="testuser", maxResults=10) assert result == "sync_result" mock_run_until_complete.assert_called_once() class TestMCPUtilityFunctions: """Test utility functions from util.py that don't have dedicated test classes.""" def test_sanitize_mcp_name(self): """Test MCP name sanitization.""" assert util.sanitize_mcp_name("Test Name 123") == "test_name_123" assert util.sanitize_mcp_name(" ") == "" assert util.sanitize_mcp_name("123abc") == "_123abc" assert util.sanitize_mcp_name("Tést-😀-Námé") == "test_name" assert util.sanitize_mcp_name("a" * 100) == "a" * 46 def test_get_unique_name(self): """Test unique name generation.""" names = {"foo", "foo_1"} assert util.get_unique_name("foo", 10, names) == "foo_2" assert util.get_unique_name("bar", 10, names) == "bar" assert util.get_unique_name("longname", 4, {"long"}) == "lo_1" def test_is_valid_key_value_item(self): """Test key-value item validation.""" assert util._is_valid_key_value_item({"key": "a", "value": "b"}) is True assert util._is_valid_key_value_item({"key": "a"}) is False assert util._is_valid_key_value_item(["key", "value"]) is False assert util._is_valid_key_value_item(None) is False def test_validate_node_installation(self): """Test Node.js installation validation.""" if shutil.which("node"): assert util._validate_node_installation("npx something") == "npx something" else: with pytest.raises(ValueError, match=re.escape("Node.js is not installed")): util._validate_node_installation("npx something") assert util._validate_node_installation("echo test") == "echo test" def test_create_input_schema_from_json_schema(self): """Test JSON schema to Pydantic model conversion.""" schema = { "type": "object", "properties": { "foo": {"type": "string", "description": "desc"}, "bar": {"type": "integer"}, }, "required": ["foo"], } model_class = util.create_input_schema_from_json_schema(schema) instance = model_class(foo="abc", bar=1) assert instance.foo == "abc" assert instance.bar == 1 with pytest.raises(Exception): # noqa: B017, PT011 model_class(bar=1) # missing required field @pytest.mark.asyncio async def test_validate_connection_params(self): """Test connection parameter validation.""" # Valid parameters await util._validate_connection_params("Stdio", command="echo test") await util._validate_connection_params("SSE", url="http://test") # Invalid parameters with pytest.raises(ValueError, match="Command is required for Stdio mode"): await util._validate_connection_params("Stdio", command=None) with pytest.raises(ValueError, match="URL is required for SSE mode"): await util._validate_connection_params("SSE", url=None) with pytest.raises(ValueError, match="Invalid mode"): await util._validate_connection_params("InvalidMode") @pytest.mark.asyncio async def test_get_flow_snake_case_mocked(self): """Test flow lookup by snake case name with mocked session.""" class DummyFlow: def __init__(self, name: str, user_id: str, *, is_component: bool = False, action_name: str | None = None): self.name = name self.user_id = user_id self.is_component = is_component self.action_name = action_name class DummyExec: def __init__(self, flows: list[DummyFlow]): self._flows = flows def all(self): return self._flows class DummySession: def __init__(self, flows: list[DummyFlow]): self._flows = flows async def exec(self, stmt): # noqa: ARG002 return DummyExec(self._flows) user_id = "123e4567-e89b-12d3-a456-426614174000" flows = [DummyFlow("Test Flow", user_id), DummyFlow("Other", user_id)] # Should match sanitized name result = await util.get_flow_snake_case(util.sanitize_mcp_name("Test Flow"), user_id, DummySession(flows)) assert result is flows[0] # Should return None if not found result = await util.get_flow_snake_case("notfound", user_id, DummySession(flows)) assert result is None @pytest.mark.skip(reason="Skipping MCPStdioClientWithEverythingServer tests.") class TestMCPStdioClientWithEverythingServer: """Test MCPStdioClient with the Everything MCP server.""" @pytest.fixture def stdio_client(self): """Create a stdio client for testing.""" return MCPStdioClient() @pytest.mark.asyncio @pytest.mark.skipif(not shutil.which("npx"), reason="Node.js not available") @pytest.mark.skipif( sys.version_info >= (3, 13), reason="Temporarily disabled on Python 3.13 due to frequent timeouts with MCP Everything server", ) async def test_connect_to_everything_server(self, stdio_client): """Test connecting to the Everything MCP server.""" command = "npx -y @modelcontextprotocol/server-everything" try: # Connect to the server tools = await stdio_client.connect_to_server(command) # Verify tools were returned assert len(tools) > 0 # Find the echo tool echo_tool = None for tool in tools: if hasattr(tool, "name") and tool.name == "echo": echo_tool = tool break assert echo_tool is not None, "Echo tool not found in server tools" assert echo_tool.description is not None # Verify the echo tool has the expected input schema assert hasattr(echo_tool, "inputSchema") assert echo_tool.inputSchema is not None finally: # Clean up the connection await stdio_client.disconnect() @pytest.mark.asyncio @pytest.mark.skipif(not shutil.which("npx"), reason="Node.js not available") async def test_run_echo_tool(self, stdio_client): """Test running the echo tool from the Everything server.""" command = "npx -y @modelcontextprotocol/server-everything" try: # Connect to the server tools = await stdio_client.connect_to_server(command) # Find the echo tool echo_tool = None for tool in tools: if hasattr(tool, "name") and tool.name == "echo": echo_tool = tool break assert echo_tool is not None, "Echo tool not found" # Run the echo tool test_message = "Hello, MCP!" result = await stdio_client.run_tool("echo", {"message": test_message}) # Verify the result assert result is not None assert hasattr(result, "content") assert len(result.content) > 0 # Check that the echo worked - content should contain our message content_text = str(result.content[0]) assert test_message in content_text or "Echo:" in content_text finally: await stdio_client.disconnect() @pytest.mark.asyncio @pytest.mark.skipif(not shutil.which("npx"), reason="Node.js not available") async def test_list_all_tools(self, stdio_client): """Test listing all available tools from the Everything server.""" command = "npx -y @modelcontextprotocol/server-everything" try: # Connect to the server tools = await stdio_client.connect_to_server(command) # Verify we have multiple tools assert len(tools) >= 3 # Everything server typically has several tools # Check that tools have the expected attributes for tool in tools: assert hasattr(tool, "name") assert hasattr(tool, "description") assert hasattr(tool, "inputSchema") assert tool.name is not None assert len(tool.name) > 0 # Common tools that should be available expected_tools = ["echo"] # Echo is typically available for expected_tool in expected_tools: assert any(tool.name == expected_tool for tool in tools), f"Expected tool '{expected_tool}' not found" finally: await stdio_client.disconnect() @pytest.mark.asyncio @pytest.mark.skipif(not shutil.which("npx"), reason="Node.js not available") async def test_session_reuse(self, stdio_client): """Test that sessions are properly reused.""" command = "npx -y @modelcontextprotocol/server-everything" try: # Set session context stdio_client.set_session_context("test_session_reuse") # Connect to the server tools1 = await stdio_client.connect_to_server(command) # Connect again - should reuse the session tools2 = await stdio_client.connect_to_server(command) # Should have the same tools assert len(tools1) == len(tools2) # Run a tool to verify the session is working result = await stdio_client.run_tool("echo", {"message": "Session reuse test"}) assert result is not None finally: await stdio_client.disconnect() class TestMCPStreamableHttpClientWithDeepWikiServer: """Test MCPSseClient with the DeepWiki MCP server.""" @pytest.fixture def streamable_http_client(self): """Create an SSE client for testing.""" return MCPStreamableHttpClient() @pytest.mark.asyncio async def test_connect_to_deepwiki_server(self, streamable_http_client): """Test connecting to the DeepWiki MCP server.""" url = "https://mcp.deepwiki.com/sse" try: # Connect to the server tools = await streamable_http_client.connect_to_server(url) # Verify tools were returned assert len(tools) > 0 # Check for expected DeepWiki tools expected_tools = ["read_wiki_structure", "read_wiki_contents", "ask_question"] # Verify we have the expected tools for expected_tool in expected_tools: assert any(tool.name == expected_tool for tool in tools), f"Expected tool '{expected_tool}' not found" except Exception as e: # If the server is not accessible, skip the test pytest.skip(f"DeepWiki server not accessible: {e}") finally: await streamable_http_client.disconnect() @pytest.mark.asyncio async def test_run_wiki_structure_tool(self, streamable_http_client): """Test running the read_wiki_structure tool.""" url = "https://mcp.deepwiki.com/sse" try: # Connect to the server tools = await streamable_http_client.connect_to_server(url) # Find the read_wiki_structure tool wiki_tool = None for tool in tools: if hasattr(tool, "name") and tool.name == "read_wiki_structure": wiki_tool = tool break assert wiki_tool is not None, "read_wiki_structure tool not found" # Run the tool with a test repository (use repoName as expected by the API) result = await streamable_http_client.run_tool("read_wiki_structure", {"repoName": "microsoft/vscode"}) # Verify the result assert result is not None assert hasattr(result, "content") assert len(result.content) > 0 except Exception as e: # If the server is not accessible or the tool fails, skip the test pytest.skip(f"DeepWiki server test failed: {e}") finally: await streamable_http_client.disconnect() @pytest.mark.asyncio async def test_ask_question_tool(self, streamable_http_client): """Test running the ask_question tool.""" url = "https://mcp.deepwiki.com/sse" try: # Connect to the server tools = await streamable_http_client.connect_to_server(url) # Find the ask_question tool ask_tool = None for tool in tools: if hasattr(tool, "name") and tool.name == "ask_question": ask_tool = tool break assert ask_tool is not None, "ask_question tool not found" # Run the tool with a test question (use repoName as expected by the API) result = await streamable_http_client.run_tool( "ask_question", {"repoName": "microsoft/vscode", "question": "What is VS Code?"} ) # Verify the result assert result is not None assert hasattr(result, "content") assert len(result.content) > 0 except Exception as e: # If the server is not accessible or the tool fails, skip the test pytest.skip(f"DeepWiki server test failed: {e}") finally: await streamable_http_client.disconnect() @pytest.mark.asyncio async def test_url_validation(self, streamable_http_client): """Test URL validation for SSE connections.""" # Test valid URL valid_url = "https://mcp.deepwiki.com/sse" is_valid, error = await streamable_http_client.validate_url(valid_url) # Either valid or accessible, or rate-limited (429) which indicates server is reachable if not is_valid and "429" in error: # Rate limiting indicates the server is accessible but limiting requests # This is a transient network issue, not a test failure pytest.skip(f"DeepWiki server is rate limiting requests: {error}") assert is_valid or error == "" # Either valid or accessible # Test invalid URL invalid_url = "not_a_url" is_valid, error = await streamable_http_client.validate_url(invalid_url) assert not is_valid assert error != "" @pytest.fixture def mock_tool(self): """Create a mock MCP tool.""" tool = MagicMock() tool.name = "test_tool" tool.description = "Test tool description" tool.inputSchema = { "type": "object", "properties": {"test_param": {"type": "string", "description": "Test parameter"}}, "required": ["test_param"], } return tool @pytest.fixture def mock_session(self, mock_tool): """Create a mock ClientSession.""" session = AsyncMock() session.initialize = AsyncMock() list_tools_result = MagicMock() list_tools_result.tools = [mock_tool] session.list_tools = AsyncMock(return_value=list_tools_result) session.call_tool = AsyncMock( return_value=MagicMock(content=[MagicMock(model_dump=lambda: {"result": "success"})]) ) return session class TestMCPSseClientUnit: """Unit tests for MCPSseClient functionality.""" @pytest.fixture def sse_client(self): return MCPSseClient() @pytest.mark.asyncio async def test_client_initialization(self, sse_client): """Test that SSE client initializes correctly.""" # Client should initialize with default values assert sse_client.session is None assert sse_client._connection_params is None assert sse_client._connected is False assert sse_client._session_context is None async def test_validate_url_valid(self, sse_client): """Test URL validation with valid URL.""" with patch("httpx.AsyncClient") as mock_client: mock_response = MagicMock() mock_response.status_code = 200 mock_client.return_value.__aenter__.return_value.get.return_value = mock_response is_valid, error_msg = await sse_client.validate_url("http://test.url") assert is_valid is True assert error_msg == "" async def test_validate_url_invalid_format(self, sse_client): """Test URL validation with invalid format.""" is_valid, error_msg = await sse_client.validate_url("invalid-url") assert is_valid is False assert "Invalid URL format" in error_msg async def test_validate_url_with_404_response(self, sse_client): """Test URL validation with 404 response (should be valid for SSE).""" with patch("httpx.AsyncClient") as mock_client: mock_response = MagicMock() mock_response.status_code = 404 mock_client.return_value.__aenter__.return_value.get.return_value = mock_response is_valid, error_msg = await sse_client.validate_url("http://test.url") assert is_valid is True assert error_msg == "" async def test_connect_to_server_with_headers(self, sse_client): """Test connecting to server via SSE with custom headers.""" test_url = "http://test.url" test_headers = {"Authorization": "Bearer token123", "Custom-Header": "value"} expected_headers = {"authorization": "Bearer token123", "custom-header": "value"} # normalized with ( patch.object(sse_client, "validate_url", return_value=(True, "")), patch.object(sse_client, "_get_or_create_session") as mock_get_session, ): # Mock session mock_session = AsyncMock() mock_tool = MagicMock() mock_tool.name = "test_tool" list_tools_result = MagicMock() list_tools_result.tools = [mock_tool] mock_session.list_tools = AsyncMock(return_value=list_tools_result) mock_get_session.return_value = mock_session tools = await sse_client.connect_to_server(test_url, test_headers) assert len(tools) == 1 assert tools[0].name == "test_tool" assert sse_client._connected is True # Verify headers are stored in connection params (normalized) assert sse_client._connection_params is not None assert sse_client._connection_params["headers"] == expected_headers assert sse_client._connection_params["url"] == test_url async def test_headers_passed_to_session_manager(self, sse_client): """Test that headers are properly passed to the session manager.""" test_url = "http://test.url" expected_headers = {"authorization": "Bearer token123", "x-api-key": "secret"} # normalized sse_client._session_context = "test_context" sse_client._connection_params = { "url": test_url, "headers": expected_headers, # Use normalized headers "timeout_seconds": 30, "sse_read_timeout_seconds": 30, } with patch.object(sse_client, "_get_session_manager") as mock_get_manager: mock_manager = AsyncMock() mock_session = AsyncMock() mock_manager.get_session = AsyncMock(return_value=mock_session) mock_get_manager.return_value = mock_manager result_session = await sse_client._get_or_create_session() # Verify session manager was called with correct parameters including normalized headers mock_manager.get_session.assert_called_once_with( "test_context", sse_client._connection_params, "streamable_http" ) assert result_session == mock_session async def test_run_tool_with_retry_on_connection_error(self, sse_client): """Test that run_tool retries on connection errors.""" # Setup connection state sse_client._connected = True sse_client._connection_params = {"url": "http://test.url", "headers": {}} sse_client._session_context = "test_context" call_count = 0 async def mock_get_session_side_effect(): nonlocal call_count call_count += 1 session = AsyncMock() if call_count == 1: # First call fails with connection error from anyio import ClosedResourceError session.call_tool = AsyncMock(side_effect=ClosedResourceError()) else: # Second call succeeds mock_result = MagicMock() session.call_tool = AsyncMock(return_value=mock_result) return session with ( patch.object(sse_client, "_get_or_create_session", side_effect=mock_get_session_side_effect), patch.object(sse_client, "_get_session_manager") as mock_get_manager, ): mock_manager = AsyncMock() mock_get_manager.return_value = mock_manager result = await sse_client.run_tool("test_tool", {"param": "value"}) # Should have retried and succeeded on second attempt assert call_count == 2 assert result is not None # Should have cleaned up the failed session mock_manager._cleanup_session.assert_called_once_with("test_context") class TestMCPStructuredTool: """Test the MCPStructuredTool inner methods.""" @pytest.fixture def mock_client(self): """Create a mock MCP client.""" from unittest.mock import AsyncMock client = AsyncMock() client.run_tool = AsyncMock(return_value="tool_result") return client @pytest.fixture def test_schema(self): """Create a test Pydantic schema with snake_case fields.""" from pydantic import Field, create_model return create_model( "TestSchema", weather_main=(str, Field(..., description="Main weather condition")), top_n=(int, Field(..., description="Number of results")), user_id=(str, Field(default="default_user", description="User identifier")), ) @pytest.fixture def mcp_tool(self, test_schema, mock_client): """Create an MCPStructuredTool instance for testing.""" import json # Import the MCPStructuredTool class from the actual code # We need to recreate it here since it's defined inline in the update_tools function from langchain_core.tools import StructuredTool from lfx.base.mcp.util import create_tool_coroutine, create_tool_func class MCPStructuredTool(StructuredTool): def run(self, tool_input: str | dict, config=None, **kwargs): """Override the main run method to handle parameter conversion before validation.""" # Parse tool_input if it's a string if isinstance(tool_input, str): try: parsed_input = json.loads(tool_input) except json.JSONDecodeError: parsed_input = {"input": tool_input} else: parsed_input = tool_input or {} # Convert camelCase parameters to snake_case converted_input = self._convert_parameters(parsed_input) # Call the parent run method with converted parameters return super().run(converted_input, config=config, **kwargs) async def arun(self, tool_input: str | dict, config=None, **kwargs): """Override the main arun method to handle parameter conversion before validation.""" # Parse tool_input if it's a string if isinstance(tool_input, str): try: parsed_input = json.loads(tool_input) except json.JSONDecodeError: parsed_input = {"input": tool_input} else: parsed_input = tool_input or {} # Convert camelCase parameters to snake_case converted_input = self._convert_parameters(parsed_input) # Call the parent arun method with converted parameters return await super().arun(converted_input, config=config, **kwargs) def _convert_parameters(self, input_dict): if not input_dict or not isinstance(input_dict, dict): return input_dict from lfx.base.mcp.util import _camel_to_snake converted_dict = {} original_fields = set(self.args_schema.model_fields.keys()) for key, value in input_dict.items(): if key in original_fields: # Field exists as-is converted_dict[key] = value else: # Try to convert camelCase to snake_case snake_key = _camel_to_snake(key) if snake_key in original_fields: converted_dict[snake_key] = value else: # Keep original key converted_dict[key] = value return converted_dict return MCPStructuredTool( name="test_tool", description="Test tool for unit testing", args_schema=test_schema, func=create_tool_func("test_tool", test_schema, mock_client), coroutine=create_tool_coroutine("test_tool", test_schema, mock_client), ) def test_convert_parameters_exact_match(self, mcp_tool): """Test _convert_parameters with fields that exactly match schema.""" input_dict = {"weather_main": "Snow", "top_n": 5, "user_id": "user123"} result = mcp_tool._convert_parameters(input_dict) # Should pass through unchanged since fields match exactly assert result == {"weather_main": "Snow", "top_n": 5, "user_id": "user123"} def test_convert_parameters_camel_to_snake(self, mcp_tool): """Test _convert_parameters converts camelCase to snake_case.""" input_dict = {"weatherMain": "Rain", "topN": 10, "userId": "user456"} result = mcp_tool._convert_parameters(input_dict) # Should convert camelCase to snake_case assert result == {"weather_main": "Rain", "top_n": 10, "user_id": "user456"} def test_convert_parameters_mixed_fields(self, mcp_tool): """Test _convert_parameters with mixed exact and camelCase fields.""" input_dict = { "weather_main": "Cloudy", # Exact match "topN": 3, # CamelCase -> snake_case "userId": "user789", # CamelCase -> snake_case } result = mcp_tool._convert_parameters(input_dict) assert result == {"weather_main": "Cloudy", "top_n": 3, "user_id": "user789"} def test_convert_parameters_unknown_fields(self, mcp_tool): """Test _convert_parameters with fields not in schema.""" input_dict = {"weatherMain": "Sunny", "unknownField": "value", "anotherUnknown": 42} result = mcp_tool._convert_parameters(input_dict) # Known fields should be converted, unknown fields kept as-is assert result == {"weather_main": "Sunny", "unknownField": "value", "anotherUnknown": 42} def test_convert_parameters_empty_input(self, mcp_tool): """Test _convert_parameters with empty/None input.""" assert mcp_tool._convert_parameters({}) == {} assert mcp_tool._convert_parameters(None) is None assert mcp_tool._convert_parameters("not_a_dict") == "not_a_dict" def test_convert_parameters_preserves_value_types(self, mcp_tool): """Test _convert_parameters preserves all value types correctly.""" input_dict = { "weatherMain": "Snow", "topN": 42, "complexData": {"nested": "value", "list": [1, 2, 3], "boolean": True}, } result = mcp_tool._convert_parameters(input_dict) expected = { "weather_main": "Snow", "top_n": 42, "complexData": {"nested": "value", "list": [1, 2, 3], "boolean": True}, } assert result == expected def test_run_with_dict_input(self, mcp_tool, mock_client): """Test run method with dictionary input.""" # Test with all required fields input_data = {"weatherMain": "Snow", "topN": 5} mcp_tool.run(input_data) # Verify the mock client was called with converted parameters mock_client.run_tool.assert_called_once() call_args = mock_client.run_tool.call_args[1]["arguments"] assert call_args["weather_main"] == "Snow" assert call_args["top_n"] == 5 def test_run_with_string_input_json(self, mcp_tool, mock_client): """Test run method with valid JSON string input.""" import json input_data = json.dumps({"weatherMain": "Rain", "topN": 3}) mcp_tool.run(input_data) # Verify the mock client was called with converted parameters mock_client.run_tool.assert_called_once() call_args = mock_client.run_tool.call_args[1]["arguments"] assert call_args["weather_main"] == "Rain" assert call_args["top_n"] == 3 def test_run_with_string_input_non_json(self, mcp_tool): """Test run method with non-JSON string input.""" # This will cause a validation error since we have required fields # Let's test that the error handling works with pytest.raises(Exception): # noqa: B017, PT011 mcp_tool.run("simple string input") def test_run_with_none_input(self, mcp_tool): """Test run method with None input.""" # This will cause a validation error since we have required fields with pytest.raises(Exception): # noqa: B017, PT011 mcp_tool.run(None) @pytest.mark.asyncio async def test_arun_with_dict_input(self, mcp_tool, mock_client): """Test arun method with dictionary input.""" input_data = {"weatherMain": "Snow", "topN": 8} await mcp_tool.arun(input_data) # Verify the mock client was called with converted parameters mock_client.run_tool.assert_called_once() call_args = mock_client.run_tool.call_args[1]["arguments"] assert call_args["weather_main"] == "Snow" assert call_args["top_n"] == 8 @pytest.mark.asyncio async def test_arun_with_string_input_json(self, mcp_tool, mock_client): """Test arun method with valid JSON string input.""" import json input_data = json.dumps({"weatherMain": "Storm", "topN": 1}) await mcp_tool.arun(input_data) # Verify the mock client was called with converted parameters mock_client.run_tool.assert_called_once() call_args = mock_client.run_tool.call_args[1]["arguments"] assert call_args["weather_main"] == "Storm" assert call_args["top_n"] == 1 @pytest.mark.asyncio async def test_arun_with_string_input_non_json(self, mcp_tool): """Test arun method with non-JSON string input.""" # This will cause a validation error since we have required fields with pytest.raises(Exception): # noqa: B017, PT011 await mcp_tool.arun("async string input") @pytest.mark.asyncio async def test_arun_with_none_input(self, mcp_tool): """Test arun method with None input.""" # This will cause a validation error since we have required fields with pytest.raises(Exception): # noqa: B017, PT011 await mcp_tool.arun(None) def test_run_passes_config_and_kwargs(self, mcp_tool, mock_client): """Test that run method properly passes config and kwargs to parent.""" from unittest.mock import patch input_data = {"weatherMain": "Clear", "topN": 1} config = {"some": "config"} extra_kwargs = {"extra": "param"} # Mock run_until_complete from async_helpers with patch("lfx.base.mcp.util.run_until_complete", return_value="tool_result"): # Just verify that the method completes successfully with config/kwargs mcp_tool.run(input_data, config=config, **extra_kwargs) # Verify the tool was executed mock_client.run_tool.assert_called_once() @pytest.mark.asyncio async def test_arun_passes_config_and_kwargs(self, mcp_tool, mock_client): """Test that arun method properly passes config and kwargs to parent.""" input_data = {"weatherMain": "Hail", "topN": 2} config = {"async": "config"} extra_kwargs = {"async_extra": "param"} # Just verify that the method completes successfully with config/kwargs await mcp_tool.arun(input_data, config=config, **extra_kwargs) # Verify the tool was executed mock_client.run_tool.assert_called_once() def test_run_integration_with_validation_error(self, mcp_tool): """Test run method handles validation errors properly.""" # Input missing required field to trigger validation error input_data = {"weatherMain": "Snow"} # Missing topN with pytest.raises(Exception): # noqa: B017, PT011 mcp_tool.run(input_data) @pytest.mark.asyncio async def test_arun_integration_with_validation_error(self, mcp_tool): """Test arun method handles validation errors properly.""" # Input missing required field to trigger validation error input_data = {"weatherMain": "Rain"} # Missing topN with pytest.raises(Exception): # noqa: B017, PT011 await mcp_tool.arun(input_data) class TestSnakeToCamelConversion: """Test the _snake_to_camel function from json_schema module.""" def test_snake_to_camel_basic(self): """Test basic snake_case to camelCase conversion.""" from lfx.schema.json_schema import _snake_to_camel assert _snake_to_camel("weather_main") == "weatherMain" assert _snake_to_camel("top_n") == "topN" assert _snake_to_camel("first_name") == "firstName" assert _snake_to_camel("last_name") == "lastName" assert _snake_to_camel("user_id") == "userId" def test_snake_to_camel_single_word(self): """Test single word conversion (should remain unchanged).""" from lfx.schema.json_schema import _snake_to_camel assert _snake_to_camel("simple") == "simple" assert _snake_to_camel("name") == "name" assert _snake_to_camel("id") == "id" def test_snake_to_camel_empty_string(self): """Test empty string handling.""" from lfx.schema.json_schema import _snake_to_camel assert _snake_to_camel("") == "" def test_snake_to_camel_leading_underscores(self): """Test that leading underscores are preserved.""" from lfx.schema.json_schema import _snake_to_camel # Single leading underscore (private convention) assert _snake_to_camel("_my_variable") == "_myVariable" assert _snake_to_camel("_user_id") == "_userId" assert _snake_to_camel("_internal_name") == "_internalName" # Double leading underscore (strongly private convention) assert _snake_to_camel("__private_var") == "__privateVar" assert _snake_to_camel("__init_method") == "__initMethod" # Dunder methods (magic methods) assert _snake_to_camel("__special_method__") == "__specialMethod__" def test_snake_to_camel_trailing_underscores(self): """Test that trailing underscores are preserved.""" from lfx.schema.json_schema import _snake_to_camel # Single trailing underscore (keyword conflict avoidance) assert _snake_to_camel("class_") == "class_" assert _snake_to_camel("type_") == "type_" assert _snake_to_camel("from_address_") == "fromAddress_" # Multiple trailing underscores assert _snake_to_camel("reserved_word__") == "reservedWord__" def test_snake_to_camel_both_leading_and_trailing(self): """Test preservation of both leading and trailing underscores.""" from lfx.schema.json_schema import _snake_to_camel assert _snake_to_camel("_my_class_") == "_myClass_" assert _snake_to_camel("__private_type__") == "__privateType__" assert _snake_to_camel("_internal_method_") == "_internalMethod_" def test_snake_to_camel_only_underscores(self): """Test strings that are only underscores.""" from lfx.schema.json_schema import _snake_to_camel assert _snake_to_camel("_") == "_" assert _snake_to_camel("__") == "__" assert _snake_to_camel("___") == "___" def test_snake_to_camel_multiple_consecutive_underscores(self): """Test handling of multiple consecutive underscores in the middle.""" from lfx.schema.json_schema import _snake_to_camel # Multiple underscores should be treated as separators # Note: This tests current behavior - we may want to normalize this assert _snake_to_camel("my__double__underscore") == "myDoubleUnderscore" assert _snake_to_camel("triple___underscore") == "tripleUnderscore" def test_snake_to_camel_edge_cases(self): """Test various edge cases.""" from lfx.schema.json_schema import _snake_to_camel # Single character components assert _snake_to_camel("a_b_c") == "aBC" # Numbers in names assert _snake_to_camel("version_2_beta") == "version2Beta" assert _snake_to_camel("test_123_value") == "test123Value" # Already camelCase (no underscores) assert _snake_to_camel("alreadyCamelCase") == "alreadyCamelCase" def test_snake_to_camel_with_api_field_names(self): """Test conversion of common API field names that should preserve underscores.""" from lfx.schema.json_schema import _snake_to_camel # MongoDB-style IDs assert _snake_to_camel("_id") == "_id" # Type discriminators assert _snake_to_camel("_type") == "_type" # Metadata fields assert _snake_to_camel("_meta_data") == "_metaData" assert _snake_to_camel("_created_at") == "_createdAt"
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/base/mcp/test_mcp_util.py", "license": "MIT License", "lines": 1540, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/tests/integration/test_dynamic_import_integration.py
"""Integration tests for dynamic import refactor. Tests the dynamic import system in realistic usage scenarios to ensure the refactor doesn't break existing functionality. """ import sys import time import pytest from langflow.components.data import APIRequestComponent from langflow.components.models_and_agents import AgentComponent # Backwards compatibility alias from langflow.components.openai import OpenAIModelComponent class TestDynamicImportIntegration: """Integration tests for the dynamic import system.""" def test_component_discovery_still_works(self): """Test that component discovery mechanisms still work after refactor.""" # This tests that the existing component discovery logic # can still find and load components from langflow import components # Test that we can discover components through the main module openai_module = components.openai assert hasattr(openai_module, "OpenAIModelComponent") data_module = components.data assert hasattr(data_module, "APIRequestComponent") def test_existing_import_patterns_work(self): """Test that all existing import patterns continue to work.""" # Test direct imports import langflow.components.data as data_comp # Test module imports import langflow.components.openai as openai_comp # All should work assert OpenAIModelComponent is not None assert APIRequestComponent is not None assert AgentComponent is not None assert openai_comp.OpenAIModelComponent is not None assert data_comp.APIRequestComponent is not None def test_component_instantiation_works(self): """Test that components can still be instantiated normally.""" # Test that we can create component instances # (Note: Some components may require specific initialization parameters) from langflow.components.helpers import CalculatorComponent # Should be able to access the class assert CalculatorComponent is not None assert callable(CalculatorComponent) def test_template_creation_compatibility(self): """Test that template creation still works with dynamic imports.""" # Test accessing component attributes needed for templates # Components should have all necessary attributes for template creation assert hasattr(OpenAIModelComponent, "__name__") assert hasattr(OpenAIModelComponent, "__module__") assert hasattr(OpenAIModelComponent, "display_name") assert isinstance(OpenAIModelComponent.display_name, str) assert OpenAIModelComponent.display_name assert hasattr(OpenAIModelComponent, "description") assert isinstance(OpenAIModelComponent.description, str) assert OpenAIModelComponent.description assert hasattr(OpenAIModelComponent, "icon") assert isinstance(OpenAIModelComponent.icon, str) assert OpenAIModelComponent.icon assert hasattr(OpenAIModelComponent, "inputs") assert isinstance(OpenAIModelComponent.inputs, list) assert len(OpenAIModelComponent.inputs) > 0 # Check that each input has required attributes for input_field in OpenAIModelComponent.inputs: assert hasattr(input_field, "name"), f"Input {input_field} missing 'name' attribute" assert hasattr(input_field, "display_name"), f"Input {input_field} missing 'display_name' attribute" def test_multiple_import_styles_same_result(self): """Test that different import styles yield the same component.""" # Import the same component in different ways from langflow import components from langflow.components.openai import OpenAIModelComponent as DirectImport dynamic_import = components.openai.OpenAIModelComponent import langflow.components.openai as openai_module module_import = openai_module.OpenAIModelComponent # All three should be the exact same class object assert DirectImport is dynamic_import assert dynamic_import is module_import assert DirectImport is module_import def test_startup_performance_improvement(self): """Test that startup time is improved with lazy loading.""" # This test measures the difference in import time # Fresh modules to test startup behavior modules_to_clean = [ "langflow.components.vectorstores", "langflow.components.tools", "langflow.components.langchain_utilities", ] for module_name in modules_to_clean: if module_name in sys.modules: del sys.modules[module_name] # Time the import of a large module start_time = time.time() from langflow.components import chroma import_time = time.time() - start_time # Import time should be very fast (just loading the __init__.py) assert import_time < 0.1 # Should be well under 100ms # Test that we can access a component (it may already be cached from previous tests) # This is expected behavior in a test suite where components get cached # Now access a component - this should trigger loading start_time = time.time() chroma_component = chroma.ChromaVectorStoreComponent access_time = time.time() - start_time assert chroma_component is not None # Access time should still be reasonable assert access_time < 2.0 # Should be under 2 seconds def test_memory_usage_efficiency(self): """Test that memory usage is more efficient with lazy loading.""" from langflow.components import processing # Count currently loaded components initial_component_count = len([k for k in processing.__dict__ if k.endswith("Component")]) # Access just one component combine_text = processing.CombineTextComponent assert combine_text is not None # At least one more component should be loaded now after_one_access = len([k for k in processing.__dict__ if k.endswith("Component")]) assert after_one_access >= initial_component_count # Access another component split_text = processing.SplitTextComponent assert split_text is not None # Should have at least one more component loaded after_two_access = len([k for k in processing.__dict__ if k.endswith("Component")]) assert after_two_access >= after_one_access def test_error_handling_in_realistic_scenarios(self): """Test error handling in realistic usage scenarios.""" from langflow import components # Test accessing non-existent component category with pytest.raises(AttributeError): _ = components.nonexistent_category # Test accessing non-existent component in valid category with pytest.raises(AttributeError): _ = components.openai.NonExistentComponent def test_ide_autocomplete_support(self): """Test that IDE autocomplete support still works.""" import langflow.components.openai as openai_components from langflow import components # __dir__ should return all available components/modules main_dir = dir(components) assert "openai" in main_dir assert "data" in main_dir assert "models_and_agents" in main_dir openai_dir = dir(openai_components) assert "OpenAIModelComponent" in openai_dir assert "OpenAIEmbeddingsComponent" in openai_dir def test_concurrent_access(self): """Test that concurrent access to components works correctly.""" import threading from langflow.components import helpers results = [] errors = [] def access_component(): try: component = helpers.CalculatorComponent results.append(component) except Exception as e: errors.append(e) # Create multiple threads accessing the same component threads = [] for _ in range(5): thread = threading.Thread(target=access_component) threads.append(thread) thread.start() # Wait for all threads to complete for thread in threads: thread.join() # Should have no errors assert len(errors) == 0 assert len(results) == 5 # All results should be the same component class first_result = results[0] for result in results[1:]: assert result is first_result def test_circular_import_prevention(self): """Test that the refactor doesn't introduce circular imports.""" # This test ensures that importing components doesn't create # circular dependency issues # These imports should work without circular import errors from langflow import components from langflow.components import openai # Access components in different orders model1 = components.openai.OpenAIModelComponent model2 = openai.OpenAIModelComponent model3 = OpenAIModelComponent # All should be the same assert model1 is model2 is model3 def test_large_scale_component_access(self): """Test accessing many components doesn't cause issues.""" from langflow.components import datastax # Access multiple components rapidly components_accessed = [] component_names = [ "AstraDBVectorStoreComponent", "AstraDBChatComponent", "AstraDBToolComponent", "AstraDBCQLToolComponent", "AstraAssistantManager", ] for name in component_names: if hasattr(datastax, name): component = getattr(datastax, name) components_accessed.append(component) # Should have accessed multiple components without issues assert len(components_accessed) > 0 # All should be different classes assert len(set(components_accessed)) == len(components_accessed) def test_component_metadata_preservation(self): """Test that component metadata is preserved after dynamic loading.""" # Component should have all expected metadata assert hasattr(OpenAIModelComponent, "__name__") assert hasattr(OpenAIModelComponent, "__module__") assert hasattr(OpenAIModelComponent, "__doc__") # Module path should be correct assert "openai" in OpenAIModelComponent.__module__ def test_backwards_compatibility_comprehensive(self): """Comprehensive test of backwards compatibility.""" # Test all major import patterns that should still work # 1. Direct component imports from langflow.components.data import APIRequestComponent assert AgentComponent is not None assert APIRequestComponent is not None # 2. Module imports # 3. Main module access import langflow.components as comp import langflow.components.helpers as helpers_mod import langflow.components.openai as openai_mod # 4. Nested access nested_component = comp.openai.OpenAIModelComponent direct_component = openai_mod.OpenAIModelComponent # All patterns should work and yield consistent results assert openai_mod.OpenAIModelComponent is not None assert helpers_mod.CalculatorComponent is not None assert nested_component is direct_component if __name__ == "__main__": pytest.main([__file__, "-v"])
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/integration/test_dynamic_import_integration.py", "license": "MIT License", "lines": 231, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/tests/unit/components/test_all_modules_importable.py
"""Test to ensure all component modules are importable after dynamic import refactor. This test validates that every component module can be imported successfully and that all components listed in __all__ can be accessed. This test suite includes: 1. Dynamic import system tests (lazy loading, caching, error handling) 2. Direct module import tests (catches actual import errors, syntax errors, deprecated imports) 3. AST-based code quality checks (deprecated import patterns) 4. Async parallel testing for performance The combination of dynamic and direct import testing ensures both the import system functionality AND the actual module code quality are validated. """ import asyncio import importlib import pkgutil import pytest from langflow import components class TestAllModulesImportable: """Test that all component modules are importable.""" def test_all_component_categories_importable(self): """Test that all component categories in __all__ can be imported.""" failed_imports = [] for category_name in components.__all__: try: category_module = getattr(components, category_name) assert category_module is not None, f"Category {category_name} is None" # Verify it's actually a module assert hasattr(category_module, "__name__"), f"Category {category_name} is not a module" except Exception as e: failed_imports.append(f"{category_name}: {e!s}") if failed_imports: pytest.fail(f"Failed to import categories: {failed_imports}") def test_all_components_in_categories_importable(self): """Test that all components in each category's __all__ can be imported.""" failed_imports = [] successful_imports = 0 print(f"Testing component imports across {len(components.__all__)} categories") # noqa: T201 for category_name in components.__all__: try: category_module = getattr(components, category_name) if hasattr(category_module, "__all__"): category_components = len(category_module.__all__) print(f"Testing {category_components} components in {category_name}") # noqa: T201 for component_name in category_module.__all__: try: component = getattr(category_module, component_name) assert component is not None, f"Component {component_name} is None" assert callable(component), f"Component {component_name} is not callable" successful_imports += 1 except Exception as e: failed_imports.append(f"{category_name}.{component_name}: {e!s}") print(f"FAILED: {category_name}.{component_name}: {e!s}") # noqa: T201 else: # Category doesn't have __all__, skip print(f"Skipping {category_name} (no __all__ attribute)") # noqa: T201 continue except Exception as e: failed_imports.append(f"Category {category_name}: {e!s}") print(f"FAILED: Category {category_name}: {e!s}") # noqa: T201 print(f"Successfully imported {successful_imports} components") # noqa: T201 if failed_imports: print(f"Failed imports ({len(failed_imports)}):") # noqa: T201 for failure in failed_imports[:10]: # Show first 10 failures print(f" - {failure}") # noqa: T201 if len(failed_imports) > 10: print(f" ... and {len(failed_imports) - 10} more") # noqa: T201 pytest.fail(f"Failed to import {len(failed_imports)} components") def test_dynamic_imports_mapping_complete(self): """Test that _dynamic_imports mapping is complete for all categories.""" failed_mappings = [] for category_name in components.__all__: try: category_module = getattr(components, category_name) if hasattr(category_module, "__all__") and hasattr(category_module, "_dynamic_imports"): category_all = set(category_module.__all__) dynamic_imports_keys = set(category_module._dynamic_imports.keys()) # Check that all items in __all__ have corresponding _dynamic_imports entries missing_in_dynamic = category_all - dynamic_imports_keys if missing_in_dynamic: failed_mappings.append(f"{category_name}: Missing in _dynamic_imports: {missing_in_dynamic}") # Check that all _dynamic_imports keys are in __all__ missing_in_all = dynamic_imports_keys - category_all if missing_in_all: failed_mappings.append(f"{category_name}: Missing in __all__: {missing_in_all}") except Exception as e: failed_mappings.append(f"{category_name}: Error checking mappings: {e!s}") if failed_mappings: pytest.fail(f"Inconsistent mappings: {failed_mappings}") def test_backward_compatibility_imports(self): """Test that traditional import patterns still work.""" # Test some key imports that should always work traditional_imports = [ ("langflow.components.openai", "OpenAIModelComponent"), ("langflow.components.anthropic", "AnthropicModelComponent"), ("langflow.components.data", "APIRequestComponent"), ("langflow.components.models_and_agents", "AgentComponent"), ("langflow.components.helpers", "CalculatorComponent"), ] failed_imports = [] for module_name, component_name in traditional_imports: try: module = importlib.import_module(module_name) component = getattr(module, component_name) assert component is not None assert callable(component) except Exception as e: failed_imports.append(f"{module_name}.{component_name}: {e!s}") if failed_imports: pytest.fail(f"Traditional imports failed: {failed_imports}") def test_component_modules_have_required_attributes(self): """Test that component modules have required attributes for dynamic loading.""" failed_modules = [] for category_name in components.__all__: try: category_module = getattr(components, category_name) # Check for required attributes required_attrs = ["__all__"] failed_modules.extend( f"{category_name}: Missing required attribute {attr}" for attr in required_attrs if not hasattr(category_module, attr) ) # Check that if it has dynamic imports, it has the pattern if hasattr(category_module, "_dynamic_imports"): if not hasattr(category_module, "__getattr__"): failed_modules.append(f"{category_name}: Has _dynamic_imports but no __getattr__") if not hasattr(category_module, "__dir__"): failed_modules.append(f"{category_name}: Has _dynamic_imports but no __dir__") except Exception as e: failed_modules.append(f"{category_name}: Error checking attributes: {e!s}") if failed_modules: pytest.fail(f"Module attribute issues: {failed_modules}") def test_no_circular_imports(self): """Test that there are no circular import issues.""" # Test importing in different orders to catch circular imports import_orders = [ ["models_and_agents", "data", "openai"], ["openai", "models_and_agents", "data"], ["data", "openai", "models_and_agents"], ] for order in import_orders: try: for category_name in order: category_module = getattr(components, category_name) # Access a component to trigger dynamic import if hasattr(category_module, "__all__") and category_module.__all__: first_component_name = category_module.__all__[0] getattr(category_module, first_component_name) except Exception as e: pytest.fail(f"Circular import issue with order {order}: {e!s}") def test_component_access_caching(self): """Test that component access caching works correctly.""" # Access the same component multiple times and ensure caching works test_cases = [ ("openai", "OpenAIModelComponent"), ("data", "APIRequestComponent"), ("helpers", "CalculatorComponent"), ] for category_name, component_name in test_cases: category_module = getattr(components, category_name) # First access component1 = getattr(category_module, component_name) # Component should now be cached in module globals assert component_name in category_module.__dict__ # Second access should return the same object component2 = getattr(category_module, component_name) assert component1 is component2, f"Caching failed for {category_name}.{component_name}" def test_error_handling_for_missing_components(self): """Test that appropriate errors are raised for missing components.""" test_cases = [ ("openai", "NonExistentComponent"), ("data", "AnotherNonExistentComponent"), ] for category_name, component_name in test_cases: category_module = getattr(components, category_name) with pytest.raises(AttributeError, match=f"has no attribute '{component_name}'"): getattr(category_module, component_name) def test_dir_functionality(self): """Test that __dir__ functionality works for all modules.""" # Test main components module main_dir = dir(components) assert "openai" in main_dir assert "data" in main_dir assert "models_and_agents" in main_dir # Test category modules for category_name in ["openai", "data", "helpers"]: category_module = getattr(components, category_name) category_dir = dir(category_module) # Should include all components from __all__ if hasattr(category_module, "__all__"): for component_name in category_module.__all__: assert component_name in category_dir, f"{component_name} missing from dir({category_name})" def test_module_metadata_preservation(self): """Test that module metadata is preserved after dynamic loading.""" test_components = [ ("openai", "OpenAIModelComponent"), ("anthropic", "AnthropicModelComponent"), ("data", "APIRequestComponent"), ] for category_name, component_name in test_components: category_module = getattr(components, category_name) component = getattr(category_module, component_name) # Check that component has expected metadata assert hasattr(component, "__name__") assert hasattr(component, "__module__") assert component.__name__ == component_name assert category_name in component.__module__ class TestSpecificModulePatterns: """Test specific module patterns and edge cases.""" def test_empty_init_modules(self): """Test modules that might have empty __init__.py files.""" # These modules might have empty __init__.py files in the original structure potentially_empty_modules = [ "chains", "output_parsers", "textsplitters", "toolkits", "link_extractors", "documentloaders", ] for module_name in potentially_empty_modules: if module_name in components.__all__: try: module = getattr(components, module_name) # Should be able to import even if empty assert module is not None except Exception as e: pytest.fail(f"Failed to import potentially empty module {module_name}: {e}") def test_platform_specific_imports(self): """Test platform-specific imports like NVIDIA Windows components.""" # Test NVIDIA module which has platform-specific logic nvidia_module = components.nvidia assert nvidia_module is not None # Should have basic components regardless of platform assert "NVIDIAModelComponent" in nvidia_module.__all__ # Should be able to access components nvidia_model = nvidia_module.NVIDIAModelComponent assert nvidia_model is not None def test_large_modules_import_efficiently(self): """Test that large modules with many components import efficiently.""" import time # Test large modules large_modules = ["data", "processing", "langchain_utilities"] for module_name in large_modules: if module_name in components.__all__: start_time = time.time() module = getattr(components, module_name) import_time = time.time() - start_time # Initial import should be fast (just loading __init__.py) assert import_time < 0.5, f"Module {module_name} took too long to import: {import_time}s" # Should have components available assert hasattr(module, "__all__") assert len(module.__all__) > 0 class TestDirectModuleImports: """Test direct module imports to catch actual import errors. These tests bypass the lazy import system and directly import module files to catch issues like: - Deprecated import paths (e.g., langchain.embeddings.base) - Syntax errors - Missing imports - Circular imports """ @pytest.mark.asyncio async def test_all_lfx_component_modules_directly_importable(self): """Test that all lfx component modules can be directly imported. This bypasses the lazy import system to catch actual import errors like deprecated imports, syntax errors, etc. Uses async for 3-5x performance improvement. """ try: import lfx.components as components_pkg except ImportError: pytest.skip("lfx.components not available") # Collect all module names module_names = [] for _, modname, _ in pkgutil.walk_packages(components_pkg.__path__, prefix=components_pkg.__name__ + "."): # Skip deactivated components if "deactivated" in modname: continue # Skip private modules if any(part.startswith("_") for part in modname.split(".")): continue module_names.append(modname) # Define async function to import a single module async def import_module_async(modname): """Import a module asynchronously.""" try: # Run import in thread pool to avoid blocking await asyncio.to_thread(importlib.import_module, modname) except ImportError as e: error_msg = str(e) # Check if it's a missing optional dependency (expected) if any( pkg in error_msg for pkg in [ "agentics", "agentics-py", "crewai", "langchain_openai", "langchain_anthropic", "langchain_google", "langchain_cohere", "langchain_pinecone", "langchain_chroma", "qdrant_client", "pymongo", "cassandra", "weaviate", "pinecone", "chromadb", "redis", "elasticsearch", "langchain_community", ] ): return ("skipped", modname, "missing optional dependency") return ("failed", modname, error_msg) except Exception as e: return ("failed", modname, f"{type(e).__name__}: {e}") else: return ("success", modname, None) # Import all modules in parallel results = await asyncio.gather(*[import_module_async(modname) for modname in module_names]) # Process results failed_imports = [] successful_imports = 0 skipped_modules = [] for status, modname, error in results: if status == "success": successful_imports += 1 elif status == "skipped": skipped_modules.append(f"{modname} ({error})") else: # failed failed_imports.append(f"{modname}: {error}") if failed_imports: failure_msg = ( f"Failed to import {len(failed_imports)} component modules. " f"Successfully imported {successful_imports} modules. " f"Skipped {len(skipped_modules)} modules.\n\n" f"Failed imports:\n" + "\n".join(f" • {f}" for f in failed_imports) + "\n\n" "This may indicate deprecated imports, syntax errors, or other issues." ) pytest.fail(failure_msg) def test_no_deprecated_langchain_imports(self): """Test that no component uses deprecated langchain import paths. This specifically catches issues like the Qdrant bug where 'from langchain.embeddings.base import Embeddings' was used instead of 'from langchain_core.embeddings import Embeddings'. Uses AST parsing to scan all Python files for deprecated patterns. """ import ast from pathlib import Path try: import lfx lfx_path = Path(lfx.__file__).parent except ImportError: pytest.skip("lfx package not found") components_path = lfx_path / "components" if not components_path.exists(): pytest.skip("lfx.components directory not found") deprecated_imports = [] # Known deprecated import patterns deprecated_patterns = [ ("langchain.embeddings.base", "langchain_core.embeddings"), ("langchain.llms.base", "langchain_core.language_models.llms"), ("langchain.chat_models.base", "langchain_core.language_models.chat_models"), ("langchain.schema", "langchain_core.messages"), ("langchain.vectorstores", "langchain_community.vectorstores"), ("langchain.document_loaders", "langchain_community.document_loaders"), ("langchain.text_splitter", "langchain_text_splitters"), ] # Walk through all Python files in components for py_file in components_path.rglob("*.py"): if py_file.name.startswith("_"): continue try: content = py_file.read_text(encoding="utf-8") tree = ast.parse(content, filename=str(py_file)) for node in ast.walk(tree): if isinstance(node, ast.ImportFrom): module = node.module or "" # Check against deprecated patterns for deprecated, replacement in deprecated_patterns: if module.startswith(deprecated): relative_path = py_file.relative_to(lfx_path) deprecated_imports.append( f"{relative_path}:{node.lineno}: " f"Uses deprecated '{deprecated}' - should use '{replacement}'" ) except Exception: # noqa: S112 # Skip files that can't be parsed continue if deprecated_imports: failure_msg = ( f"Found {len(deprecated_imports)} deprecated langchain imports.\n\n" f"Deprecated imports:\n" + "\n".join(f" • {imp}" for imp in deprecated_imports) + "\n\n" "Please update to use current import paths." ) pytest.fail(failure_msg) @pytest.mark.asyncio async def test_vector_store_components_directly_importable(self): """Test that all vector store components can be directly imported. Vector stores are particularly prone to import issues due to their many optional dependencies. This test ensures they can be imported when dependencies are available. """ vector_store_components = [ ("lfx.components.chroma", "ChromaVectorStoreComponent"), ("lfx.components.pinecone", "PineconeVectorStoreComponent"), ("lfx.components.qdrant", "QdrantVectorStoreComponent"), ("lfx.components.weaviate", "WeaviateVectorStoreComponent"), ("lfx.components.vectorstores", "LocalDBComponent"), ] async def test_vector_store_import(module_name, class_name): """Test import of a single vector store component.""" try: def _import(): module = importlib.import_module(module_name) component_class = getattr(module, class_name) assert isinstance(component_class, type) await asyncio.to_thread(_import) except (ImportError, AttributeError) as e: error_msg = str(e) # Check if it's a missing optional dependency if any( pkg in error_msg for pkg in [ "langchain_chroma", "langchain_pinecone", "qdrant_client", "weaviate", "chromadb", "pinecone", "langchain_community", ] ): return ("skipped", module_name, class_name, "missing optional dependency") return ("failed", module_name, class_name, error_msg) else: return ("success", module_name, class_name, None) # Test all vector stores in parallel results = await asyncio.gather(*[test_vector_store_import(mod, cls) for mod, cls in vector_store_components]) # Process results failed_imports = [] for status, module_name, class_name, error in results: if status == "failed": failed_imports.append(f"{module_name}.{class_name}: {error}") if failed_imports: failure_msg = ( f"Failed to import {len(failed_imports)} vector store components.\n\n" f"Failed imports:\n" + "\n".join(f" • {f}" for f in failed_imports) ) pytest.fail(failure_msg) def test_qdrant_component_directly_importable(self): """Regression test for Qdrant component import (deprecated import fix). This test specifically validates that the Qdrant component can be imported after fixing the deprecated langchain.embeddings.base import. """ try: from lfx.components.qdrant import QdrantVectorStoreComponent # Verify it's a class assert isinstance(QdrantVectorStoreComponent, type) # Verify it has expected attributes assert hasattr(QdrantVectorStoreComponent, "display_name") assert QdrantVectorStoreComponent.display_name == "Qdrant" except ImportError as e: if "qdrant_client" in str(e) or "langchain_community" in str(e): pytest.skip("Qdrant dependencies not installed (expected in test environment)") pytest.fail(f"Failed to import QdrantVectorStoreComponent: {e}") except AttributeError as e: if "Could not import" in str(e): pytest.skip("Qdrant dependencies not installed (expected in test environment)") raise if __name__ == "__main__": pytest.main([__file__, "-v"])
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/components/test_all_modules_importable.py", "license": "MIT License", "lines": 474, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:scripts/generate_coverage_config.py
#!/usr/bin/env python3 """Script to generate a custom .coveragerc file for backend testing. This script: 1. Reads SIDEBAR_BUNDLES from frontend styleUtils.ts to get bundled component names 2. Scans backend components for files containing 'legacy = True' 3. Generates a .coveragerc file that omits these paths from coverage reporting Usage: python scripts/generate_coverage_config.py """ import re from pathlib import Path def extract_sidebar_bundles(frontend_path: Path) -> set[str]: """Extract component names from SIDEBAR_BUNDLES in styleUtils.ts.""" style_utils_path = frontend_path / "src/utils/styleUtils.ts" if not style_utils_path.exists(): print(f"Warning: styleUtils.ts not found at {style_utils_path}") return set() bundle_names = set() with style_utils_path.open(encoding="utf-8") as f: content = f.read() # Find SIDEBAR_BUNDLES array sidebar_match = re.search(r"export const SIDEBAR_BUNDLES = \[(.*?)\];", content, re.DOTALL) if not sidebar_match: print("Warning: SIDEBAR_BUNDLES not found in styleUtils.ts") return set() bundles_content = sidebar_match.group(1) # Extract name fields using regex name_matches = re.findall(r'name:\s*["\']([^"\']+)["\']', bundles_content) for name in name_matches: bundle_names.add(name) print(f"Found {len(bundle_names)} bundled components from SIDEBAR_BUNDLES") return bundle_names def find_legacy_components(backend_components_path: Path) -> set[str]: """Find Python files containing 'legacy = True'.""" legacy_files = set() if not backend_components_path.exists(): print(f"Warning: Backend components path not found: {backend_components_path}") return set() # Walk through all Python files in components directory for py_file in backend_components_path.rglob("*.py"): try: with py_file.open(encoding="utf-8") as f: content = f.read() # Check if file contains 'legacy = True' if re.search(r"\blegacy\s*=\s*True\b", content): # Get relative path from components directory rel_path = py_file.relative_to(backend_components_path) legacy_files.add(str(rel_path)) except (UnicodeDecodeError, PermissionError) as e: print(f"Warning: Could not read {py_file}: {e}") continue print(f"Found {len(legacy_files)} legacy component files") return legacy_files def generate_coveragerc(bundle_names: set[str], legacy_files: set[str], output_path: Path): """Generate .coveragerc file with omit patterns.""" # Base coveragerc content config_content = """# Auto-generated .coveragerc file # Generated by scripts/generate_coverage_config.py # Do not edit manually - changes will be overwritten [run] source = src/backend/base/langflow omit = # Test files */tests/* */test_* */*test* # Migration files */alembic/* */migrations/* # Cache and build files */__pycache__/* */.* # Init files (typically just imports) */__init__.py # Deactivate Components */components/deactivated/* """ # Add bundled components to omit list if bundle_names: config_content += " # Bundled components from SIDEBAR_BUNDLES\n" for bundle_name in sorted(bundle_names): config_content += f" */components/{bundle_name}/*\n" config_content += "\n" # Add legacy components to omit list if legacy_files: config_content += " # Legacy components (contain 'legacy = True')\n" for legacy_file in sorted(legacy_files): # Convert relative path to omit pattern omit_pattern = f" */components/{legacy_file}\n" config_content += omit_pattern config_content += """ # Note: [report] and [html] sections omitted for Codecov compatibility # Codecov handles its own reporting and ignores these sections """ # Write the config file output_path.parent.mkdir(parents=True, exist_ok=True) with output_path.open("w", encoding="utf-8") as f: f.write(config_content) print(f"Generated .coveragerc at {output_path}") print(f" - Omitting {len(bundle_names)} bundled component directories") print(f" - Omitting {len(legacy_files)} legacy component files") def main(): """Main function.""" # Determine project root (script is in scripts/ directory) script_dir = Path(__file__).parent project_root = script_dir.parent # Paths frontend_path = project_root / "src" / "frontend" backend_components_path = project_root / "src" / "backend" / "base" / "langflow" / "components" output_path = project_root / "src" / "backend" / ".coveragerc" print(f"Project root: {project_root}") print(f"Frontend path: {frontend_path}") print(f"Backend components path: {backend_components_path}") print(f"Output path: {output_path}") print() # Extract bundled component names bundle_names = extract_sidebar_bundles(frontend_path) # Find legacy components legacy_files = find_legacy_components(backend_components_path) # Generate .coveragerc file generate_coveragerc(bundle_names, legacy_files, output_path) print("\nDone! You can now run backend tests with coverage using:") print("cd src/backend && python -m pytest --cov=src/backend/base/langflow --cov-config=.coveragerc") if __name__ == "__main__": main()
{ "repo_id": "langflow-ai/langflow", "file_path": "scripts/generate_coverage_config.py", "license": "MIT License", "lines": 125, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
langflow-ai/langflow:src/backend/tests/unit/custom/component/test_component_loading_fix.py
"""Tests for the component loading fix that filters out BASE_COMPONENTS_PATH from custom components. - BASE_COMPONENTS_PATH is properly filtered out from custom components paths - Lazy loading mode works correctly - Custom components are loaded only from valid custom paths - No regression in existing functionality """ import asyncio from unittest.mock import AsyncMock, MagicMock, patch import pytest from lfx.interface.components import ( component_cache, get_and_cache_all_types_dict, ) from lfx.services.settings.base import BASE_COMPONENTS_PATH from lfx.services.settings.service import SettingsService class TestComponentLoadingFix: """Test suite for the component loading fix that filters BASE_COMPONENTS_PATH.""" @pytest.fixture def mock_settings_service(self): """Create a mock settings service with configurable options.""" settings_service = MagicMock(spec=SettingsService) settings_service.settings = MagicMock() settings_service.settings.lazy_load_components = False settings_service.settings.components_path = [] return settings_service @pytest.fixture def mock_custom_paths(self): """Create mock custom component paths.""" return ["/custom/path1", "/custom/path2"] @pytest.fixture def mock_langflow_components(self): """Create mock langflow components response.""" return { "components": { "category1": { "Component1": {"display_name": "Component1", "type": "category1"}, "Component2": {"display_name": "Component2", "type": "category1"}, }, "category2": { "Component3": {"display_name": "Component3", "type": "category2"}, }, } } @pytest.fixture def mock_custom_components(self): """Create mock custom components response.""" return { "custom_category": { "CustomComponent1": {"display_name": "CustomComponent1", "type": "custom_category"}, "CustomComponent2": {"display_name": "CustomComponent2", "type": "custom_category"}, } } @pytest.fixture(autouse=True) def clear_component_cache(self): """Clear component cache before each test.""" component_cache.all_types_dict = None yield component_cache.all_types_dict = None @pytest.mark.asyncio async def test_base_components_path_filtering( self, mock_settings_service, mock_langflow_components, mock_custom_components ): """Test that BASE_COMPONENTS_PATH is properly filtered out from custom components paths.""" # Setup: Include BASE_COMPONENTS_PATH in the components_path list mock_settings_service.settings.components_path = [BASE_COMPONENTS_PATH, "/custom/path1", "/custom/path2"] mock_settings_service.settings.lazy_load_components = False with ( patch("lfx.interface.components.import_langflow_components", return_value=mock_langflow_components), patch("lfx.interface.components.aget_all_types_dict") as mock_aget_all_types_dict, ): # Mock aget_all_types_dict to return custom components mock_aget_all_types_dict.return_value = mock_custom_components # Execute the function result = await get_and_cache_all_types_dict(mock_settings_service) # Verify that aget_all_types_dict was called with filtered paths (BASE_COMPONENTS_PATH excluded) mock_aget_all_types_dict.assert_called_once_with(["/custom/path1", "/custom/path2"]) # Verify result contains both langflow and custom components assert "category1" in result assert "category2" in result assert "custom_category" in result assert "Component1" in result["category1"] assert "CustomComponent1" in result["custom_category"] @pytest.mark.asyncio async def test_only_base_components_path_in_list(self, mock_settings_service, mock_langflow_components): """Test behavior when components_path contains only BASE_COMPONENTS_PATH.""" # Setup: Only BASE_COMPONENTS_PATH in the list mock_settings_service.settings.components_path = [BASE_COMPONENTS_PATH] mock_settings_service.settings.lazy_load_components = False with ( patch("lfx.interface.components.import_langflow_components", return_value=mock_langflow_components), patch("lfx.interface.components.aget_all_types_dict") as mock_aget_all_types_dict, ): # Execute the function result = await get_and_cache_all_types_dict(mock_settings_service) # Verify that aget_all_types_dict was NOT called (no custom paths after filtering) mock_aget_all_types_dict.assert_not_called() # Verify result contains only langflow components assert "category1" in result assert "category2" in result assert "Component1" in result["category1"] assert "Component3" in result["category2"] @pytest.mark.asyncio async def test_empty_components_path(self, mock_settings_service, mock_langflow_components): """Test behavior when components_path is empty.""" # Setup: Empty components_path mock_settings_service.settings.components_path = [] mock_settings_service.settings.lazy_load_components = False with ( patch("lfx.interface.components.import_langflow_components", return_value=mock_langflow_components), patch("lfx.interface.components.aget_all_types_dict") as mock_aget_all_types_dict, ): # Execute the function result = await get_and_cache_all_types_dict(mock_settings_service) # Verify that aget_all_types_dict was NOT called mock_aget_all_types_dict.assert_not_called() # Verify result contains only langflow components assert "category1" in result assert "category2" in result assert "Component1" in result["category1"] @pytest.mark.asyncio async def test_none_components_path(self, mock_settings_service, mock_langflow_components): """Test behavior when components_path is None.""" # Setup: None components_path mock_settings_service.settings.components_path = None mock_settings_service.settings.lazy_load_components = False with ( patch("lfx.interface.components.import_langflow_components", return_value=mock_langflow_components), patch("lfx.interface.components.aget_all_types_dict") as mock_aget_all_types_dict, ): # Execute the function result = await get_and_cache_all_types_dict(mock_settings_service) # Verify that aget_all_types_dict was NOT called mock_aget_all_types_dict.assert_not_called() # Verify result contains only langflow components assert "category1" in result assert "category2" in result @pytest.mark.asyncio async def test_lazy_loading_mode_with_base_path_filtering(self, mock_settings_service, mock_langflow_components): """Test that lazy loading mode uses aget_component_metadata with filtered paths.""" # Setup: Enable lazy loading and include BASE_COMPONENTS_PATH mock_settings_service.settings.lazy_load_components = True mock_settings_service.settings.components_path = [BASE_COMPONENTS_PATH, "/custom/path1"] mock_metadata = { "custom_category": { "CustomComponent1": {"display_name": "CustomComponent1", "type": "custom_category"}, } } with ( patch("lfx.interface.components.import_langflow_components", return_value=mock_langflow_components), patch("lfx.interface.components.aget_component_metadata", return_value=mock_metadata) as mock_aget_metadata, ): # Execute the function result = await get_and_cache_all_types_dict(mock_settings_service) # Verify that aget_component_metadata was called with the full path (not filtered in lazy mode) mock_aget_metadata.assert_called_once_with([BASE_COMPONENTS_PATH, "/custom/path1"]) # Verify result contains both langflow and custom components assert "category1" in result assert "custom_category" in result @pytest.mark.asyncio async def test_multiple_custom_paths_with_base_path( self, mock_settings_service, mock_langflow_components, mock_custom_components ): """Test filtering with multiple custom paths and BASE_COMPONENTS_PATH.""" # Setup: Multiple paths including BASE_COMPONENTS_PATH custom_paths = ["/path1", BASE_COMPONENTS_PATH, "/path2", "/path3"] mock_settings_service.settings.components_path = custom_paths mock_settings_service.settings.lazy_load_components = False with ( patch("lfx.interface.components.import_langflow_components", return_value=mock_langflow_components), patch( "lfx.interface.components.aget_all_types_dict", return_value=mock_custom_components ) as mock_aget_all_types_dict, ): # Execute the function result = await get_and_cache_all_types_dict(mock_settings_service) # Verify that aget_all_types_dict was called with filtered paths expected_filtered_paths = ["/path1", "/path2", "/path3"] mock_aget_all_types_dict.assert_called_once_with(expected_filtered_paths) # Verify result structure assert isinstance(result, dict) assert "category1" in result # From langflow components assert "custom_category" in result # From custom components @pytest.mark.asyncio async def test_component_merging_logic(self, mock_settings_service, mock_langflow_components): """Test that langflow and custom components are properly merged.""" # Setup mock_settings_service.settings.components_path = ["/custom/path1"] mock_settings_service.settings.lazy_load_components = False # Create overlapping component names to test merging behavior overlapping_custom_components = { "category1": { # Same category as langflow "Component1": {"display_name": "CustomComponent1", "type": "category1"}, # Same name as langflow "Component4": {"display_name": "Component4", "type": "category1"}, # New component }, "new_category": { "NewComponent": {"display_name": "NewComponent", "type": "new_category"}, }, } with ( patch("lfx.interface.components.import_langflow_components", return_value=mock_langflow_components), patch("lfx.interface.components.aget_all_types_dict", return_value=overlapping_custom_components), ): # Execute the function result = await get_and_cache_all_types_dict(mock_settings_service) # Verify that custom components override langflow components with same name assert "category1" in result assert "category2" in result # From langflow assert "new_category" in result # From custom # Custom category should completely override langflow category assert result["category1"]["Component1"]["display_name"] == "CustomComponent1" # Only components from custom category should remain in category1 assert "Component2" not in result["category1"] # Langflow component is replaced by custom category assert "Component4" in result["category1"] # New custom component # New custom component should be added assert result["category1"]["Component4"]["display_name"] == "Component4" # New category should be added assert result["new_category"]["NewComponent"]["display_name"] == "NewComponent" @pytest.mark.asyncio async def test_component_cache_behavior(self, mock_settings_service, mock_langflow_components): """Test that component cache is properly used and populated.""" # Setup mock_settings_service.settings.components_path = ["/custom/path1"] mock_settings_service.settings.lazy_load_components = False with ( patch("lfx.interface.components.import_langflow_components", return_value=mock_langflow_components), patch("lfx.interface.components.aget_all_types_dict", return_value={}), ): # First call - should populate cache result1 = await get_and_cache_all_types_dict(mock_settings_service) # Verify cache is populated assert component_cache.all_types_dict is not None assert component_cache.all_types_dict == result1 # Second call - should use cache result2 = await get_and_cache_all_types_dict(mock_settings_service) # Verify same result returned from cache assert result1 == result2 assert result1 is result2 # Same object reference @pytest.mark.asyncio async def test_logging_behavior(self, mock_settings_service, mock_langflow_components, mock_custom_components): """Test that appropriate logging messages are generated.""" # Setup mock_settings_service.settings.components_path = ["/custom/path1"] mock_settings_service.settings.lazy_load_components = False with ( patch("lfx.interface.components.import_langflow_components", return_value=mock_langflow_components), patch("lfx.interface.components.aget_all_types_dict", return_value=mock_custom_components), patch("lfx.interface.components.logger") as mock_logger, ): # Configure async mock methods mock_logger.adebug = AsyncMock() # Execute the function await get_and_cache_all_types_dict(mock_settings_service) # Verify debug logging calls mock_logger.adebug.assert_any_call("Building components cache") # Verify total component count logging debug_calls = [call.args[0] for call in mock_logger.adebug.call_args_list] total_count_logs = [log for log in debug_calls if "Loaded" in log and "components" in log] assert len(total_count_logs) >= 1 @pytest.mark.asyncio async def test_error_handling_in_custom_component_loading(self, mock_settings_service, mock_langflow_components): """Test error handling when custom component loading fails.""" # Setup mock_settings_service.settings.components_path = ["/custom/path1"] mock_settings_service.settings.lazy_load_components = False with ( patch("lfx.interface.components.import_langflow_components", return_value=mock_langflow_components), patch("lfx.interface.components.aget_all_types_dict", side_effect=Exception("Custom loading failed")), pytest.raises(Exception, match="Custom loading failed"), ): # Execute the function - should raise exception when custom component loading fails await get_and_cache_all_types_dict(mock_settings_service) @pytest.mark.asyncio async def test_base_components_path_constant_value(self): """Test that BASE_COMPONENTS_PATH has expected value and behavior.""" # Verify BASE_COMPONENTS_PATH is defined and has expected characteristics assert BASE_COMPONENTS_PATH is not None assert isinstance(BASE_COMPONENTS_PATH, str) assert len(BASE_COMPONENTS_PATH) > 0 # Should be an absolute path containing "langflow" and "components" assert "langflow" in BASE_COMPONENTS_PATH.lower() assert "components" in BASE_COMPONENTS_PATH.lower() @pytest.mark.asyncio async def test_path_filtering_edge_cases(self, mock_settings_service, mock_langflow_components): """Test edge cases in path filtering logic.""" # Setup mock_settings_service.settings.lazy_load_components = False # Test with duplicate BASE_COMPONENTS_PATH mock_settings_service.settings.components_path = [BASE_COMPONENTS_PATH, "/custom/path", BASE_COMPONENTS_PATH] with ( patch("lfx.interface.components.import_langflow_components", return_value=mock_langflow_components), patch("lfx.interface.components.aget_all_types_dict", return_value={}) as mock_aget_all_types_dict, ): # Clear cache for fresh test component_cache.all_types_dict = None # Execute the function await get_and_cache_all_types_dict(mock_settings_service) # Verify that both instances of BASE_COMPONENTS_PATH are filtered out mock_aget_all_types_dict.assert_called_once_with(["/custom/path"]) @pytest.mark.asyncio async def test_component_count_calculation(self, mock_settings_service, mock_langflow_components): """Test that component count calculation works correctly.""" # Setup with known component counts mock_settings_service.settings.components_path = ["/custom/path1"] mock_settings_service.settings.lazy_load_components = False # Mock custom components with known count mock_custom_components = { "custom_cat1": { "CustomComp1": {"display_name": "CustomComp1"}, "CustomComp2": {"display_name": "CustomComp2"}, }, "custom_cat2": { "CustomComp3": {"display_name": "CustomComp3"}, }, } with ( patch("lfx.interface.components.import_langflow_components", return_value=mock_langflow_components), patch("lfx.interface.components.aget_all_types_dict", return_value=mock_custom_components), ): # Execute the function result = await get_and_cache_all_types_dict(mock_settings_service) # Verify result structure assert len(result) >= 2 # At least langflow categories + custom categories # Verify custom components are present assert "custom_cat1" in result assert "custom_cat2" in result assert "CustomComp1" in result["custom_cat1"] assert "CustomComp3" in result["custom_cat2"] @pytest.mark.asyncio async def test_async_concurrency_safety( self, mock_settings_service, mock_langflow_components, mock_custom_components ): """Test that concurrent calls to get_and_cache_all_types_dict are safe.""" # Setup mock_settings_service.settings.components_path = ["/custom/path1"] mock_settings_service.settings.lazy_load_components = False with ( patch("lfx.interface.components.import_langflow_components", return_value=mock_langflow_components), patch("lfx.interface.components.aget_all_types_dict", return_value=mock_custom_components), ): # Execute multiple concurrent calls tasks = [get_and_cache_all_types_dict(mock_settings_service) for _ in range(3)] results = await asyncio.gather(*tasks) # Verify all results are identical (cache working properly) first_result = results[0] for result in results[1:]: assert result == first_result # Results should be consistent, though reference may vary due to concurrency @pytest.mark.asyncio async def test_integration_with_real_base_components_path(self, mock_settings_service): """Integration test with real BASE_COMPONENTS_PATH to ensure filtering works.""" # Setup with real BASE_COMPONENTS_PATH value mock_settings_service.settings.components_path = [BASE_COMPONENTS_PATH, "/custom/test"] mock_settings_service.settings.lazy_load_components = False # This test should work with real langflow components with patch("lfx.interface.components.aget_all_types_dict", return_value={}) as mock_aget_all_types_dict: # Execute the function result = await get_and_cache_all_types_dict(mock_settings_service) # Verify BASE_COMPONENTS_PATH was filtered out mock_aget_all_types_dict.assert_called_once_with(["/custom/test"]) # Verify we got real langflow components assert isinstance(result, dict) assert len(result) >= 0 # Should not have langflow components
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/custom/component/test_component_loading_fix.py", "license": "MIT License", "lines": 362, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/base/langflow/utils/template_validation.py
"""Template validation utilities for Langflow starter projects. This module provides validation functions to ensure template integrity and prevent unexpected breakage in starter project templates. """ import asyncio import json import uuid from typing import Any from lfx.custom.validate import validate_code from lfx.graph.graph.base import Graph def validate_template_structure(template_data: dict[str, Any], filename: str) -> list[str]: """Validate basic template structure. Args: template_data: The template data to validate filename: Name of the template file for error reporting Returns: List of error messages, empty if validation passes """ errors = [] # Handle wrapped format data = template_data.get("data", template_data) # Check required fields if "nodes" not in data: errors.append(f"{filename}: Missing 'nodes' field") elif not isinstance(data["nodes"], list): errors.append(f"{filename}: 'nodes' must be a list") if "edges" not in data: errors.append(f"{filename}: Missing 'edges' field") elif not isinstance(data["edges"], list): errors.append(f"{filename}: 'edges' must be a list") # Check nodes have required fields for i, node in enumerate(data.get("nodes", [])): if "id" not in node: errors.append(f"{filename}: Node {i} missing 'id'") if "data" not in node: errors.append(f"{filename}: Node {i} missing 'data'") return errors def validate_flow_can_build(template_data: dict[str, Any], filename: str) -> list[str]: """Validate that the template can be built into a working flow. Args: template_data: The template data to validate filename: Name of the template file for error reporting Returns: List of build errors, empty if flow builds successfully """ errors = [] try: # Create a unique flow ID for testing flow_id = str(uuid.uuid4()) flow_name = filename.replace(".json", "") # Try to build the graph from the template data graph = Graph.from_payload(template_data, flow_id, flow_name, user_id="test_user") # Validate stream configuration graph.validate_stream() # Basic validation that the graph has vertices if not graph.vertices: errors.append(f"{filename}: Flow has no vertices after building") # Validate that all vertices have valid IDs errors.extend([f"{filename}: Vertex missing ID" for vertex in graph.vertices if not vertex.id]) except (ValueError, TypeError, KeyError, AttributeError) as e: errors.append(f"{filename}: Failed to build flow graph: {e!s}") return errors def validate_flow_code(template_data: dict[str, Any], filename: str) -> list[str]: """Validate flow code using direct function call. Args: template_data: The template data to validate filename: Name of the template file for error reporting Returns: List of validation errors, empty if validation passes """ errors = [] try: # Extract code fields from template for validation data = template_data.get("data", template_data) for node in data.get("nodes", []): node_data = node.get("data", {}) node_template = node_data.get("node", {}).get("template", {}) # Look for code-related fields in the node template for field_data in node_template.values(): if isinstance(field_data, dict) and field_data.get("type") == "code": code_value = field_data.get("value", "") if code_value and isinstance(code_value, str): # Validate the code using direct function call validation_result = validate_code(code_value) # Check for import errors if validation_result.get("imports", {}).get("errors"): errors.extend( [ f"{filename}: Import error in node {node_data.get('id', 'unknown')}: {error}" for error in validation_result["imports"]["errors"] ] ) # Check for function errors if validation_result.get("function", {}).get("errors"): errors.extend( [ f"{filename}: Function error in node {node_data.get('id', 'unknown')}: {error}" for error in validation_result["function"]["errors"] ] ) except (ValueError, TypeError, KeyError, AttributeError) as e: errors.append(f"{filename}: Code validation failed: {e!s}") return errors async def validate_flow_execution( client, template_data: dict[str, Any], filename: str, headers: dict[str, str] ) -> list[str]: """Validate flow execution by building and running the flow. Args: client: AsyncClient for API requests template_data: The template data to validate filename: Name of the template file for error reporting headers: Authorization headers for API requests Returns: List of execution errors, empty if execution succeeds """ errors = [] try: # Create a flow from the template with timeout create_response = await client.post("api/v1/flows/", json=template_data, headers=headers, timeout=10) if create_response.status_code != 201: # noqa: PLR2004 errors.append(f"{filename}: Failed to create flow: {create_response.status_code}") return errors flow_id = create_response.json()["id"] try: # Build the flow with timeout build_response = await client.post(f"api/v1/build/{flow_id}/flow", json={}, headers=headers, timeout=10) if build_response.status_code != 200: # noqa: PLR2004 errors.append(f"{filename}: Failed to build flow: {build_response.status_code}") return errors job_id = build_response.json()["job_id"] # Get build events to validate execution events_headers = {**headers, "Accept": "application/x-ndjson"} events_response = await client.get(f"api/v1/build/{job_id}/events", headers=events_headers, timeout=10) if events_response.status_code != 200: # noqa: PLR2004 errors.append(f"{filename}: Failed to get build events: {events_response.status_code}") return errors # Validate the event stream await _validate_event_stream(events_response, job_id, filename, errors) finally: # Clean up the flow with timeout try: # noqa: SIM105 await client.delete(f"api/v1/flows/{flow_id}", headers=headers, timeout=10) except asyncio.TimeoutError: # Log but don't fail if cleanup times out pass except asyncio.TimeoutError: errors.append(f"{filename}: Flow execution timed out") except (ValueError, TypeError, KeyError, AttributeError) as e: errors.append(f"{filename}: Flow execution validation failed: {e!s}") return errors async def _validate_event_stream(response, job_id: str, filename: str, errors: list[str]) -> None: """Validate the event stream from flow execution. Args: response: The response object with event stream job_id: The job ID to verify in events filename: Name of the template file for error reporting errors: List to append errors to """ try: vertices_sorted_seen = False end_event_seen = False vertex_count = 0 async def process_events(): nonlocal vertices_sorted_seen, end_event_seen, vertex_count async for line in response.aiter_lines(): if not line: continue try: parsed = json.loads(line) except json.JSONDecodeError: errors.append(f"{filename}: Invalid JSON in event stream: {line}") continue # Verify job_id in events if "job_id" in parsed and parsed["job_id"] != job_id: errors.append(f"{filename}: Job ID mismatch in event stream") continue event_type = parsed.get("event") if event_type == "vertices_sorted": vertices_sorted_seen = True if not parsed.get("data", {}).get("ids"): errors.append(f"{filename}: Missing vertex IDs in vertices_sorted event") elif event_type == "end_vertex": vertex_count += 1 if not parsed.get("data", {}).get("build_data"): errors.append(f"{filename}: Missing build_data in end_vertex event") elif event_type == "end": end_event_seen = True elif event_type == "error": error_data = parsed.get("data", {}) if isinstance(error_data, dict): error_msg = error_data.get("error", "Unknown error") # Skip if error is just "False" which is not a real error if error_msg != "False" and error_msg is not False: errors.append(f"{filename}: Flow execution error: {error_msg}") else: error_msg = str(error_data) if error_msg != "False": errors.append(f"{filename}: Flow execution error: {error_msg}") elif event_type == "message": # Handle message events (normal part of flow execution) pass elif event_type in ["token", "add_message", "stream_closed"]: # Handle other common event types that don't indicate errors pass # Process events with shorter timeout for comprehensive testing await asyncio.wait_for(process_events(), timeout=5.0) # Validate we saw required events (more lenient for diverse templates) # Only require end event - some templates may not follow the standard pattern if not end_event_seen: errors.append(f"{filename}: Missing end event in execution") # Allow flows with no vertices to be executed (some templates might be simple) # if vertex_count == 0: # errors.append(f"{filename}: No vertices executed in flow") except asyncio.TimeoutError: errors.append(f"{filename}: Flow execution timeout") except (ValueError, TypeError, KeyError, AttributeError) as e: errors.append(f"{filename}: Event stream validation failed: {e!s}")
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/base/langflow/utils/template_validation.py", "license": "MIT License", "lines": 217, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
langflow-ai/langflow:src/backend/tests/unit/template/test_starter_projects.py
"""Comprehensive tests for starter project templates. Tests all JSON templates in the starter_projects folder to ensure they: 1. Are valid JSON 2. Have required structure (nodes, edges) 3. Don't have basic security issues 4. Can be built into working flows Validates that templates work correctly and prevent unexpected breakage. """ import json from importlib import import_module from pathlib import Path import pytest # Import langflow validation utilities from langflow.utils.template_validation import ( validate_flow_can_build, validate_flow_execution, validate_template_structure, ) def get_starter_projects_path() -> Path: """Get path to starter projects directory.""" return Path("src/backend/base/langflow/initial_setup/starter_projects") def get_template_files(): """Get all template files for parameterization.""" return list(get_starter_projects_path().glob("*.json")) def get_basic_template_files(): """Get basic template files for parameterization.""" path = get_starter_projects_path() basic_templates = ["Basic Prompting.json", "Basic Prompt Chaining.json"] return [path / name for name in basic_templates if (path / name).exists()] @pytest.fixture(autouse=True) def disable_tracing(monkeypatch): """Disable tracing for all template tests.""" monkeypatch.setenv("LANGFLOW_DEACTIVATE_TRACING", "true") class TestStarterProjects: """Test all starter project templates.""" def test_templates_exist(self): """Test that templates directory exists and has templates.""" path = get_starter_projects_path() assert path.exists(), f"Directory not found: {path}" templates = get_template_files() assert len(templates) > 0, "No template files found" @pytest.mark.parametrize("template_file", get_template_files(), ids=lambda x: x.name) def test_template_valid_json(self, template_file): """Test template is valid JSON.""" with template_file.open(encoding="utf-8") as f: try: json.load(f) except json.JSONDecodeError as e: pytest.fail(f"Invalid JSON in {template_file.name}: {e}") @pytest.mark.parametrize("template_file", get_template_files(), ids=lambda x: x.name) def test_template_structure(self, template_file): """Test template has required structure.""" with template_file.open(encoding="utf-8") as f: template_data = json.load(f) errors = validate_template_structure(template_data, template_file.name) if errors: error_msg = "\n".join(errors) pytest.fail(f"Template structure errors in {template_file.name}:\n{error_msg}") @pytest.mark.parametrize("template_file", get_template_files(), ids=lambda x: x.name) def test_template_can_build_flow(self, template_file): """Test template can be built into working flow.""" with template_file.open(encoding="utf-8") as f: template_data = json.load(f) errors = validate_flow_can_build(template_data, template_file.name) if errors: error_msg = "\n".join(errors) pytest.fail(f"Flow build errors in {template_file.name}:\n{error_msg}") @pytest.mark.asyncio @pytest.mark.parametrize("template_file", get_template_files(), ids=lambda x: x.name) async def test_template_validate_endpoint(self, template_file, client, logged_in_headers): """Test template using the validate endpoint.""" with template_file.open(encoding="utf-8") as f: template_data = json.load(f) errors = await validate_flow_execution(client, template_data, template_file.name, logged_in_headers) if errors: error_msg = "\n".join(errors) pytest.fail(f"Endpoint validation errors in {template_file.name}:\n{error_msg}") @pytest.mark.asyncio @pytest.mark.parametrize("template_file", get_template_files(), ids=lambda x: x.name) async def test_template_flow_execution(self, template_file, client, logged_in_headers): """Test template can execute successfully.""" try: with template_file.open(encoding="utf-8") as f: template_data = json.load(f) errors = await validate_flow_execution(client, template_data, template_file.name, logged_in_headers) if errors: error_msg = "\n".join(errors) pytest.fail(f"Template execution errors in {template_file.name}:\n{error_msg}") except (ValueError, TypeError, KeyError, AttributeError, OSError, json.JSONDecodeError) as e: pytest.fail(f"{template_file.name}: Unexpected error during validation: {e!s}") @pytest.mark.parametrize("template_file", get_template_files(), ids=lambda x: x.name) def test_template_field_order_matches_component(self, template_file): """Test that field_order in starter project JSON matches the actual component's input order.""" with template_file.open(encoding="utf-8") as f: template_data = json.load(f) errors = [] for node in template_data.get("data", {}).get("nodes", []): node_data = node.get("data", {}) node_info = node_data.get("node", {}) metadata = node_info.get("metadata", {}) module_path = metadata.get("module", "") json_field_order = node_info.get("field_order") if not module_path or json_field_order is None: continue # Parse module path: "lfx.components.foo.bar.ClassName" parts = module_path.rsplit(".", 1) if len(parts) != 2: continue module_name, class_name = parts try: mod = import_module(module_name) cls = getattr(mod, class_name) instance = cls() component_field_order = instance._get_field_order() except Exception as e: errors.append( f" Node '{node_data.get('display_name', node_data.get('type', '?'))}' " f"({class_name}): Could not instantiate component: {e}" ) continue # Verify that the JSON field_order exactly matches the component's full field order. # A subset would cause layout inconsistency between template and sidebar components. if json_field_order != component_field_order: display = node_data.get("display_name") or node_data.get("type", "?") missing = [f for f in component_field_order if f not in json_field_order] extra = [f for f in json_field_order if f not in component_field_order] detail_lines = [ f" JSON field_order: {json_field_order}", f" Expected (component): {component_field_order}", ] if missing: detail_lines.append(f" Missing fields: {missing}") if extra: detail_lines.append(f" Extra fields: {extra}") errors.append(f" Node '{display}' ({class_name}):\n" + "\n".join(detail_lines)) if errors: error_msg = "\n".join(errors) pytest.fail(f"field_order mismatches in {template_file.name}:\n{error_msg}") @pytest.mark.parametrize("template_file", get_template_files(), ids=lambda x: x.name) def test_template_nodes_no_overlap(self, template_file): """Test that no two generic nodes overlap on the canvas.""" with template_file.open(encoding="utf-8") as f: template_data = json.load(f) nodes = template_data.get("data", {}).get("nodes", []) # Collect bounding boxes for generic (non-note) nodes boxes = [] for node in nodes: if node.get("type") == "noteNode": continue pos = node.get("position", {}) measured = node.get("measured", {}) x = pos.get("x") y = pos.get("y") w = measured.get("width") h = measured.get("height") if x is None or y is None or w is None or h is None: continue display = node.get("data", {}).get("display_name") or node.get("data", {}).get("type", node.get("id", "?")) boxes.append((display, x, y, w, h)) # Minimum overlap in pixels on each axis to count as a real overlap. # Stored `measured` dimensions can be slightly stale, so ignore # near-miss intersections smaller than this threshold. min_overlap_px = 20 errors = [] for i, (name_a, ax, ay, aw, ah) in enumerate(boxes): for name_b, bx, by, bw, bh in boxes[i + 1 :]: # Compute overlap extent on each axis overlap_x = min(ax + aw, bx + bw) - max(ax, bx) overlap_y = min(ay + ah, by + bh) - max(ay, by) if overlap_x > min_overlap_px and overlap_y > min_overlap_px: errors.append(f" '{name_a}' and '{name_b}' overlap on the canvas") if errors: error_msg = "\n".join(errors) pytest.fail(f"Node overlaps in {template_file.name}:\n{error_msg}") @pytest.mark.asyncio @pytest.mark.parametrize("template_file", get_basic_template_files(), ids=lambda x: x.name) async def test_basic_template_flow_execution(self, template_file, client, logged_in_headers): """Test basic template can execute successfully.""" try: with template_file.open(encoding="utf-8") as f: template_data = json.load(f) errors = await validate_flow_execution(client, template_data, template_file.name, logged_in_headers) if errors: error_msg = "\n".join(errors) pytest.fail(f"Basic template execution errors in {template_file.name}:\n{error_msg}") except (ValueError, TypeError, KeyError, AttributeError, OSError, json.JSONDecodeError) as e: pytest.fail(f"{template_file.name}: Unexpected error during validation: {e!s}")
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/template/test_starter_projects.py", "license": "MIT License", "lines": 187, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/tests/unit/utils/test_template_validation.py
"""Unit tests for template validation utilities.""" import asyncio from unittest.mock import AsyncMock, Mock, patch import pytest from langflow.utils.template_validation import ( _validate_event_stream, validate_flow_can_build, validate_flow_code, validate_flow_execution, validate_template_structure, ) class AsyncIteratorMock: """Mock class that provides proper async iteration.""" def __init__(self, items): self.items = items def __aiter__(self): return self async def __anext__(self): if not self.items: raise StopAsyncIteration return self.items.pop(0) class TestValidateTemplateStructure: """Test cases for validate_template_structure function.""" def test_valid_template_structure(self): """Test validation passes for valid template structure.""" template_data = { "nodes": [ {"id": "node1", "data": {"type": "input"}}, {"id": "node2", "data": {"type": "output"}}, ], "edges": [{"source": "node1", "target": "node2"}], } errors = validate_template_structure(template_data, "test.json") assert errors == [] def test_valid_template_with_data_wrapper(self): """Test validation passes for template with data wrapper.""" template_data = { "data": { "nodes": [{"id": "node1", "data": {"type": "input"}}], "edges": [], } } errors = validate_template_structure(template_data, "test.json") assert errors == [] def test_missing_nodes_field(self): """Test validation fails when nodes field is missing.""" template_data = {"edges": []} errors = validate_template_structure(template_data, "test.json") assert "test.json: Missing 'nodes' field" in errors def test_missing_edges_field(self): """Test validation fails when edges field is missing.""" template_data = {"nodes": []} errors = validate_template_structure(template_data, "test.json") assert "test.json: Missing 'edges' field" in errors def test_nodes_not_list(self): """Test validation fails when nodes is not a list.""" template_data = {"nodes": "not_a_list", "edges": []} errors = validate_template_structure(template_data, "test.json") assert "test.json: 'nodes' must be a list" in errors def test_edges_not_list(self): """Test validation fails when edges is not a list.""" template_data = {"nodes": [], "edges": "not_a_list"} errors = validate_template_structure(template_data, "test.json") assert "test.json: 'edges' must be a list" in errors def test_node_missing_id(self): """Test validation fails when node is missing id.""" template_data = { "nodes": [{"data": {"type": "input"}}], "edges": [], } errors = validate_template_structure(template_data, "test.json") assert "test.json: Node 0 missing 'id'" in errors def test_node_missing_data(self): """Test validation fails when node is missing data.""" template_data = { "nodes": [{"id": "node1"}], "edges": [], } errors = validate_template_structure(template_data, "test.json") assert "test.json: Node 0 missing 'data'" in errors def test_multiple_validation_errors(self): """Test multiple validation errors are collected.""" template_data = { "nodes": [ {"data": {"type": "input"}}, # Missing id {"id": "node2"}, # Missing data ], "edges": "not_a_list", } errors = validate_template_structure(template_data, "test.json") assert len(errors) == 3 assert "Node 0 missing 'id'" in str(errors) assert "Node 1 missing 'data'" in str(errors) assert "'edges' must be a list" in str(errors) class TestValidateFlowCanBuild: """Test cases for validate_flow_can_build function.""" @patch("langflow.utils.template_validation.Graph") def test_valid_flow_builds_successfully(self, mock_graph_class): """Test validation passes when flow builds successfully.""" # Setup mock graph mock_graph = Mock() mock_graph.vertices = [Mock(id="vertex1"), Mock(id="vertex2")] mock_graph_class.from_payload.return_value = mock_graph template_data = { "nodes": [{"id": "node1", "data": {"type": "input"}}], "edges": [], } errors = validate_flow_can_build(template_data, "test.json") assert errors == [] mock_graph_class.from_payload.assert_called_once() mock_graph.validate_stream.assert_called_once() @patch("langflow.utils.template_validation.Graph") def test_flow_build_fails_with_exception(self, mock_graph_class): """Test validation fails when flow build raises exception.""" mock_graph_class.from_payload.side_effect = ValueError("Build failed") template_data = {"nodes": [], "edges": []} errors = validate_flow_can_build(template_data, "test.json") assert len(errors) == 1 assert "test.json: Failed to build flow graph: Build failed" in errors @patch("langflow.utils.template_validation.Graph") def test_flow_has_no_vertices(self, mock_graph_class): """Test validation fails when flow has no vertices.""" mock_graph = Mock() mock_graph.vertices = [] mock_graph_class.from_payload.return_value = mock_graph template_data = {"nodes": [], "edges": []} errors = validate_flow_can_build(template_data, "test.json") assert "test.json: Flow has no vertices after building" in errors @patch("langflow.utils.template_validation.Graph") def test_vertex_missing_id(self, mock_graph_class): """Test validation fails when vertex is missing ID.""" mock_vertex = Mock() mock_vertex.id = None mock_graph = Mock() mock_graph.vertices = [mock_vertex] mock_graph_class.from_payload.return_value = mock_graph template_data = {"nodes": [], "edges": []} errors = validate_flow_can_build(template_data, "test.json") assert "test.json: Vertex missing ID" in errors @patch("langflow.utils.template_validation.Graph") def test_uses_unique_flow_id(self, mock_graph_class): """Test that unique flow ID and name are used.""" mock_graph = Mock() mock_graph.vertices = [Mock(id="vertex1")] mock_graph_class.from_payload.return_value = mock_graph template_data = {"nodes": [], "edges": []} validate_flow_can_build(template_data, "my_flow.json") # Verify from_payload was called with proper parameters call_args = mock_graph_class.from_payload.call_args assert call_args[0][0] == template_data # template_data assert len(call_args[0][1]) == 36 # UUID length assert call_args[0][2] == "my_flow" # flow_name # The user_id is passed as a keyword argument assert call_args[1]["user_id"] == "test_user" @patch("langflow.utils.template_validation.Graph") def test_validate_stream_exception(self, mock_graph_class): """Test that validate_stream exceptions are caught.""" mock_graph = Mock() mock_graph.vertices = [Mock(id="vertex1")] mock_graph.validate_stream.side_effect = ValueError("Stream validation failed") mock_graph_class.from_payload.return_value = mock_graph template_data = {"nodes": [], "edges": []} errors = validate_flow_can_build(template_data, "test.json") assert len(errors) == 1 assert "Failed to build flow graph: Stream validation failed" in errors[0] class TestValidateFlowCode: """Test cases for validate_flow_code function.""" @patch("langflow.utils.template_validation.validate_code") def test_valid_flow_code(self, mock_validate_code): """Test validation passes when code is valid.""" mock_validate_code.return_value = { "imports": {"errors": []}, "function": {"errors": []}, } template_data = { "data": { "nodes": [ { "id": "node1", "data": { "id": "node1", "node": { "template": { "code_field": { "type": "code", "value": "def hello(): return 'world'", } } }, }, } ] } } errors = validate_flow_code(template_data, "test.json") assert errors == [] mock_validate_code.assert_called_once_with("def hello(): return 'world'") @patch("langflow.utils.template_validation.validate_code") def test_code_import_errors(self, mock_validate_code): """Test validation fails when code has import errors.""" mock_validate_code.return_value = { "imports": {"errors": ["Module not found: nonexistent_module"]}, "function": {"errors": []}, } template_data = { "nodes": [ { "data": { "id": "node1", "node": { "template": { "code_field": { "type": "code", "value": "import nonexistent_module", } } }, } } ] } errors = validate_flow_code(template_data, "test.json") assert len(errors) == 1 assert "Import error in node node1: Module not found: nonexistent_module" in errors[0] @patch("langflow.utils.template_validation.validate_code") def test_code_function_errors(self, mock_validate_code): """Test validation fails when code has function errors.""" mock_validate_code.return_value = { "imports": {"errors": []}, "function": {"errors": ["Syntax error in function"]}, } template_data = { "nodes": [ { "data": { "id": "node2", "node": { "template": { "code_field": { "type": "code", "value": "def broken(: pass", } } }, } } ] } errors = validate_flow_code(template_data, "test.json") assert len(errors) == 1 assert "Function error in node node2: Syntax error in function" in errors[0] def test_no_code_fields(self): """Test validation passes when there are no code fields.""" template_data = { "nodes": [{"data": {"node": {"template": {"text_field": {"type": "text", "value": "hello"}}}}}] } errors = validate_flow_code(template_data, "test.json") assert errors == [] def test_empty_code_value(self): """Test validation passes when code value is empty.""" template_data = {"nodes": [{"data": {"node": {"template": {"code_field": {"type": "code", "value": ""}}}}}]} errors = validate_flow_code(template_data, "test.json") assert errors == [] def test_code_validation_exception(self): """Test validation handles exceptions gracefully.""" template_data = { "nodes": [{"data": {"node": {"template": {"code_field": {"type": "code", "value": "def test(): pass"}}}}}] } with patch("langflow.utils.template_validation.validate_code", side_effect=ValueError("Unexpected error")): errors = validate_flow_code(template_data, "test.json") assert len(errors) == 1 assert "Code validation failed: Unexpected error" in errors[0] def test_code_validation_other_exceptions(self): """Test validation handles different exception types.""" template_data = { "nodes": [{"data": {"node": {"template": {"code_field": {"type": "code", "value": "def test(): pass"}}}}}] } # Test TypeError with patch("langflow.utils.template_validation.validate_code", side_effect=TypeError("Type error")): errors = validate_flow_code(template_data, "test.json") assert len(errors) == 1 assert "Code validation failed: Type error" in errors[0] # Test KeyError with patch("langflow.utils.template_validation.validate_code", side_effect=KeyError("key")): errors = validate_flow_code(template_data, "test.json") assert len(errors) == 1 assert "Code validation failed: 'key'" in errors[0] # Test AttributeError with patch("langflow.utils.template_validation.validate_code", side_effect=AttributeError("Attribute error")): errors = validate_flow_code(template_data, "test.json") assert len(errors) == 1 assert "Code validation failed: Attribute error" in errors[0] class TestValidateFlowExecution: """Test cases for validate_flow_execution function.""" @pytest.mark.asyncio async def test_successful_flow_execution(self): """Test validation passes when flow execution succeeds.""" # Mock client responses mock_client = AsyncMock() # Mock create flow response create_response = Mock() create_response.status_code = 201 create_response.json.return_value = {"id": "flow123"} mock_client.post.return_value = create_response # Mock build response build_response = Mock() build_response.status_code = 200 build_response.json.return_value = {"job_id": "job123"} # Mock events response events_response = Mock() events_response.status_code = 200 events_response.aiter_lines = Mock( return_value=AsyncIteratorMock( [ '{"event": "vertices_sorted", "job_id": "job123", "data": {"ids": ["v1"]}}', '{"event": "end_vertex", "job_id": "job123", "data": {"build_data": {"result": "success"}}}', '{"event": "end", "job_id": "job123"}', ] ) ) # Set up call sequence mock_client.post.side_effect = [create_response, build_response] mock_client.get.return_value = events_response mock_client.delete.return_value = Mock() template_data = {"nodes": [], "edges": []} headers = {"Authorization": "Bearer token"} errors = await validate_flow_execution(mock_client, template_data, "test.json", headers) assert errors == [] # Verify API calls assert mock_client.post.call_count == 2 mock_client.get.assert_called_once() mock_client.delete.assert_called_once() @pytest.mark.asyncio async def test_flow_creation_fails(self): """Test validation fails when flow creation fails.""" mock_client = AsyncMock() create_response = Mock() create_response.status_code = 400 mock_client.post.return_value = create_response template_data = {"nodes": [], "edges": []} headers = {"Authorization": "Bearer token"} errors = await validate_flow_execution(mock_client, template_data, "test.json", headers) assert len(errors) == 1 assert "Failed to create flow: 400" in errors[0] @pytest.mark.asyncio async def test_flow_build_fails(self): """Test validation fails when flow build fails.""" mock_client = AsyncMock() # Mock successful create create_response = Mock() create_response.status_code = 201 create_response.json.return_value = {"id": "flow123"} # Mock failed build build_response = Mock() build_response.status_code = 500 mock_client.post.side_effect = [create_response, build_response] mock_client.delete.return_value = Mock() template_data = {"nodes": [], "edges": []} headers = {"Authorization": "Bearer token"} errors = await validate_flow_execution(mock_client, template_data, "test.json", headers) assert len(errors) == 1 assert "Failed to build flow: 500" in errors[0] @pytest.mark.asyncio async def test_execution_timeout(self): """Test validation fails when execution times out.""" mock_client = AsyncMock() mock_client.post.side_effect = asyncio.TimeoutError() template_data = {"nodes": [], "edges": []} headers = {"Authorization": "Bearer token"} errors = await validate_flow_execution(mock_client, template_data, "test.json", headers) assert len(errors) == 1 assert "Flow execution timed out" in errors[0] @pytest.mark.asyncio async def test_cleanup_on_exception(self): """Test that flow cleanup happens even when exceptions occur.""" mock_client = AsyncMock() # Mock successful create create_response = Mock() create_response.status_code = 201 create_response.json.return_value = {"id": "flow123"} # Mock build that raises exception mock_client.post.side_effect = [create_response, ValueError("Build error")] mock_client.delete.return_value = Mock() template_data = {"nodes": [], "edges": []} headers = {"Authorization": "Bearer token", "timeout": 10} errors = await validate_flow_execution(mock_client, template_data, "test.json", headers) assert len(errors) == 1 assert "Flow execution validation failed: Build error" in errors[0] # Verify cleanup was called mock_client.delete.assert_called_once_with("api/v1/flows/flow123", headers=headers, timeout=10) class TestValidateEventStream: """Test cases for _validate_event_stream function.""" @pytest.mark.asyncio async def test_valid_event_stream(self): """Test validation passes for valid event stream.""" mock_response = Mock() mock_response.aiter_lines = Mock( return_value=AsyncIteratorMock( [ '{"event": "vertices_sorted", "job_id": "job123", "data": {"ids": ["v1", "v2"]}}', '{"event": "end_vertex", "job_id": "job123", "data": {"build_data": {"result": "success"}}}', '{"event": "end_vertex", "job_id": "job123", "data": {"build_data": {"result": "success"}}}', '{"event": "end", "job_id": "job123"}', ] ) ) errors = [] await _validate_event_stream(mock_response, "job123", "test.json", errors) assert errors == [] @pytest.mark.asyncio async def test_missing_end_event(self): """Test validation fails when end event is missing.""" mock_response = Mock() mock_response.aiter_lines = Mock( return_value=AsyncIteratorMock( ['{"event": "vertices_sorted", "job_id": "job123", "data": {"ids": ["v1"]}}'] ) ) errors = [] await _validate_event_stream(mock_response, "job123", "test.json", errors) assert len(errors) == 1 assert "Missing end event in execution" in errors[0] @pytest.mark.asyncio async def test_job_id_mismatch(self): """Test validation fails when job ID doesn't match.""" mock_response = Mock() mock_response.aiter_lines = Mock( return_value=AsyncIteratorMock( [ '{"event": "vertices_sorted", "job_id": "wrong_job", "data": {"ids": ["v1"]}}', '{"event": "end", "job_id": "job123"}', ] ) ) errors = [] await _validate_event_stream(mock_response, "job123", "test.json", errors) assert len(errors) == 1 assert "Job ID mismatch in event stream" in errors[0] @pytest.mark.asyncio async def test_invalid_json_in_stream(self): """Test validation handles invalid JSON in event stream.""" mock_response = Mock() mock_response.aiter_lines = Mock( return_value=AsyncIteratorMock(["invalid json", '{"event": "end", "job_id": "job123"}']) ) errors = [] await _validate_event_stream(mock_response, "job123", "test.json", errors) assert len(errors) == 1 assert "Invalid JSON in event stream: invalid json" in errors[0] @pytest.mark.asyncio async def test_error_event_handling(self): """Test validation handles error events properly.""" mock_response = Mock() mock_response.aiter_lines = Mock( return_value=AsyncIteratorMock( [ '{"event": "error", "job_id": "job123", "data": {"error": "Something went wrong"}}', '{"event": "error", "job_id": "job123", "data": {"error": "False"}}', # Should be ignored '{"event": "error", "job_id": "job123", "data": "String error"}', '{"event": "end", "job_id": "job123"}', ] ) ) errors = [] await _validate_event_stream(mock_response, "job123", "test.json", errors) assert len(errors) == 2 assert "Flow execution error: Something went wrong" in errors[0] assert "Flow execution error: String error" in errors[1] @pytest.mark.asyncio async def test_missing_vertex_ids(self): """Test validation fails when vertices_sorted event missing IDs.""" mock_response = Mock() mock_response.aiter_lines = Mock( return_value=AsyncIteratorMock( [ '{"event": "vertices_sorted", "job_id": "job123", "data": {}}', '{"event": "end", "job_id": "job123"}', ] ) ) errors = [] await _validate_event_stream(mock_response, "job123", "test.json", errors) assert len(errors) == 1 assert "Missing vertex IDs in vertices_sorted event" in errors[0] @pytest.mark.asyncio async def test_missing_build_data(self): """Test validation fails when end_vertex event missing build_data.""" mock_response = Mock() mock_response.aiter_lines = Mock( return_value=AsyncIteratorMock( [ '{"event": "end_vertex", "job_id": "job123", "data": {}}', '{"event": "end", "job_id": "job123"}', ] ) ) errors = [] await _validate_event_stream(mock_response, "job123", "test.json", errors) assert len(errors) == 1 assert "Missing build_data in end_vertex event" in errors[0] @pytest.mark.asyncio async def test_event_stream_timeout(self): """Test validation handles timeout gracefully.""" class SlowAsyncIterator: """Async iterator that will cause timeout.""" def __aiter__(self): return self async def __anext__(self): await asyncio.sleep(10) # Will cause timeout return '{"event": "end", "job_id": "job123"}' mock_response = Mock() mock_response.aiter_lines = Mock(return_value=SlowAsyncIterator()) errors = [] await _validate_event_stream(mock_response, "job123", "test.json", errors) assert len(errors) == 1 assert "Flow execution timeout" in errors[0] @pytest.mark.asyncio async def test_common_event_types_ignored(self): """Test that common event types don't cause errors.""" mock_response = Mock() mock_response.aiter_lines = Mock( return_value=AsyncIteratorMock( [ '{"event": "message", "job_id": "job123"}', '{"event": "token", "job_id": "job123"}', '{"event": "add_message", "job_id": "job123"}', '{"event": "stream_closed", "job_id": "job123"}', '{"event": "end", "job_id": "job123"}', ] ) ) errors = [] await _validate_event_stream(mock_response, "job123", "test.json", errors) assert errors == [] @pytest.mark.asyncio async def test_vertices_sorted_without_end_vertex_events(self): """Test validation with vertices_sorted but no end_vertex events.""" mock_response = Mock() mock_response.aiter_lines = Mock( return_value=AsyncIteratorMock( [ '{"event": "vertices_sorted", "job_id": "job123", "data": {"ids": ["v1", "v2"]}}', '{"event": "end", "job_id": "job123"}', ] ) ) errors = [] await _validate_event_stream(mock_response, "job123", "test.json", errors) assert errors == [] @pytest.mark.asyncio async def test_vertex_count_tracking(self): """Test that vertex_count is properly tracked.""" mock_response = Mock() mock_response.aiter_lines = Mock( return_value=AsyncIteratorMock( [ '{"event": "vertices_sorted", "job_id": "job123", "data": {"ids": ["v1", "v2", "v3"]}}', '{"event": "end_vertex", "job_id": "job123", "data": {"build_data": {"result": "success"}}}', '{"event": "end_vertex", "job_id": "job123", "data": {"build_data": {"result": "success"}}}', '{"event": "end_vertex", "job_id": "job123", "data": {"build_data": {"result": "success"}}}', '{"event": "end", "job_id": "job123"}', ] ) ) errors = [] await _validate_event_stream(mock_response, "job123", "test.json", errors) assert errors == [] @pytest.mark.asyncio async def test_empty_lines_in_stream(self): """Test that empty lines in event stream are properly handled.""" mock_response = Mock() mock_response.aiter_lines = Mock( return_value=AsyncIteratorMock( [ "", # Empty line '{"event": "vertices_sorted", "job_id": "job123", "data": {"ids": ["v1"]}}', "", # Another empty line '{"event": "end", "job_id": "job123"}', "", # Empty line at end ] ) ) errors = [] await _validate_event_stream(mock_response, "job123", "test.json", errors) assert errors == [] @pytest.mark.asyncio async def test_event_stream_validation_exception(self): """Test that event stream validation handles exceptions properly.""" mock_response = Mock() mock_response.aiter_lines = Mock( return_value=AsyncIteratorMock( [ '{"event": "end", "job_id": "job123"}', ] ) ) # Mock the json.loads to raise a different exception type errors = [] with patch("langflow.utils.template_validation.json.loads", side_effect=TypeError("Type error")): await _validate_event_stream(mock_response, "job123", "test.json", errors) assert len(errors) == 1 assert "Event stream validation failed: Type error" in errors[0]
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/utils/test_template_validation.py", "license": "MIT License", "lines": 602, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/tests/unit/utils/test_validate.py
"""Unit tests for validate.py utilities.""" import ast import warnings from unittest.mock import Mock, patch import pytest from lfx.custom.validate import ( _create_langflow_execution_context, add_type_ignores, build_class_constructor, compile_class_code, create_class, create_function, create_type_ignore_class, eval_function, execute_function, extract_class_code, extract_class_name, extract_function_name, find_names_in_code, get_default_imports, prepare_global_scope, validate_code, ) class TestAddTypeIgnores: """Test cases for add_type_ignores function.""" def test_adds_type_ignore_when_missing(self): """Test that TypeIgnore is added when not present.""" # Remove TypeIgnore if it exists if hasattr(ast, "TypeIgnore"): delattr(ast, "TypeIgnore") add_type_ignores() assert hasattr(ast, "TypeIgnore") assert issubclass(ast.TypeIgnore, ast.AST) assert ast.TypeIgnore._fields == () def test_does_nothing_when_already_exists(self): """Test that function doesn't modify existing TypeIgnore.""" # Ensure TypeIgnore exists first add_type_ignores() original_type_ignore = ast.TypeIgnore add_type_ignores() assert ast.TypeIgnore is original_type_ignore class TestValidateCode: """Test cases for validate_code function.""" def test_valid_code_with_function(self): """Test validation passes for valid code with function.""" code = """ def hello_world(): return "Hello, World!" """ result = validate_code(code) assert result["imports"]["errors"] == [] assert result["function"]["errors"] == [] def test_code_with_valid_imports(self): """Test validation passes for code with valid imports.""" code = """ import os import sys def get_path(): return os.path.join(sys.path[0], "test") """ result = validate_code(code) assert result["imports"]["errors"] == [] assert result["function"]["errors"] == [] def test_code_with_invalid_imports(self): """Test validation fails for code with invalid imports.""" code = """ import nonexistent_module def test_func(): return nonexistent_module.some_function() """ result = validate_code(code) assert len(result["imports"]["errors"]) == 1 assert "nonexistent_module" in result["imports"]["errors"][0] def test_code_with_syntax_error(self): """Test validation fails for code with syntax errors.""" code = """ def broken_function( return "incomplete" """ result = validate_code(code) # The function should catch the syntax error and return it in the results assert len(result["function"]["errors"]) >= 1 error_message = " ".join(result["function"]["errors"]) assert ( "SyntaxError" in error_message or "invalid syntax" in error_message or "was never closed" in error_message ) def test_code_with_function_execution_error(self): """Test validation fails when function execution fails.""" code = """ def error_function(): undefined_variable + 1 """ result = validate_code(code) # This should pass parsing but may fail execution assert result["imports"]["errors"] == [] def test_empty_code(self): """Test validation handles empty code.""" result = validate_code("") assert result["imports"]["errors"] == [] assert result["function"]["errors"] == [] def test_code_with_multiple_imports(self): """Test validation handles multiple imports.""" code = """ import os import sys import json import nonexistent1 import nonexistent2 def test_func(): return json.dumps({"path": os.getcwd()}) """ result = validate_code(code) assert len(result["imports"]["errors"]) == 2 assert any("nonexistent1" in err for err in result["imports"]["errors"]) assert any("nonexistent2" in err for err in result["imports"]["errors"]) @patch("lfx.custom.validate.logger") def test_logging_on_parse_error(self, mock_logger): """Test that parsing errors are logged.""" # Structlog doesn't have opt method, so hasattr(logger, "opt") returns False mock_logger.debug = Mock() code = "invalid python syntax +++" validate_code(code) # With structlog, we expect logger.debug to be called with exc_info=True mock_logger.debug.assert_called_with("Error parsing code", exc_info=True) class TestCreateLangflowExecutionContext: """Test cases for _create_langflow_execution_context function.""" def test_creates_context_with_langflow_imports(self): """Test that context includes langflow imports.""" # The function imports modules inside try/except blocks # We don't need to patch anything, just test it works context = _create_langflow_execution_context() # Check that the context contains the expected keys # The actual imports may succeed or fail, but the function should handle both cases assert isinstance(context, dict) # These keys should be present regardless of import success/failure expected_keys = ["DataFrame", "Message", "Data", "Component", "HandleInput", "Output", "TabInput"] for key in expected_keys: assert key in context, f"Expected key '{key}' not found in context" def test_creates_mock_classes_on_import_failure(self): """Test that mock classes are created when imports fail.""" # Test that the function handles import failures gracefully # by checking the actual implementation behavior with patch("builtins.__import__", side_effect=ImportError("Module not found")): context = _create_langflow_execution_context() # Even with import failures, the context should still be created assert isinstance(context, dict) # The function should create mock classes when imports fail if "DataFrame" in context: assert isinstance(context["DataFrame"], type) def test_includes_typing_imports(self): """Test that typing imports are included.""" context = _create_langflow_execution_context() assert "Any" in context assert "Dict" in context assert "List" in context assert "Optional" in context assert "Union" in context def test_does_not_include_pandas(self): """Test that pandas is not included in the langflow execution context.""" context = _create_langflow_execution_context() assert "pd" not in context class TestEvalFunction: """Test cases for eval_function function.""" def test_evaluates_simple_function(self): """Test evaluation of a simple function.""" function_string = """ def add_numbers(a, b): return a + b """ func = eval_function(function_string) assert callable(func) assert func(2, 3) == 5 def test_evaluates_function_with_default_args(self): """Test evaluation of function with default arguments.""" function_string = """ def greet(name="World"): return f"Hello, {name}!" """ func = eval_function(function_string) assert func() == "Hello, World!" assert func("Alice") == "Hello, Alice!" def test_raises_error_for_no_function(self): """Test that error is raised when no function is found.""" code_string = """ x = 42 y = "hello" """ with pytest.raises(ValueError, match="Function string does not contain a function"): eval_function(code_string) def test_finds_correct_function_among_multiple(self): """Test that the correct function is found when multiple exist.""" function_string = """ def helper(): return "helper" def main_function(): return "main" """ func = eval_function(function_string) # Should return one of the functions (implementation detail) assert callable(func) class TestExecuteFunction: """Test cases for execute_function function.""" def test_executes_function_with_args(self): """Test execution of function with arguments.""" code = """ def multiply(x, y): return x * y """ result = execute_function(code, "multiply", 4, 5) assert result == 20 def test_executes_function_with_kwargs(self): """Test execution of function with keyword arguments.""" code = """ def create_message(text, urgent=False): prefix = "URGENT: " if urgent else "" return prefix + text """ result = execute_function(code, "create_message", "Hello", urgent=True) assert result == "URGENT: Hello" def test_executes_function_with_imports(self): """Test execution of function that uses imports.""" code = """ import os def get_current_dir(): return os.getcwd() """ result = execute_function(code, "get_current_dir") assert isinstance(result, str) def test_raises_error_for_missing_module(self): """Test that error is raised for missing modules.""" code = """ import nonexistent_module def test_func(): return nonexistent_module.test() """ with pytest.raises(ModuleNotFoundError, match="Module nonexistent_module not found"): execute_function(code, "test_func") def test_raises_error_for_missing_function(self): """Test that error is raised when function doesn't exist.""" code = """ def existing_function(): return "exists" """ # The function should raise an error when the specified function doesn't exist with pytest.raises((ValueError, StopIteration)): execute_function(code, "nonexistent_function") class TestCreateFunction: """Test cases for create_function function.""" def test_creates_callable_function(self): """Test that a callable function is created.""" code = """ def square(x): return x ** 2 """ func = create_function(code, "square") assert callable(func) assert func(5) == 25 def test_handles_imports_in_function(self): """Test that imports within function are handled.""" code = """ import math def calculate_area(radius): return math.pi * radius ** 2 """ func = create_function(code, "calculate_area") result = func(2) assert abs(result - 12.566370614359172) < 0.0001 def test_handles_from_imports(self): """Test that from imports are handled correctly.""" code = """ from math import sqrt def hypotenuse(a, b): return sqrt(a**2 + b**2) """ func = create_function(code, "hypotenuse") assert func(3, 4) == 5.0 def test_raises_error_for_missing_module(self): """Test that error is raised for missing modules.""" code = """ import nonexistent_module def test_func(): return "test" """ with pytest.raises(ModuleNotFoundError, match="Module nonexistent_module not found"): create_function(code, "test_func") class TestCreateClass: """Test cases for create_class function.""" def test_creates_simple_class(self): """Test creation of a simple class.""" code = """ class TestClass: def __init__(self, value=None): self.value = value def get_value(self): return self.value """ cls = create_class(code, "TestClass") instance = cls() assert hasattr(instance, "__init__") assert hasattr(instance, "get_value") def test_handles_class_with_imports(self): """Test creation of class that uses imports.""" code = """ import json class JsonHandler: def __init__(self): self.data = {} def to_json(self): return json.dumps(self.data) """ cls = create_class(code, "JsonHandler") instance = cls() assert hasattr(instance, "to_json") def test_replaces_legacy_imports(self): """Test that legacy import statements are replaced.""" code = """ from langflow import CustomComponent class MyComponent(CustomComponent): def build(self): return "test" """ # Should not raise an error due to import replacement with patch("lfx.custom.validate.prepare_global_scope") as mock_prepare: mock_prepare.return_value = {"CustomComponent": type("CustomComponent", (), {})} with patch("lfx.custom.validate.extract_class_code") as mock_extract: mock_extract.return_value = Mock() with patch("lfx.custom.validate.compile_class_code") as mock_compile: mock_compile.return_value = compile("pass", "<string>", "exec") with patch("lfx.custom.validate.build_class_constructor") as mock_build: mock_build.return_value = lambda: None create_class(code, "MyComponent") def test_handles_syntax_error(self): """Test that syntax errors are handled properly.""" code = """ class BrokenClass def __init__(self): pass """ with pytest.raises(ValueError, match="Syntax error in code"): create_class(code, "BrokenClass") def test_handles_validation_error(self): """Test that validation errors are handled properly.""" code = """ class TestClass: def __init__(self): pass """ # Create a proper ValidationError instance from pydantic_core import ValidationError as CoreValidationError validation_error = CoreValidationError.from_exception_data("TestClass", []) with ( patch("lfx.custom.validate.prepare_global_scope", side_effect=validation_error), pytest.raises(ValueError, match=r".*"), ): create_class(code, "TestClass") class TestHelperFunctions: """Test cases for helper functions.""" def test_create_type_ignore_class(self): """Test creation of TypeIgnore class.""" type_ignore_class = create_type_ignore_class() assert issubclass(type_ignore_class, ast.AST) assert type_ignore_class._fields == () def test_extract_function_name(self): """Test extraction of function name from code.""" code = """ def my_function(): return "test" """ name = extract_function_name(code) assert name == "my_function" def test_extract_function_name_no_function(self): """Test error when no function found.""" code = "x = 42" with pytest.raises(ValueError, match="No function definition found"): extract_function_name(code) def test_extract_class_name(self): """Test extraction of Component class name.""" code = """ class MyComponent(Component): def build(self): pass """ name = extract_class_name(code) assert name == "MyComponent" def test_extract_class_name_no_component(self): """Test error when no Component subclass found.""" code = """ class RegularClass: pass """ with pytest.raises(TypeError, match="No Component subclass found"): extract_class_name(code) def test_extract_class_name_syntax_error(self): """Test error handling for syntax errors in extract_class_name.""" code = "class BrokenClass" with pytest.raises(ValueError, match="Invalid Python code"): extract_class_name(code) def test_find_names_in_code(self): """Test finding specific names in code.""" code = "from typing import Optional, List\ndata: Optional[List[str]] = None" names = ["Optional", "List", "Dict", "Union"] found = find_names_in_code(code, names) assert found == {"Optional", "List"} def test_find_names_in_code_none_found(self): """Test when no names are found in code.""" code = "x = 42" names = ["Optional", "List"] found = find_names_in_code(code, names) assert found == set() class TestPrepareGlobalScope: """Test cases for prepare_global_scope function.""" def test_handles_imports(self): """Test that imports are properly handled.""" code = """ import os import sys def test(): pass """ module = ast.parse(code) scope = prepare_global_scope(module) assert "os" in scope assert "sys" in scope def test_handles_from_imports(self): """Test that from imports are properly handled.""" code = """ from os import path from sys import version def test(): pass """ module = ast.parse(code) scope = prepare_global_scope(module) assert "path" in scope assert "version" in scope def test_handles_import_errors(self): """Test that import errors are properly raised.""" code = """ import nonexistent_module def test(): pass """ module = ast.parse(code) with pytest.raises(ModuleNotFoundError, match="No module named 'nonexistent_module'"): prepare_global_scope(module) def test_handles_langchain_warnings(self): """Test that langchain warnings are suppressed.""" code = """ from langchain_core.messages import BaseMessage def test(): pass """ module = ast.parse(code) with patch("importlib.import_module") as mock_import: mock_module = Mock() mock_module.BaseMessage = Mock() mock_import.return_value = mock_module with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") prepare_global_scope(module) # Should not have langchain warnings langchain_warnings = [warning for warning in w if "langchain" in str(warning.message).lower()] assert len(langchain_warnings) == 0 def test_executes_definitions(self): """Test that class and function definitions are executed.""" code = """ def helper(): return "helper" class TestClass: value = 42 """ module = ast.parse(code) scope = prepare_global_scope(module) assert "helper" in scope assert "TestClass" in scope assert callable(scope["helper"]) assert scope["TestClass"].value == 42 class TestClassCodeOperations: """Test cases for class code operation functions.""" def test_extract_class_code(self): """Test extraction of class code from module.""" code = """ def helper(): pass class MyClass: def method(self): pass """ module = ast.parse(code) class_code = extract_class_code(module, "MyClass") assert isinstance(class_code, ast.ClassDef) assert class_code.name == "MyClass" def test_compile_class_code(self): """Test compilation of class code.""" code = """ class TestClass: def method(self): return "test" """ module = ast.parse(code) class_code = extract_class_code(module, "TestClass") compiled = compile_class_code(class_code) assert compiled is not None def test_build_class_constructor(self): """Test building class constructor.""" code = """ class SimpleClass: def __init__(self): self.value = "test" """ module = ast.parse(code) class_code = extract_class_code(module, "SimpleClass") compiled = compile_class_code(class_code) constructor = build_class_constructor(compiled, {}, "SimpleClass") assert constructor is not None class TestGetDefaultImports: """Test cases for get_default_imports function.""" @patch("lfx.field_typing.constants.CUSTOM_COMPONENT_SUPPORTED_TYPES", {"TestType": Mock()}) def test_returns_default_imports(self): """Test that default imports are returned.""" code = "TestType and Optional" with patch("importlib.import_module") as mock_import: mock_module = Mock() mock_module.TestType = Mock() mock_import.return_value = mock_module imports = get_default_imports(code) assert "Optional" in imports assert "List" in imports assert "Dict" in imports assert "Union" in imports def test_includes_langflow_imports(self): """Test that langflow imports are included when found in code.""" # Use an actual type from CUSTOM_COMPONENT_SUPPORTED_TYPES code = "Chain is used here" with patch("lfx.custom.validate.importlib") as mock_importlib: mock_module = Mock() mock_module.Chain = Mock() mock_importlib.import_module.return_value = mock_module imports = get_default_imports(code) assert "Chain" in imports
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/utils/test_validate.py", "license": "MIT License", "lines": 540, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/base/langflow/alembic/versions/3162e83e485f_add_auth_settings_to_folder_and_merge.py
"""Add auth_settings column to folder table and merge migration branches. Revision ID: 3162e83e485f Revises: 0ae3a2674f32, d9a6ea21edcd Create Date: 2025-01-16 13:00:00.000000 """ from collections.abc import Sequence import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision: str = "3162e83e485f" down_revision: str | Sequence[str] | None = ("0ae3a2674f32", "d9a6ea21edcd") branch_labels: str | Sequence[str] | None = None depends_on: str | Sequence[str] | None = None def upgrade() -> None: """Add auth_settings column to folder table and merge migration branches.""" conn = op.get_bind() inspector = sa.inspect(conn) # Check if folder table exists table_names = inspector.get_table_names() if "folder" not in table_names: # If folder table doesn't exist, skip this migration return # Get current column names in folder table column_names = [column["name"] for column in inspector.get_columns("folder")] # Add auth_settings column to folder table if it doesn't exist with op.batch_alter_table("folder", schema=None) as batch_op: if "auth_settings" not in column_names: batch_op.add_column(sa.Column("auth_settings", sa.JSON(), nullable=True)) def downgrade() -> None: """Remove auth_settings column from folder table.""" conn = op.get_bind() inspector = sa.inspect(conn) # Check if folder table exists table_names = inspector.get_table_names() if "folder" not in table_names: # If folder table doesn't exist, skip this migration return # Get current column names in folder table column_names = [column["name"] for column in inspector.get_columns("folder")] # Remove auth_settings column from folder table if it exists with op.batch_alter_table("folder", schema=None) as batch_op: if "auth_settings" in column_names: batch_op.drop_column("auth_settings")
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/base/langflow/alembic/versions/3162e83e485f_add_auth_settings_to_folder_and_merge.py", "license": "MIT License", "lines": 43, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
langflow-ai/langflow:src/backend/tests/unit/api/v1/test_rename_flow_to_save.py
import pytest from fastapi import status from httpx import AsyncClient @pytest.mark.asyncio async def test_duplicate_flow_name_basic(client: AsyncClient, logged_in_headers): """Test that duplicate flow names get numbered correctly.""" base_flow = { "name": "Test Flow", "description": "Test flow description", "data": {}, "is_component": False, } # Create first flow response1 = await client.post("api/v1/flows/", json=base_flow, headers=logged_in_headers) assert response1.status_code == status.HTTP_201_CREATED assert response1.json()["name"] == "Test Flow" # Create second flow with same name - should become "Test Flow (1)" response2 = await client.post("api/v1/flows/", json=base_flow, headers=logged_in_headers) assert response2.status_code == status.HTTP_201_CREATED assert response2.json()["name"] == "Test Flow (1)" # Create third flow with same name - should become "Test Flow (2)" response3 = await client.post("api/v1/flows/", json=base_flow, headers=logged_in_headers) assert response3.status_code == status.HTTP_201_CREATED assert response3.json()["name"] == "Test Flow (2)" @pytest.mark.asyncio async def test_duplicate_flow_name_with_numbers_in_original(client: AsyncClient, logged_in_headers): """Test duplication of flows with numbers in their original name.""" base_flow = { "name": "Untitled document (7)", "description": "Test flow description", "data": {}, "is_component": False, } # Create first flow response1 = await client.post("api/v1/flows/", json=base_flow, headers=logged_in_headers) assert response1.status_code == status.HTTP_201_CREATED assert response1.json()["name"] == "Untitled document (7)" # Create second flow with same name - should become "Untitled document (7) (1)" response2 = await client.post("api/v1/flows/", json=base_flow, headers=logged_in_headers) assert response2.status_code == status.HTTP_201_CREATED assert response2.json()["name"] == "Untitled document (7) (1)" # Create third flow with same name - should become "Untitled document (7) (2)" response3 = await client.post("api/v1/flows/", json=base_flow, headers=logged_in_headers) assert response3.status_code == status.HTTP_201_CREATED assert response3.json()["name"] == "Untitled document (7) (2)" @pytest.mark.asyncio async def test_duplicate_flow_name_with_non_numeric_suffixes(client: AsyncClient, logged_in_headers): """Test that non-numeric suffixes don't interfere with numbering.""" base_flow = { "name": "My Flow", "description": "Test flow description", "data": {}, "is_component": False, } # Create first flow response1 = await client.post("api/v1/flows/", json=base_flow, headers=logged_in_headers) assert response1.status_code == status.HTTP_201_CREATED assert response1.json()["name"] == "My Flow" # Create flow with non-numeric suffix backup_flow = base_flow.copy() backup_flow["name"] = "My Flow (Backup)" response2 = await client.post("api/v1/flows/", json=backup_flow, headers=logged_in_headers) assert response2.status_code == status.HTTP_201_CREATED assert response2.json()["name"] == "My Flow (Backup)" # Create another flow with original name - should become "My Flow (1)" # because "My Flow (Backup)" doesn't match the numeric pattern response3 = await client.post("api/v1/flows/", json=base_flow, headers=logged_in_headers) assert response3.status_code == status.HTTP_201_CREATED assert response3.json()["name"] == "My Flow (1)" @pytest.mark.asyncio async def test_duplicate_flow_name_gaps_in_numbering(client: AsyncClient, logged_in_headers): """Test that gaps in numbering are handled correctly (uses max + 1).""" base_flow = { "name": "Gapped Flow", "description": "Test flow description", "data": {}, "is_component": False, } # Create original flow response1 = await client.post("api/v1/flows/", json=base_flow, headers=logged_in_headers) assert response1.status_code == status.HTTP_201_CREATED assert response1.json()["name"] == "Gapped Flow" # Create numbered flows with gaps numbered_flows = [ "Gapped Flow (1)", "Gapped Flow (5)", # Gap: 2, 3, 4 missing "Gapped Flow (7)", # Gap: 6 missing ] for flow_name in numbered_flows: numbered_flow = base_flow.copy() numbered_flow["name"] = flow_name response = await client.post("api/v1/flows/", json=numbered_flow, headers=logged_in_headers) assert response.status_code == status.HTTP_201_CREATED assert response.json()["name"] == flow_name # Create another duplicate - should use max(1,5,7) + 1 = 8 response_final = await client.post("api/v1/flows/", json=base_flow, headers=logged_in_headers) assert response_final.status_code == status.HTTP_201_CREATED assert response_final.json()["name"] == "Gapped Flow (8)" @pytest.mark.asyncio async def test_duplicate_flow_name_special_characters(client: AsyncClient, logged_in_headers): """Test duplication with special characters in flow names.""" base_flow = { "name": "Flow-with_special@chars!", "description": "Test flow description", "data": {}, "is_component": False, } # Create first flow response1 = await client.post("api/v1/flows/", json=base_flow, headers=logged_in_headers) assert response1.status_code == status.HTTP_201_CREATED assert response1.json()["name"] == "Flow-with_special@chars!" # Create duplicate - should properly escape special characters in regex response2 = await client.post("api/v1/flows/", json=base_flow, headers=logged_in_headers) assert response2.status_code == status.HTTP_201_CREATED assert response2.json()["name"] == "Flow-with_special@chars! (1)" @pytest.mark.asyncio async def test_duplicate_flow_name_regex_patterns(client: AsyncClient, logged_in_headers): """Test that flow names containing regex special characters work correctly.""" base_flow = { "name": "Flow (.*) [test]", "description": "Test flow description", "data": {}, "is_component": False, } # Create first flow response1 = await client.post("api/v1/flows/", json=base_flow, headers=logged_in_headers) assert response1.status_code == status.HTTP_201_CREATED assert response1.json()["name"] == "Flow (.*) [test]" # Create duplicate response2 = await client.post("api/v1/flows/", json=base_flow, headers=logged_in_headers) assert response2.status_code == status.HTTP_201_CREATED assert response2.json()["name"] == "Flow (.*) [test] (1)"
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/api/v1/test_rename_flow_to_save.py", "license": "MIT License", "lines": 132, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/tests/unit/test_code_hash.py
"""Test code hash and module metadata functionality.""" import pytest from langflow.interface.components import import_langflow_components @pytest.mark.asyncio async def test_component_metadata_has_code_hash(): """Test that built-in components have valid module and code_hash metadata.""" result = await import_langflow_components() assert result is not None assert "components" in result assert len(result["components"]) > 0 # Find first component to test sample_category = None sample_component = None for category, components in result["components"].items(): if components: sample_category = category sample_component = next(iter(components.values())) break assert sample_component is not None, "No components found to test" # Test metadata presence - metadata should be in the 'metadata' sub-field assert "metadata" in sample_component, f"Metadata field missing from component in {sample_category}" # metadata = sample_component["metadata"] # assert "module" in metadata, f"Module metadata missing from component in {sample_category}" # assert "code_hash" in metadata, f"Code hash metadata missing from component in {sample_category}" # Test that values are valid # module_name = metadata["module"] # code_hash = metadata["code_hash"] # assert isinstance(module_name, str), f"Invalid module name type: {type(module_name)}" # assert module_name, f"Invalid module name: {module_name}" # assert isinstance(code_hash, str), f"Invalid code hash type: {type(code_hash)}" # assert len(code_hash) == 12, f"Invalid code hash: {code_hash} (should be 12 chars)" @pytest.mark.skip(reason="Skipping while metadata is not added") async def test_code_hash_uniqueness(): """Test that different built-in components have different code hashes.""" result = await import_langflow_components() all_hashes = [] for components in result["components"].values(): for comp in components.values(): metadata = comp.get("metadata", {}) if metadata.get("code_hash"): all_hashes.append(metadata["code_hash"]) # Check that we have some components with metadata assert len(all_hashes) > 0, "No components with code hashes found" # Check that we have reasonable uniqueness in hashes unique_hashes = len(set(all_hashes)) total_hashes = len(all_hashes) uniqueness_ratio = unique_hashes / total_hashes # Should have high uniqueness (most components have different code) # Adjusted threshold to 90% to account for legitimate code sharing between similar components assert uniqueness_ratio > 0.90, f"Hash uniqueness too low: {uniqueness_ratio:.1%}"
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/test_code_hash.py", "license": "MIT License", "lines": 50, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/base/langflow/api/v1/mcp_utils.py
"""Common MCP handler functions shared between mcp.py and mcp_projects.py. This module serves as the single source of truth for MCP functionality. """ import asyncio import base64 from collections.abc import Awaitable, Callable from contextvars import ContextVar from functools import wraps from pathlib import Path from typing import Any, ParamSpec, TypeVar from urllib.parse import quote, unquote, urlparse from uuid import uuid4 from lfx.base.mcp.constants import MAX_MCP_TOOL_NAME_LENGTH from lfx.base.mcp.util import get_flow_snake_case, get_unique_name, sanitize_mcp_name from lfx.log.logger import logger from lfx.utils.helpers import build_content_type_from_extension from mcp import types from sqlmodel import select from langflow.api.v1.endpoints import simple_run_flow from langflow.api.v1.schemas import SimplifiedAPIRequest from langflow.helpers.flow import json_schema_from_flow from langflow.schema.message import Message from langflow.services.database.models import Flow from langflow.services.database.models.file.model import File as UserFile from langflow.services.database.models.user.model import User from langflow.services.deps import get_settings_service, get_storage_service, session_scope T = TypeVar("T") P = ParamSpec("P") MCP_SERVERS_FILE = "_mcp_servers" # Create context variables current_user_ctx: ContextVar[User] = ContextVar("current_user_ctx") # Carries per-request variables injected via HTTP headers (e.g., X-Langflow-Global-Var-*) current_request_variables_ctx: ContextVar[dict[str, str] | None] = ContextVar( "current_request_variables_ctx", default=None ) def handle_mcp_errors(func: Callable[P, Awaitable[T]]) -> Callable[P, Awaitable[T]]: """Decorator to handle MCP endpoint errors consistently.""" @wraps(func) async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T: try: return await func(*args, **kwargs) except Exception as e: msg = f"Error in {func.__name__}: {e!s}" await logger.aexception(msg) raise return wrapper async def with_db_session(operation: Callable[[Any], Awaitable[T]]) -> T: """Execute an operation within a database session context.""" async with session_scope() as session: return await operation(session) class MCPConfig: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) cls._instance.enable_progress_notifications = None return cls._instance def get_mcp_config(): return MCPConfig() async def handle_list_resources(project_id=None): """Handle listing resources for MCP. Args: project_id: Optional project ID to filter resources by project """ resources = [] try: storage_service = get_storage_service() settings_service = get_settings_service() # Build full URL from settings host = getattr(settings_service.settings, "host", "localhost") port = getattr(settings_service.settings, "port", 3000) base_url = f"http://{host}:{port}".rstrip("/") try: current_user = current_user_ctx.get() except Exception as e: # noqa: BLE001 msg = f"Error getting current user: {e!s}" await logger.aexception(msg) current_user = None async with session_scope() as session: # Build query based on whether project_id is provided flows_query = select(Flow).where(Flow.folder_id == project_id) if project_id else select(Flow) flows = (await session.exec(flows_query)).all() for flow in flows: if flow.id: try: files = await storage_service.list_files(flow_id=str(flow.id)) for file_name in files: # URL encode the filename safe_filename = quote(file_name) resource = types.Resource( uri=f"{base_url}/api/v1/files/download/{flow.id}/{safe_filename}", name=file_name, description=f"File in flow: {flow.name}", mimeType=build_content_type_from_extension(file_name), ) resources.append(resource) except FileNotFoundError as e: msg = f"Error listing files for flow {flow.id}: {e}" await logger.adebug(msg) continue #################################################### # When a user uploads a file inside a flow # (e.g., via the File Read component), # it hits /api/v2/files (POST), # which saves files at the user-level. # So the above query for flow files is not enough. # So we list all user files for the current user. # This is not good. We need to fix this for 1.8.0. ################################################### if current_user: user_files_stmt = select(UserFile).where(UserFile.user_id == current_user.id) user_files = (await session.exec(user_files_stmt)).all() for user_file in user_files: stored_path = getattr(user_file, "path", "") or "" stored_filename = Path(stored_path).name if stored_path else user_file.name safe_filename = quote(stored_filename) if stored_filename.startswith(f"{MCP_SERVERS_FILE}_{current_user.id}"): # reserved file name for langflow MCP server config file(s) continue description = getattr(user_file, "provider", None) or "User file uploaded via File Manager" resource = types.Resource( uri=f"{base_url}/api/v1/files/download/{current_user.id}/{safe_filename}", name=stored_filename, description=description, mimeType=build_content_type_from_extension(stored_filename), ) resources.append(resource) except Exception as e: msg = f"Error in listing resources: {e!s}" await logger.aexception(msg) raise return resources async def handle_read_resource(uri: str) -> bytes: """Handle resource read requests.""" try: # Parse the URI properly parsed_uri = urlparse(str(uri)) # Path will be like /api/v1/files/download/{namespace}/{filename} path_parts = parsed_uri.path.split("/") # Remove empty strings from split path_parts = [p for p in path_parts if p] # The flow_id and filename should be the last two parts two = 2 if len(path_parts) < two: msg = f"Invalid URI format: {uri}" raise ValueError(msg) flow_id = path_parts[-2] filename = unquote(path_parts[-1]) # URL decode the filename storage_service = get_storage_service() # Read the file content content = await storage_service.get_file(flow_id=flow_id, file_name=filename) if not content: msg = f"File {filename} not found in flow {flow_id}" raise ValueError(msg) # Ensure content is base64 encoded if isinstance(content, str): content = content.encode() return base64.b64encode(content) except Exception as e: msg = f"Error reading resource {uri}: {e!s}" await logger.aexception(msg) raise async def handle_call_tool( name: str, arguments: dict, server, project_id=None, *, is_action=False ) -> list[types.TextContent]: """Handle tool execution requests. Args: name: Tool name arguments: Tool arguments server: MCP server instance project_id: Optional project ID to filter flows by project is_action: Whether to use action name for flow lookup """ mcp_config = get_mcp_config() if mcp_config.enable_progress_notifications is None: settings_service = get_settings_service() mcp_config.enable_progress_notifications = settings_service.settings.mcp_server_enable_progress_notifications current_user = current_user_ctx.get() # Build execution context with request-level variables if present request_variables = current_request_variables_ctx.get() exec_context = {"request_variables": request_variables} if request_variables else None async def execute_tool(session): # Get flow id from name flow = await get_flow_snake_case(name, current_user.id, session, is_action=is_action) if not flow: msg = f"Flow with name '{name}' not found" raise ValueError(msg) # If project_id is provided, verify the flow belongs to the project if project_id and flow.folder_id != project_id: msg = f"Flow '{name}' not found in project {project_id}" raise ValueError(msg) # Process inputs processed_inputs = dict(arguments) # Initial progress notification if mcp_config.enable_progress_notifications and (progress_token := server.request_context.meta.progressToken): await server.request_context.session.send_progress_notification( progress_token=progress_token, progress=0.0, total=1.0 ) conversation_id = str(uuid4()) input_request = SimplifiedAPIRequest( input_value=processed_inputs.get("input_value", ""), session_id=conversation_id ) async def send_progress_updates(progress_token): try: progress = 0.0 while True: await server.request_context.session.send_progress_notification( progress_token=progress_token, progress=min(0.9, progress), total=1.0 ) progress += 0.1 await asyncio.sleep(1.0) except asyncio.CancelledError: if mcp_config.enable_progress_notifications: await server.request_context.session.send_progress_notification( progress_token=progress_token, progress=1.0, total=1.0 ) raise collected_results = [] try: progress_task = None if mcp_config.enable_progress_notifications and server.request_context.meta.progressToken: progress_task = asyncio.create_task(send_progress_updates(server.request_context.meta.progressToken)) try: try: result = await simple_run_flow( flow=flow, input_request=input_request, stream=False, api_key_user=current_user, context=exec_context, ) # Process all outputs and messages, ensuring no duplicates processed_texts = set() def add_result(text: str): if text not in processed_texts: processed_texts.add(text) collected_results.append(types.TextContent(type="text", text=text)) for run_output in result.outputs: for component_output in run_output.outputs: # Handle messages for msg in component_output.messages or []: add_result(msg.message) # Handle results for value in (component_output.results or {}).values(): if isinstance(value, Message): add_result(value.get_text()) else: add_result(str(value)) except Exception as e: # noqa: BLE001 error_msg = f"Error Executing the {flow.name} tool. Error: {e!s}" collected_results.append(types.TextContent(type="text", text=error_msg)) return collected_results finally: if progress_task: progress_task.cancel() await asyncio.gather(progress_task, return_exceptions=True) except Exception: if mcp_config.enable_progress_notifications and ( progress_token := server.request_context.meta.progressToken ): await server.request_context.session.send_progress_notification( progress_token=progress_token, progress=1.0, total=1.0 ) raise try: return await with_db_session(execute_tool) except Exception as e: msg = f"Error executing tool {name}: {e!s}" await logger.aexception(msg) raise async def handle_list_tools(project_id=None, *, mcp_enabled_only=False): """Handle listing tools for MCP. Args: project_id: Optional project ID to filter tools by project mcp_enabled_only: Whether to filter for MCP-enabled flows only """ tools = [] try: async with session_scope() as session: # Build query based on parameters if project_id: # Filter flows by project and optionally by MCP enabled status flows_query = select(Flow).where(Flow.folder_id == project_id, Flow.is_component == False) # noqa: E712 if mcp_enabled_only: flows_query = flows_query.where(Flow.mcp_enabled == True) # noqa: E712 else: # Get all flows flows_query = select(Flow) flows = (await session.exec(flows_query)).all() existing_names = set() for flow in flows: if flow.user_id is None: continue # For project-specific tools, use action names if available if project_id: base_name = ( sanitize_mcp_name(flow.action_name) if flow.action_name else sanitize_mcp_name(flow.name) ) name = get_unique_name(base_name, MAX_MCP_TOOL_NAME_LENGTH, existing_names) description = flow.action_description or ( flow.description if flow.description else f"Tool generated from flow: {name}" ) else: # For global tools, use simple sanitized names base_name = sanitize_mcp_name(flow.name) name = base_name[:MAX_MCP_TOOL_NAME_LENGTH] if name in existing_names: i = 1 while True: suffix = f"_{i}" truncated_base = base_name[: MAX_MCP_TOOL_NAME_LENGTH - len(suffix)] candidate = f"{truncated_base}{suffix}" if candidate not in existing_names: name = candidate break i += 1 description = ( f"{flow.id}: {flow.description}" if flow.description else f"Tool generated from flow: {name}" ) try: tool = types.Tool( name=name, description=description, inputSchema=json_schema_from_flow(flow), ) tools.append(tool) existing_names.add(name) except Exception as e: # noqa: BLE001 msg = f"Error in listing tools: {e!s} from flow: {base_name}" await logger.awarning(msg) continue except Exception as e: msg = f"Error in listing tools: {e!s}" await logger.aexception(msg) raise return tools
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/base/langflow/api/v1/mcp_utils.py", "license": "MIT License", "lines": 336, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
langflow-ai/langflow:src/backend/base/langflow/services/database/session.py
class NoopSession: class NoopBind: class NoopConnect: async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): pass async def run_sync(self, fn, *args, **kwargs): # noqa: ARG002 return None def connect(self): return self.NoopConnect() bind = NoopBind() async def add(self, *args, **kwargs): pass async def commit(self): pass async def rollback(self): pass async def execute(self, *args, **kwargs): # noqa: ARG002 return None async def query(self, *args, **kwargs): # noqa: ARG002 return [] async def close(self): pass async def refresh(self, *args, **kwargs): pass async def delete(self, *args, **kwargs): pass async def __aenter__(self): return self async def __aexit__(self, exc_type, exc, tb): pass async def get(self, *args, **kwargs): # noqa: ARG002 return None async def exec(self, *args, **kwargs): # noqa: ARG002 class _NoopResult: def first(self): return None def all(self): return [] def one_or_none(self): return None def __iter__(self): return iter([]) return _NoopResult()
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/base/langflow/services/database/session.py", "license": "MIT License", "lines": 45, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
langflow-ai/langflow:src/backend/tests/unit/test_async_helpers.py
"""Tests for async_helpers.py functions.""" import asyncio import threading import time from unittest.mock import patch import pytest from lfx.utils.async_helpers import run_until_complete class TestRunUntilComplete: """Test the run_until_complete function.""" def test_run_until_complete_no_running_loop(self): """Test run_until_complete when no event loop is running.""" async def simple_coro(): return "test_result" # Should work when no loop is running result = run_until_complete(simple_coro()) assert result == "test_result" def test_run_until_complete_simple_coro_with_running_loop(self): """Test run_until_complete with a simple coroutine when loop is running.""" async def simple_coro(): return "from_thread" async def main_test(): # This should work with our fix - runs in separate thread return run_until_complete(simple_coro()) result = asyncio.run(main_test()) assert result == "from_thread" def test_run_until_complete_complex_coro_with_running_loop(self): """Test run_until_complete with a complex async coroutine when loop is running.""" async def complex_coro(): await asyncio.sleep(0.01) # This requires event loop cooperation return "complex_result" async def main_test(): # This would deadlock with old implementation that calls loop.run_until_complete # using the running loop return run_until_complete(complex_coro()) result = asyncio.run(main_test()) assert result == "complex_result" def test_run_until_complete_with_exception_in_new_thread(self): """Test that exceptions in the new thread are properly propagated.""" async def failing_coro(): msg = "Test exception" raise ValueError(msg) async def main_test(): with pytest.raises(ValueError, match="Test exception"): run_until_complete(failing_coro()) asyncio.run(main_test()) def test_run_until_complete_preserves_return_value(self): """Test that complex return values are preserved across threads.""" async def return_complex(): return {"key": "value", "list": [1, 2, 3], "nested": {"inner": "data"}} async def main_test(): return run_until_complete(return_complex()) result = asyncio.run(main_test()) expected = {"key": "value", "list": [1, 2, 3], "nested": {"inner": "data"}} assert result == expected def test_run_until_complete_thread_isolation(self): """Test that thread-local data is properly isolated.""" # Set up thread-local storage local_data = threading.local() local_data.value = "main_thread" async def check_thread_isolation(): # This should NOT have access to main thread's local data try: return getattr(local_data, "value", "no_value") except AttributeError: return "no_value" async def main_test(): # Confirm main thread has the value assert getattr(local_data, "value", None) == "main_thread" # Check that new thread doesn't have access return run_until_complete(check_thread_isolation()) result = asyncio.run(main_test()) assert result == "no_value" # Thread isolation working def test_run_until_complete_concurrent_execution(self): """Test that multiple concurrent calls work correctly.""" async def delayed_coro(delay, value): await asyncio.sleep(delay) return f"result_{value}" async def main_test(): # Run multiple coroutines concurrently import concurrent.futures with concurrent.futures.ThreadPoolExecutor() as executor: futures = [executor.submit(run_until_complete, delayed_coro(0.01, i)) for i in range(3)] return [f.result() for f in futures] results = asyncio.run(main_test()) expected = ["result_0", "result_1", "result_2"] assert results == expected def test_run_until_complete_performance_impact(self): """Test that the performance impact is reasonable.""" async def quick_coro(): return "quick" async def main_test(): # Time multiple executions start_time = time.time() for _ in range(10): result = run_until_complete(quick_coro()) assert result == "quick" end_time = time.time() return end_time - start_time duration = asyncio.run(main_test()) # Should complete 10 executions in reasonable time (less than 1 second) assert duration < 1.0, f"Performance test took too long: {duration}s" def test_run_until_complete_nested_async_operations(self): """Test with nested async operations that require event loop.""" async def inner_async(): await asyncio.sleep(0.001) return "inner" async def outer_async(): # This creates tasks that need event loop scheduling tasks = [asyncio.create_task(inner_async()) for _ in range(3)] return await asyncio.gather(*tasks) async def main_test(): # This would definitely deadlock with old implementation return run_until_complete(outer_async()) result = asyncio.run(main_test()) assert result == ["inner", "inner", "inner"] def test_run_until_complete_with_timeout(self): """Test that timeouts work correctly in the new thread.""" async def slow_coro(): await asyncio.sleep(10) # Very long delay return "should_not_reach" async def timeout_coro(): try: await asyncio.wait_for(slow_coro(), timeout=0.01) except asyncio.TimeoutError: return "timeout_occurred" return "no_timeout" async def main_test(): return run_until_complete(timeout_coro()) result = asyncio.run(main_test()) assert result == "timeout_occurred" def test_original_behavior_preserved_no_loop(self): """Test that original behavior is preserved when no loop is running.""" async def test_coro(): return "original_behavior" # Mock asyncio.run to verify it's called when no loop exists with patch("asyncio.run", return_value="mocked_result") as mock_run: result = run_until_complete(test_coro()) # Should have called asyncio.run (original behavior) mock_run.assert_called_once() assert result == "mocked_result"
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/test_async_helpers.py", "license": "MIT License", "lines": 140, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/tests/unit/components/bundles/langwatch/test_langwatch_component.py
import json import os from unittest.mock import Mock, patch import httpx import pytest import respx from httpx import Response from lfx.base.langwatch.utils import get_cached_evaluators from lfx.components.langwatch.langwatch import LangWatchComponent from lfx.schema.data import Data from lfx.schema.dotdict import dotdict from tests.base import ComponentTestBaseWithoutClient class TestLangWatchComponent(ComponentTestBaseWithoutClient): @pytest.fixture def component_class(self): """Return the component class to test.""" return LangWatchComponent @pytest.fixture def default_kwargs(self): """Return the default kwargs for the component.""" return { "evaluator_name": "test_evaluator", "api_key": "test_api_key", "input": "test input", "output": "test output", "expected_output": "expected output", "contexts": "context1, context2", "timeout": 30, } @pytest.fixture def file_names_mapping(self): """Return an empty list since this component doesn't have version-specific files.""" return [] @pytest.fixture def mock_evaluators(self): """Mock evaluators data.""" return { "test_evaluator": { "name": "test_evaluator", "requiredFields": ["input", "output"], "optionalFields": ["contexts"], "settings": { "temperature": { "description": "Temperature setting", "default": 0.7, } }, "settings_json_schema": { "properties": { "temperature": { "type": "number", "default": 0.7, } } }, }, "boolean_evaluator": { "name": "boolean_evaluator", "requiredFields": ["input"], "optionalFields": [], "settings": { "strict_mode": { "description": "Strict mode setting", "default": True, } }, "settings_json_schema": { "properties": { "strict_mode": { "type": "boolean", "default": True, } } }, }, } @pytest.fixture async def component(self, component_class, default_kwargs, mock_evaluators): """Return a component instance.""" comp = component_class(**default_kwargs) comp.evaluators = mock_evaluators return comp @pytest.fixture(autouse=True) def clear_cache(self): """Clear the LRU cache before each test.""" get_cached_evaluators.cache_clear() @patch("lfx.components.langwatch.langwatch.httpx.get") async def test_set_evaluators_success(self, mock_get, component, mock_evaluators): """Test successful setting of evaluators.""" mock_response = Mock() mock_response.json.return_value = {"evaluators": mock_evaluators} mock_response.raise_for_status.return_value = None mock_get.return_value = mock_response endpoint = "https://app.langwatch.ai" component.set_evaluators(endpoint) assert component.evaluators == mock_evaluators @patch("lfx.components.langwatch.langwatch.httpx.get") async def test_set_evaluators_empty_response(self, mock_get, component): """Test setting evaluators with empty response.""" mock_response = Mock() mock_response.json.return_value = {"evaluators": {}} mock_response.raise_for_status.return_value = None mock_get.return_value = mock_response endpoint = "https://app.langwatch.ai" with pytest.raises(ValueError, match="No evaluators found"): component.set_evaluators(endpoint) def test_get_dynamic_inputs(self, component, mock_evaluators): """Test dynamic input generation.""" evaluator = mock_evaluators["test_evaluator"] dynamic_inputs = component.get_dynamic_inputs(evaluator) # Should create inputs for contexts (from optionalFields) assert "contexts" in dynamic_inputs # Should create inputs for temperature (from settings) assert "temperature" in dynamic_inputs def test_get_dynamic_inputs_with_boolean_setting(self, component, mock_evaluators): """Test dynamic input generation with boolean settings.""" evaluator = mock_evaluators["boolean_evaluator"] dynamic_inputs = component.get_dynamic_inputs(evaluator) # Should create boolean input for strict_mode assert "strict_mode" in dynamic_inputs def test_get_dynamic_inputs_error_handling(self, component): """Test error handling in dynamic input generation.""" # Test with invalid evaluator data invalid_evaluator = {"invalid": "data"} result = component.get_dynamic_inputs(invalid_evaluator) assert result == {} @patch.dict(os.environ, {"LANGWATCH_ENDPOINT": "https://test.langwatch.ai"}) def test_update_build_config_basic(self, component, mock_evaluators): """Test basic build config update.""" build_config = dotdict( { "evaluator_name": {"options": [], "value": None}, "api_key": {"value": "test_key"}, "code": {"value": ""}, "_type": {"value": ""}, "input": {"value": ""}, "output": {"value": ""}, "timeout": {"value": 30}, } ) # Mock the get_evaluators method (which doesn't exist, so create it) def mock_get_evaluators(endpoint): # noqa: ARG001 return mock_evaluators with patch.object(component, "get_evaluators", side_effect=mock_get_evaluators, create=True): result = component.update_build_config(build_config, None, None) # Should populate evaluator options assert "test_evaluator" in result["evaluator_name"]["options"] assert "boolean_evaluator" in result["evaluator_name"]["options"] @patch.dict(os.environ, {"LANGWATCH_ENDPOINT": "https://test.langwatch.ai"}) def test_update_build_config_with_evaluator_selection(self, component, mock_evaluators): """Test build config update with evaluator selection.""" build_config = dotdict( { "evaluator_name": {"options": [], "value": None}, "api_key": {"value": "test_key"}, "code": {"value": ""}, "_type": {"value": ""}, "input": {"value": ""}, "output": {"value": ""}, "timeout": {"value": 30}, } ) # Mock the get_evaluators method (which doesn't exist, so create it) def mock_get_evaluators(endpoint): # noqa: ARG001 return mock_evaluators with patch.object(component, "get_evaluators", side_effect=mock_get_evaluators, create=True): # Initialize current_evaluator attribute component.current_evaluator = None result = component.update_build_config(build_config, "test_evaluator", "evaluator_name") # Should set the selected evaluator assert result["evaluator_name"]["value"] == "test_evaluator" @patch("lfx.components.langwatch.langwatch.httpx.get") @respx.mock async def test_evaluate_success(self, mock_get, component, mock_evaluators): """Test successful evaluation.""" # Mock the evaluators HTTP request mock_response = Mock() mock_response.json.return_value = {"evaluators": mock_evaluators} mock_response.raise_for_status.return_value = None mock_get.return_value = mock_response # Mock the evaluation endpoint eval_url = "https://app.langwatch.ai/api/evaluations/test_evaluator/evaluate" expected_response = {"score": 0.95, "reasoning": "Good evaluation"} respx.post(eval_url).mock(return_value=Response(200, json=expected_response)) # Set up component component.evaluator_name = "test_evaluator" component.api_key = "test_api_key" component.input = "test input" component.output = "test output" component.contexts = "context1, context2" result = await component.evaluate() assert isinstance(result, Data) assert result.data == expected_response @respx.mock async def test_evaluate_no_api_key(self, component): """Test evaluation with missing API key.""" component.api_key = None result = await component.evaluate() assert isinstance(result, Data) assert result.data["error"] == "API key is required" async def test_evaluate_no_evaluators(self, component): """Test evaluation when no evaluators are available.""" component.api_key = "test_api_key" component.evaluator_name = None # Mock set_evaluators to avoid external HTTP calls with patch.object(component, "set_evaluators"): component.evaluators = {} # Set empty evaluators directly component.current_evaluator = None # Initialize the attribute result = await component.evaluate() assert isinstance(result, Data) assert "No evaluator selected" in result.data["error"] @patch("lfx.components.langwatch.langwatch.httpx.get") @respx.mock async def test_evaluate_evaluator_not_found(self, mock_get, component, mock_evaluators): """Test evaluation with non-existent evaluator.""" # Mock evaluators HTTP request mock_response = Mock() mock_response.json.return_value = {"evaluators": mock_evaluators} mock_response.raise_for_status.return_value = None mock_get.return_value = mock_response component.api_key = "test_api_key" component.evaluator_name = "non_existent_evaluator" result = await component.evaluate() assert isinstance(result, Data) assert "Selected evaluator 'non_existent_evaluator' not found" in result.data["error"] @patch("lfx.components.langwatch.langwatch.httpx.get") @respx.mock async def test_evaluate_http_error(self, mock_get, component, mock_evaluators): """Test evaluation with HTTP error.""" # Mock evaluators HTTP request mock_response = Mock() mock_response.json.return_value = {"evaluators": mock_evaluators} mock_response.raise_for_status.return_value = None mock_get.return_value = mock_response # Mock evaluation endpoint with error eval_url = "https://app.langwatch.ai/api/evaluations/test_evaluator/evaluate" respx.post(eval_url).mock(side_effect=httpx.RequestError("Connection failed")) component.api_key = "test_api_key" component.evaluator_name = "test_evaluator" component.input = "test input" component.output = "test output" result = await component.evaluate() assert isinstance(result, Data) assert "Evaluation error" in result.data["error"] @patch("lfx.components.langwatch.langwatch.httpx.get") @respx.mock async def test_evaluate_with_tracing(self, mock_get, component, mock_evaluators): """Test evaluation with tracing service.""" # Mock evaluators HTTP request mock_response = Mock() mock_response.json.return_value = {"evaluators": mock_evaluators} mock_response.raise_for_status.return_value = None mock_get.return_value = mock_response # Mock evaluation endpoint eval_url = "https://app.langwatch.ai/api/evaluations/test_evaluator/evaluate" expected_response = {"score": 0.95, "reasoning": "Good evaluation"} # Set up request capture request_data = None def capture_request(request): nonlocal request_data request_data = json.loads(request.content.decode()) return Response(200, json=expected_response) respx.post(eval_url).mock(side_effect=capture_request) # Set up component with mock tracing component.api_key = "test_api_key" component.evaluator_name = "test_evaluator" component.input = "test input" component.output = "test output" # Mock tracing service mock_tracer = Mock() mock_tracer.trace_id = "test_trace_id" component._tracing_service = Mock() component._tracing_service.get_tracer.return_value = mock_tracer result = await component.evaluate() # Verify trace_id was included in the request assert request_data["settings"]["trace_id"] == "test_trace_id" assert isinstance(result, Data) assert result.data == expected_response @patch("lfx.components.langwatch.langwatch.httpx.get") @respx.mock async def test_evaluate_with_contexts_parsing(self, mock_get, component, mock_evaluators): """Test evaluation with contexts parsing.""" # Mock evaluators HTTP request mock_response = Mock() mock_response.json.return_value = {"evaluators": mock_evaluators} mock_response.raise_for_status.return_value = None mock_get.return_value = mock_response # Mock evaluation endpoint eval_url = "https://app.langwatch.ai/api/evaluations/test_evaluator/evaluate" expected_response = {"score": 0.95, "reasoning": "Good evaluation"} # Set up request capture request_data = None def capture_request(request): nonlocal request_data request_data = json.loads(request.content.decode()) return Response(200, json=expected_response) respx.post(eval_url).mock(side_effect=capture_request) # Set up component component.api_key = "test_api_key" component.evaluator_name = "test_evaluator" component.input = "test input" component.output = "test output" component.contexts = "context1, context2, context3" result = await component.evaluate() # Verify contexts were parsed correctly (contexts are split by comma, including whitespace) assert request_data["data"]["contexts"] == ["context1", " context2", " context3"] assert isinstance(result, Data) assert result.data == expected_response @patch("lfx.components.langwatch.langwatch.httpx.get") @respx.mock async def test_evaluate_timeout_handling(self, mock_get, component, mock_evaluators): """Test evaluation with timeout.""" # Mock evaluators HTTP request mock_response = Mock() mock_response.json.return_value = {"evaluators": mock_evaluators} mock_response.raise_for_status.return_value = None mock_get.return_value = mock_response # Mock evaluation endpoint with timeout eval_url = "https://app.langwatch.ai/api/evaluations/test_evaluator/evaluate" respx.post(eval_url).mock(side_effect=httpx.TimeoutException("Request timed out")) component.api_key = "test_api_key" component.evaluator_name = "test_evaluator" component.input = "test input" component.output = "test output" component.timeout = 5 result = await component.evaluate() assert isinstance(result, Data) assert "Evaluation error" in result.data["error"]
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/components/bundles/langwatch/test_langwatch_component.py", "license": "MIT License", "lines": 328, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/base/langflow/langflow_launcher.py
import os import platform import sys try: from dotenv import load_dotenv load_dotenv() except ImportError: pass from langflow.helpers.windows_postgres_helper import configure_windows_postgres_event_loop configure_windows_postgres_event_loop(source="launcher") import typer # noqa: E402 def main(): """Launches langflow with appropriate environment setup. On macOS, sets required environment variables and replaces current process. On Windows with PostgreSQL, configures event loop for psycopg compatibility. On other platforms, calls main function directly. """ if platform.system() == "Darwin": # macOS _launch_with_exec() else: # On non-macOS systems, call the main function directly from langflow.__main__ import main as langflow_main langflow_main() def _launch_with_exec(): """Launch langflow by replacing current process with properly configured environment. This approach is necessary because Objective-C libraries are preloaded by the Python runtime before any Python code executes. Setting OBJC_DISABLE_INITIALIZE_FORK_SAFETY within Python code is too late - it must be set in the parent process environment before spawning Python. Testing with OBJC_PRINT_INITIALIZE=YES confirms that NSCheapMutableString and other Objective-C classes are initialized during Python startup, before any user code runs. This causes fork safety issues when gunicorn or multiprocessing attempts to fork the process. The exec approach sets the environment variables and then replaces the current process with a new Python process. This is more efficient than subprocess since we don't need the launcher process to remain running, and signals are handled directly by the target process. """ # Set environment variables before exec os.environ["OBJC_DISABLE_INITIALIZE_FORK_SAFETY"] = "YES" # Additional fix for gunicorn compatibility os.environ["no_proxy"] = "*" try: os.execv(sys.executable, [sys.executable, "-m", "langflow.__main__", *sys.argv[1:]]) # noqa: S606 except OSError as e: # If exec fails, we need to exit since the process replacement failed typer.echo(f"Failed to exec langflow: {e}", file=sys.stderr) sys.exit(1)
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/base/langflow/langflow_launcher.py", "license": "MIT License", "lines": 48, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
langflow-ai/langflow:src/backend/tests/unit/api/v2/test_mcp_servers_file.py
import io import uuid from types import SimpleNamespace from typing import TYPE_CHECKING import pytest from fastapi import UploadFile # Module under test from langflow.api.v2.files import upload_user_file from langflow.api.v2.mcp import get_mcp_file if TYPE_CHECKING: from langflow.services.database.models.file.model import File as UserFile class FakeStorageService: # Minimal stub for storage interactions def __init__(self): # key -> bytes self._store: dict[str, bytes] = {} async def save_file(self, flow_id: str, file_name: str, data: bytes, *, append: bool = False): key = f"{flow_id}/{file_name}" if append and key in self._store: self._store[key] += data else: self._store[key] = data async def get_file_size(self, flow_id: str, file_name: str): return len(self._store.get(f"{flow_id}/{file_name}", b"")) async def delete_file(self, flow_id: str, file_name: str): self._store.pop(f"{flow_id}/{file_name}", None) class FakeResult: # Helper for Session.exec return def __init__(self, rows): self._rows = rows def first(self): return self._rows[0] if self._rows else None def all(self): return list(self._rows) class FakeSession: # Minimal async session stub def __init__(self): self._db: dict[str, UserFile] = {} async def exec(self, stmt): # Extremely simplified: detect by LIKE pattern or equality against name/id # We only support SELECT UserFile WHERE name LIKE pattern or id equality stmt_str = str(stmt) if "user_file.name" in stmt_str: # LIKE pattern extraction pattern = stmt_str.split("like(")[-1].split(")")[0].strip('"%') rows = [f for name, f in self._db.items() if name.startswith(pattern)] return FakeResult(rows) if "user_file.id" in stmt_str: uid = stmt_str.split("=")[-1].strip().strip("'") rows = [f for f in self._db.values() if str(f.id) == uid] return FakeResult(rows) return FakeResult([]) def add(self, obj): self._db[obj.name] = obj async def commit(self): return async def refresh(self, obj): # noqa: ARG002 return async def delete(self, obj): self._db.pop(obj.name, None) async def flush(self): return class FakeSettings: max_file_size_upload: int = 10 # MB @pytest.fixture def current_user(): class User(SimpleNamespace): id: str return User(id=str(uuid.uuid4())) @pytest.fixture def storage_service(): return FakeStorageService() @pytest.fixture def settings_service(): return SimpleNamespace(settings=FakeSettings()) @pytest.fixture def session(): return FakeSession() @pytest.mark.asyncio async def test_mcp_servers_upload_replace(session, storage_service, settings_service, current_user): """Uploading _mcp_servers.json twice should keep single DB record and no rename.""" content1 = b'{"mcpServers": {}}' mcp_file_ext = await get_mcp_file(current_user, extension=True) mcp_file = await get_mcp_file(current_user) file1 = UploadFile(filename=mcp_file_ext, file=io.BytesIO(content1)) file1.size = len(content1) # First upload await upload_user_file( file=file1, session=session, current_user=current_user, storage_service=storage_service, settings_service=settings_service, ) # DB should contain single entry named _mcp_servers assert list(session._db.keys()) == [mcp_file] # Upload again with different content content2 = b'{"mcpServers": {"everything": {}}}' file2 = UploadFile(filename=mcp_file_ext, file=io.BytesIO(content2)) file2.size = len(content2) await upload_user_file( file=file2, session=session, current_user=current_user, storage_service=storage_service, settings_service=settings_service, ) # Still single record, same name assert list(session._db.keys()) == [mcp_file] record = session._db[mcp_file] # Storage path should match user_id/_mcp_servers.json expected_path = f"{current_user.id}/{mcp_file}.json" assert record.path == expected_path # Storage should have updated content stored_bytes = storage_service._store[expected_path] assert stored_bytes == content2 # Third upload with server config provided by user content3 = ( b'{"mcpServers": {"everything": {"command": "npx", "args": ["-y", "@modelcontextprotocol/server-everything"]}}}' ) file3 = UploadFile(filename=mcp_file_ext, file=io.BytesIO(content3)) file3.size = len(content3) await upload_user_file( file=file3, session=session, current_user=current_user, storage_service=storage_service, settings_service=settings_service, ) stored_bytes = storage_service._store[expected_path] assert stored_bytes == content3 @pytest.mark.asyncio async def test_concurrent_update_server_should_not_lose_servers( session, storage_service, settings_service, current_user ): """Concurrent update_server() calls must not silently drop servers. Bug: update_server() performs a non-atomic read-modify-write cycle on the MCP config file. When two calls overlap, both read the same stale config, modify independently, and the last write wins — silently losing the first call's server. This causes the E2E test 'HTTP/SSE MCP server fields should persist after saving and editing' to fail because lf-starter_project gets wiped. """ import asyncio import copy from unittest.mock import MagicMock, patch from langflow.api.v2.mcp import update_server # Shared mutable state simulating the MCP config file on disk config_state = {"mcpServers": {"server_a": {"command": "echo", "args": ["a"]}}} async def mock_get_server_list(*_args, **_kwargs): result = copy.deepcopy(config_state) await asyncio.sleep(0) # Yield to allow interleaving between concurrent calls return result async def mock_upload_server_config(new_config, *_args, **_kwargs): await asyncio.sleep(0) # Yield config_state["mcpServers"] = dict(new_config["mcpServers"]) async def mock_get_server(name, *_args, **kwargs): server_list = kwargs.get("server_list", {}) return server_list.get("mcpServers", {}).get(name) with patch.multiple( "langflow.api.v2.mcp", get_server_list=mock_get_server_list, upload_server_config=mock_upload_server_config, get_server=mock_get_server, get_shared_component_cache_service=MagicMock(return_value=SimpleNamespace()), safe_cache_get=MagicMock(return_value={}), safe_cache_set=MagicMock(), ): await asyncio.gather( update_server( "server_b", {"command": "echo", "args": ["b"]}, current_user, session, storage_service, settings_service, ), update_server( "server_c", {"command": "echo", "args": ["c"]}, current_user, session, storage_service, settings_service, ), ) assert "server_a" in config_state["mcpServers"], "server_a was lost due to concurrent update_server race condition" assert "server_b" in config_state["mcpServers"], "server_b was lost due to concurrent update_server race condition" assert "server_c" in config_state["mcpServers"], "server_c was lost due to concurrent update_server race condition"
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/api/v2/test_mcp_servers_file.py", "license": "MIT License", "lines": 186, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/base/langflow/alembic/versions/d9a6ea21edcd_rename_default_folder.py
"""Rename default folder Revision ID: d9a6ea21edcd Revises: 66f72f04a1de Create Date: 2025-07-02 09:42:46.891585 """ from collections.abc import Sequence import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision: str = "d9a6ea21edcd" down_revision: str | None = "66f72f04a1de" branch_labels: str | Sequence[str] | None = None depends_on: str | Sequence[str] | None = None def upgrade() -> None: conn = op.get_bind() # Check if the folder table exists inspector = sa.inspect(conn) table_names = inspector.get_table_names() if "folder" not in table_names: # If folder table doesn't exist, skip this migration return # Rename "My Projects" to "Starter Project" only for users who don't already have a "Starter Project" folder # This prevents unique constraint violations update_query = sa.text(""" UPDATE folder SET name = 'Starter Project' WHERE name = 'My Projects' AND NOT EXISTS ( SELECT 1 FROM folder f2 WHERE f2.user_id = folder.user_id AND f2.name = 'Starter Project' ) """) conn.execute(update_query) def downgrade() -> None: conn = op.get_bind() # Check if the folder table exists inspector = sa.inspect(conn) table_names = inspector.get_table_names() if "folder" not in table_names: # If folder table doesn't exist, skip this migration return # Rename "Starter Project" back to "My Projects" only for users who don't already have a "My Projects" folder # This prevents unique constraint violations update_query = sa.text(""" UPDATE folder SET name = 'My Projects' WHERE name = 'Starter Project' AND NOT EXISTS ( SELECT 1 FROM folder f2 WHERE f2.user_id = folder.user_id AND f2.name = 'My Projects' ) """) conn.execute(update_query)
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/base/langflow/alembic/versions/d9a6ea21edcd_rename_default_folder.py", "license": "MIT License", "lines": 55, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
langflow-ai/langflow:src/backend/tests/unit/components/languagemodels/test_openai_model.py
from unittest.mock import MagicMock, patch import pytest from langchain_openai import ChatOpenAI from lfx.components.openai.openai_chat_model import OpenAIModelComponent from tests.api_keys import get_openai_api_key, has_api_key from tests.base import ComponentTestBaseWithoutClient class TestOpenAIModelComponent(ComponentTestBaseWithoutClient): @pytest.fixture def component_class(self): return OpenAIModelComponent @pytest.fixture def default_kwargs(self): return { "max_tokens": 1000, "model_kwargs": {}, "json_mode": False, "model_name": "gpt-4.1-nano", "openai_api_base": "https://api.openai.com/v1", "api_key": "test-api-key", "temperature": 0.1, "seed": 1, "max_retries": 5, "timeout": 700, } @pytest.fixture def file_names_mapping(self): # Provide an empty list or the actual mapping if versioned files exist return [] @patch("lfx.components.openai.openai_chat_model.ChatOpenAI") async def test_build_model(self, mock_chat_openai, component_class, default_kwargs): mock_instance = MagicMock() mock_chat_openai.return_value = mock_instance component = component_class(**default_kwargs) model = component.build_model() mock_chat_openai.assert_called_once_with( api_key="test-api-key", model_name="gpt-4.1-nano", max_tokens=1000, model_kwargs={}, base_url="https://api.openai.com/v1", seed=1, max_retries=5, timeout=700, temperature=0.1, ) assert model == mock_instance @patch("lfx.components.openai.openai_chat_model.ChatOpenAI") async def test_build_model_reasoning_model(self, mock_chat_openai, component_class, default_kwargs): mock_instance = MagicMock() mock_chat_openai.return_value = mock_instance default_kwargs["model_name"] = "o1" component = component_class(**default_kwargs) model = component.build_model() # For reasoning models, temperature and seed should be excluded mock_chat_openai.assert_called_once_with( api_key="test-api-key", model_name="o1", max_tokens=1000, model_kwargs={}, base_url="https://api.openai.com/v1", max_retries=5, timeout=700, ) assert model == mock_instance # Verify that temperature and seed are not in the parameters _args, kwargs = mock_chat_openai.call_args assert "temperature" not in kwargs assert "seed" not in kwargs @patch("lfx.components.openai.openai_chat_model.ChatOpenAI") async def test_build_model_with_json_mode(self, mock_chat_openai, component_class, default_kwargs): mock_instance = MagicMock() mock_bound_instance = MagicMock() mock_instance.bind.return_value = mock_bound_instance mock_chat_openai.return_value = mock_instance default_kwargs["json_mode"] = True component = component_class(**default_kwargs) model = component.build_model() mock_chat_openai.assert_called_once() mock_instance.bind.assert_called_once_with(response_format={"type": "json_object"}) assert model == mock_bound_instance @patch("lfx.components.openai.openai_chat_model.ChatOpenAI") async def test_build_model_no_api_key(self, mock_chat_openai, component_class, default_kwargs): mock_instance = MagicMock() mock_chat_openai.return_value = mock_instance default_kwargs["api_key"] = None component = component_class(**default_kwargs) component.build_model() # When api_key is None, it should be passed as None to ChatOpenAI _args, kwargs = mock_chat_openai.call_args assert kwargs["api_key"] is None @patch("lfx.components.openai.openai_chat_model.ChatOpenAI") async def test_build_model_max_tokens_zero(self, mock_chat_openai, component_class, default_kwargs): mock_instance = MagicMock() mock_chat_openai.return_value = mock_instance default_kwargs["max_tokens"] = 0 component = component_class(**default_kwargs) component.build_model() # When max_tokens is 0, it should be passed as None to ChatOpenAI _args, kwargs = mock_chat_openai.call_args assert kwargs["max_tokens"] is None async def test_get_exception_message_bad_request_error(self, component_class, default_kwargs): component_class(**default_kwargs) # Create a mock BadRequestError with a body attribute mock_error = MagicMock() mock_error.body = {"message": "test error message"} # Test the method directly by patching the import with patch("openai.BadRequestError", mock_error.__class__): # Manually call isinstance to avoid mocking it if hasattr(mock_error, "body"): message = mock_error.body.get("message") assert message == "test error message" async def test_get_exception_message_no_openai_import(self, component_class, default_kwargs): component = component_class(**default_kwargs) # Test when openai module is not available with patch.dict("sys.modules", {"openai": None}), patch("builtins.__import__", side_effect=ImportError): message = component._get_exception_message(Exception("test")) assert message is None async def test_get_exception_message_other_exception(self, component_class, default_kwargs): component = component_class(**default_kwargs) # Create a regular exception (not BadRequestError) regular_exception = ValueError("test error") # Create a simple mock for BadRequestError that the exception won't match class MockBadRequestError: pass with patch("openai.BadRequestError", MockBadRequestError): message = component._get_exception_message(regular_exception) assert message is None async def test_update_build_config_reasoning_model(self, component_class, default_kwargs): component = component_class(**default_kwargs) build_config = { "temperature": {"show": True}, "seed": {"show": True}, } # Test with reasoning model updated_config = component.update_build_config(build_config, "o1", "model_name") assert updated_config["temperature"]["show"] is False assert updated_config["seed"]["show"] is False # Test with regular model updated_config = component.update_build_config(build_config, "gpt-4", "model_name") assert updated_config["temperature"]["show"] is True assert updated_config["seed"]["show"] is True @pytest.mark.skipif(not has_api_key("OPENAI_API_KEY"), reason="OPENAI_API_KEY is not set or is empty") def test_build_model_integration(self): component = OpenAIModelComponent() try: component.api_key = get_openai_api_key() except ValueError: component.api_key = None component.model_name = "gpt-4.1-nano" component.temperature = 0.2 component.max_tokens = 1000 component.seed = 42 component.max_retries = 3 component.timeout = 600 component.openai_api_base = "https://api.openai.com/v1" model = component.build_model() assert isinstance(model, ChatOpenAI) assert model.model_name == "gpt-4.1-nano" assert model.openai_api_base == "https://api.openai.com/v1" @pytest.mark.skipif(not has_api_key("OPENAI_API_KEY"), reason="OPENAI_API_KEY is not set or is empty") def test_build_model_integration_reasoning(self): component = OpenAIModelComponent() component.api_key = get_openai_api_key() component.model_name = "o1" component.temperature = 0.2 # This should be ignored for reasoning models component.max_tokens = 1000 component.seed = 42 # This should be ignored for reasoning models component.max_retries = 3 component.timeout = 600 component.openai_api_base = "https://api.openai.com/v1" model = component.build_model() assert isinstance(model, ChatOpenAI) assert model.model_name == "o1" assert model.openai_api_base == "https://api.openai.com/v1"
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/components/languagemodels/test_openai_model.py", "license": "MIT License", "lines": 174, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/base/langflow/cli/progress.py
import platform import sys import threading import time from collections.abc import Generator from contextlib import contextmanager from typing import Any import click MIN_DURATION_THRESHOLD = 0.1 # Minimum duration to show in seconds (100ms) class ProgressIndicator: """A CLI progress indicator that shows user-friendly step-by-step progress. Shows animated loading indicators (□ → ■) for each step of the initialization process. """ def __init__(self, *, verbose: bool = False): self.verbose = verbose self.steps: list[dict[str, Any]] = [] self.current_step = 0 self.running = False self._stop_animation = False self._animation_thread: threading.Thread | None = None # Use Windows-safe characters on Windows to prevent encoding issues if platform.system() == "Windows": self._animation_chars = ["-", "\\", "|", "/"] # ASCII spinner self._success_icon = "+" # ASCII plus sign self._failure_icon = "x" # ASCII x self._farewell_emoji = ":)" # ASCII smiley else: self._animation_chars = ["□", "▢", "▣", "■"] # Unicode squares self._success_icon = "✓" # Unicode checkmark self._failure_icon = "✗" # Unicode cross self._farewell_emoji = "👋" # Unicode wave self._animation_index = 0 def add_step(self, title: str, description: str = "") -> None: """Add a step to the progress indicator.""" self.steps.append( { "title": title, "description": description, "status": "pending", # pending, running, completed, failed "start_time": None, "end_time": None, } ) def _animate_step(self, step_index: int) -> None: """Animate the current step with rotating square characters.""" if step_index >= len(self.steps): return step = self.steps[step_index] while self.running and step["status"] == "running" and not self._stop_animation: # Clear the current line and move cursor to beginning sys.stdout.write("\r") # Show the animated character animation_char = self._animation_chars[self._animation_index] # Print the step with animation line = f"{animation_char} {step['title']}..." sys.stdout.write(line) sys.stdout.flush() # Update animation self._animation_index = (self._animation_index + 1) % len(self._animation_chars) time.sleep(0.15) # Animation speed def start_step(self, step_index: int) -> None: """Start a specific step and begin animation.""" if step_index >= len(self.steps): return self.current_step = step_index step = self.steps[step_index] step["status"] = "running" step["start_time"] = time.time() self.running = True self._stop_animation = False # Start animation in a separate thread self._animation_thread = threading.Thread(target=self._animate_step, args=(step_index,)) self._animation_thread.daemon = True self._animation_thread.start() def complete_step(self, step_index: int, *, success: bool = True) -> None: """Complete a step and stop its animation.""" if step_index >= len(self.steps): return step = self.steps[step_index] step["status"] = "completed" if success else "failed" step["end_time"] = time.time() # Stop animation self._stop_animation = True if self._animation_thread and self._animation_thread.is_alive(): self._animation_thread.join(timeout=0.5) self.running = False # Clear the current line and print final result sys.stdout.write("\r") if success: icon = click.style(self._success_icon, fg="green", bold=True) title = click.style(step["title"], fg="green") else: icon = click.style(self._failure_icon, fg="red", bold=True) title = click.style(step["title"], fg="red") duration = "" if step["start_time"] and step["end_time"]: elapsed = step["end_time"] - step["start_time"] if self.verbose and elapsed > MIN_DURATION_THRESHOLD: # Only show duration if verbose and > 100ms duration = click.style(f" ({elapsed:.2f}s)", fg="bright_black") line = f"{icon} {title}{duration}" click.echo(line) def fail_step(self, step_index: int, error_msg: str = "") -> None: """Mark a step as failed.""" self.complete_step(step_index, success=False) if error_msg and self.verbose: click.echo(click.style(f" Error: {error_msg}", fg="red")) @contextmanager def step(self, step_index: int) -> Generator[None, None, None]: """Context manager for running a step with automatic completion.""" try: self.start_step(step_index) yield self.complete_step(step_index, success=True) except Exception as e: error_msg = str(e) if self.verbose else "" self.fail_step(step_index, error_msg) raise def print_summary(self) -> None: """Print a summary of all completed steps.""" if not self.verbose: return completed_steps = [s for s in self.steps if s["status"] in ["completed", "failed"]] if not completed_steps: return total_time = sum( (s["end_time"] - s["start_time"]) for s in completed_steps if s["start_time"] and s["end_time"] ) click.echo() click.echo(click.style(f"Total initialization time: {total_time:.2f}s", fg="bright_black")) def print_shutdown_summary(self) -> None: """Print a summary of all completed shutdown steps.""" if not self.verbose: return completed_steps = [s for s in self.steps if s["status"] in ["completed", "failed"]] if not completed_steps: return total_time = sum( (s["end_time"] - s["start_time"]) for s in completed_steps if s["start_time"] and s["end_time"] ) click.echo() click.echo(click.style(f"Total shutdown time: {total_time:.2f}s", fg="bright_black")) def create_langflow_progress(*, verbose: bool = False) -> ProgressIndicator: """Create a progress indicator with predefined Langflow initialization steps.""" progress = ProgressIndicator(verbose=verbose) # Define the initialization steps matching the order in main.py steps = [ ("Initializing Langflow", "Setting up basic configuration"), ("Checking Environment", "Loading environment variables and settings"), ("Starting Core Services", "Initializing database and core services"), ("Connecting Database", "Setting up database connection and migrations"), ("Loading Components", "Caching component types and custom components"), ("Adding Starter Projects", "Creating or updating starter project templates"), ("Launching Langflow", "Starting server and final setup"), ] for title, description in steps: progress.add_step(title, description) return progress def create_langflow_shutdown_progress(*, verbose: bool = False, multiple_workers: bool = False) -> ProgressIndicator: """Create a progress indicator with predefined Langflow shutdown steps.""" progress = ProgressIndicator(verbose=verbose) # Define the shutdown steps in reverse order of initialization if multiple_workers: import os steps = [ (f"[Worker PID {os.getpid()}] Stopping Server", "Gracefully stopping the web server"), ( f"[Worker PID {os.getpid()}] Cancelling Background Tasks", "Stopping file synchronization and background jobs", ), (f"[Worker PID {os.getpid()}] Cleaning Up Services", "Teardown database connections and services"), (f"[Worker PID {os.getpid()}] Clearing Temporary Files", "Removing temporary directories and cache"), (f"[Worker PID {os.getpid()}] Finalizing Shutdown", "Completing cleanup and logging"), ] else: steps = [ ("Stopping Server", "Gracefully stopping the web server"), ("Cancelling Background Tasks", "Stopping file synchronization and background jobs"), ("Cleaning Up Services", "Teardown database connections and services"), ("Clearing Temporary Files", "Removing temporary directories and cache"), ("Finalizing Shutdown", "Completing cleanup and logging"), ] for title, description in steps: progress.add_step(title, description) return progress
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/base/langflow/cli/progress.py", "license": "MIT License", "lines": 184, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
langflow-ai/langflow:src/backend/tests/unit/test_session_endpoint.py
from uuid import uuid4 import pytest from httpx import AsyncClient from langflow.memory import aadd_messagetables from langflow.services.database.models.message.model import MessageTable from langflow.services.deps import session_scope @pytest.fixture async def messages_with_flow_ids(session): # noqa: ARG001 """Create messages with different session_ids and flow_ids for testing sessions endpoint.""" async with session_scope() as _session: flow_id_1 = uuid4() flow_id_2 = uuid4() # Create MessageTable objects directly since MessageCreate doesn't have flow_id field messagetables = [ MessageTable( text="Message 1", sender="User", sender_name="User", session_id="session_A", flow_id=flow_id_1 ), MessageTable(text="Message 2", sender="AI", sender_name="AI", session_id="session_A", flow_id=flow_id_1), MessageTable( text="Message 3", sender="User", sender_name="User", session_id="session_B", flow_id=flow_id_1 ), MessageTable( text="Message 4", sender="User", sender_name="User", session_id="session_C", flow_id=flow_id_2 ), MessageTable(text="Message 5", sender="AI", sender_name="AI", session_id="session_D", flow_id=flow_id_2), MessageTable( text="Message 6", sender="User", sender_name="User", session_id="session_E", flow_id=None, # No flow_id ), ] created_messages = await aadd_messagetables(messagetables, _session) return { "messages": created_messages, "flow_id_1": flow_id_1, "flow_id_2": flow_id_2, "expected_sessions_flow_1": {"session_A", "session_B"}, "expected_sessions_flow_2": {"session_C", "session_D"}, "expected_all_sessions": {"session_A", "session_B", "session_C", "session_D", "session_E"}, } # Tests for /sessions endpoint @pytest.mark.api_key_required async def test_get_sessions_all(client: AsyncClient, logged_in_headers, messages_with_flow_ids): """Test getting all sessions without any filter.""" response = await client.get("api/v1/monitor/messages/sessions", headers=logged_in_headers) assert response.status_code == 200, response.text sessions = response.json() assert isinstance(sessions, list) # Convert to set for easier comparison since order doesn't matter returned_sessions = set(sessions) expected_sessions = messages_with_flow_ids["expected_all_sessions"] assert returned_sessions == expected_sessions assert len(sessions) == len(expected_sessions) @pytest.mark.api_key_required async def test_get_sessions_with_flow_id_filter(client: AsyncClient, logged_in_headers, messages_with_flow_ids): """Test getting sessions filtered by flow_id.""" flow_id_1 = messages_with_flow_ids["flow_id_1"] response = await client.get( "api/v1/monitor/messages/sessions", params={"flow_id": str(flow_id_1)}, headers=logged_in_headers ) assert response.status_code == 200, response.text sessions = response.json() assert isinstance(sessions, list) returned_sessions = set(sessions) expected_sessions = messages_with_flow_ids["expected_sessions_flow_1"] assert returned_sessions == expected_sessions assert len(sessions) == len(expected_sessions) @pytest.mark.api_key_required async def test_get_sessions_with_different_flow_id(client: AsyncClient, logged_in_headers, messages_with_flow_ids): """Test getting sessions filtered by a different flow_id.""" flow_id_2 = messages_with_flow_ids["flow_id_2"] response = await client.get( "api/v1/monitor/messages/sessions", params={"flow_id": str(flow_id_2)}, headers=logged_in_headers ) assert response.status_code == 200, response.text sessions = response.json() assert isinstance(sessions, list) returned_sessions = set(sessions) expected_sessions = messages_with_flow_ids["expected_sessions_flow_2"] assert returned_sessions == expected_sessions assert len(sessions) == len(expected_sessions) @pytest.mark.api_key_required async def test_get_sessions_with_non_existent_flow_id(client: AsyncClient, logged_in_headers): """Test getting sessions with a non-existent flow_id returns empty list.""" non_existent_flow_id = uuid4() response = await client.get( "api/v1/monitor/messages/sessions", params={"flow_id": str(non_existent_flow_id)}, headers=logged_in_headers ) assert response.status_code == 200, response.text sessions = response.json() assert isinstance(sessions, list) assert len(sessions) == 0 @pytest.mark.api_key_required async def test_get_sessions_empty_database(client: AsyncClient, logged_in_headers): """Test getting sessions when no messages exist in database.""" response = await client.get("api/v1/monitor/messages/sessions", headers=logged_in_headers) assert response.status_code == 200, response.text sessions = response.json() assert isinstance(sessions, list) assert len(sessions) == 0 @pytest.mark.api_key_required async def test_get_sessions_invalid_flow_id_format(client: AsyncClient, logged_in_headers): """Test getting sessions with invalid flow_id format returns 422.""" response = await client.get( "api/v1/monitor/messages/sessions", params={"flow_id": "invalid-uuid"}, headers=logged_in_headers ) assert response.status_code == 422, response.text assert "detail" in response.json()
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/test_session_endpoint.py", "license": "MIT License", "lines": 110, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/tests/unit/utils/test_interface_utils.py
import pytest from langflow.interface.utils import extract_input_variables_from_prompt @pytest.mark.parametrize( ("prompt", "expected"), [ # Basic variable extraction ("Hello {name}!", ["name"]), ("Hi {name}, you are {age} years old", ["name", "age"]), # Empty prompt ("", []), ("No variables here", []), # Duplicate variables ("Hello {name}! How are you {name}?", ["name"]), # Whitespace handling - Formatter preserves whitespace in field names ("Hello { name }!", [" name "]), ("Hi { name }, bye", [" name "]), # Multiple braces (escaping) ("Escaped {{not_a_var}}", []), ("Mixed {{escaped}} and {real_var}", ["real_var"]), ("Double escaped {{{{not_this}}}}", []), # Complex cases ("Hello {name}! Your score is {{4 + 5}}, age: {age}", ["name", "age"]), ("Nested {{obj['key']}} with {normal_var}", ["normal_var"]), ("Template {{user.name}} with {id} and {type}", ["id", "type"]), # Edge cases ("{single}", ["single"]), ("{{double}}", []), ("{{{}}}", []), # Multiple variables with various spacing ( """ Multi-line with {var1} and {var2} plus {var3} at the end """, ["var1", "var2", "var3"], ), ], ) def test_extract_input_variables(prompt, expected): """Test the extract_input_variables_from_prompt function with various cases.""" result = extract_input_variables_from_prompt(prompt) assert sorted(result) == sorted(expected), f"Failed for prompt: {prompt}" @pytest.mark.parametrize( ("prompt", "expected_error"), [ # Malformed format strings that should raise ValueError ("}{", "Single '}' encountered in format string"), ("{incomplete", "expected '}' before end of string"), ("incomplete}", "Single '}' encountered in format string"), ], ) def test_extract_input_variables_malformed(prompt, expected_error): """Test that malformed format strings raise ValueError.""" with pytest.raises(ValueError, match=expected_error): extract_input_variables_from_prompt(prompt)
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/utils/test_interface_utils.py", "license": "MIT License", "lines": 56, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/tests/unit/test_load_components.py
# ruff: noqa: T201 import asyncio import time import warnings import pytest from lfx.constants import BASE_COMPONENTS_PATH from lfx.interface.components import aget_all_types_dict, import_langflow_components class TestComponentLoading: """Test suite for comparing component loading methods performance and functionality.""" @pytest.fixture def base_components_path(self): """Fixture to provide BASE_COMPONENTS_PATH as a list.""" return [BASE_COMPONENTS_PATH] if BASE_COMPONENTS_PATH else [] @pytest.mark.no_blockbuster @pytest.mark.asyncio async def test_import_langflow_components_basic(self): """Test basic functionality of import_langflow_components.""" result = await import_langflow_components() assert isinstance(result, dict), "Result should be a dictionary" assert "components" in result, "Result should have 'components' key" assert isinstance(result["components"], dict), "Components should be a dictionary" # Check that we have some components loaded (non-failing for CI compatibility) total_components = sum(len(comps) for comps in result["components"].values()) print(f"Loaded {total_components} components") # Note: Component count may vary due to OS file limits, so we don't assert a minimum @pytest.mark.no_blockbuster @pytest.mark.asyncio async def test_aget_all_types_dict_basic(self, base_components_path): """Test basic functionality of aget_all_types_dict.""" result = await aget_all_types_dict(base_components_path) assert isinstance(result, dict), "Result should be a dictionary" # Note: aget_all_types_dict might return empty dict if no custom components in path # This is expected behavior when BASE_COMPONENTS_PATH points to built-in components @pytest.mark.no_blockbuster @pytest.mark.asyncio async def test_component_loading_performance_comparison(self, base_components_path): """Compare performance between import_langflow_components and aget_all_types_dict.""" # Warm up the functions (first calls might be slower due to imports) await import_langflow_components() await aget_all_types_dict(base_components_path) # Time import_langflow_components start_time = time.perf_counter() langflow_result = await import_langflow_components() langflow_duration = time.perf_counter() - start_time # Time aget_all_types_dict start_time = time.perf_counter() all_types_result = await aget_all_types_dict(base_components_path) all_types_duration = time.perf_counter() - start_time # Log performance metrics print("\nPerformance Comparison:") print(f"import_langflow_components: {langflow_duration:.4f}s") print(f"aget_all_types_dict: {all_types_duration:.4f}s") print(f"Ratio (langflow/all_types): {langflow_duration / max(all_types_duration, 0.0001):.2f}") # Both should complete in reasonable time # Add warnings for slow performance before failing if langflow_duration > 10.0: warnings.warn(f"import_langflow_components is slow: {langflow_duration:.2f}s", UserWarning, stacklevel=2) if all_types_duration > 20.0: warnings.warn(f"aget_all_types_dict is slow: {all_types_duration:.2f}s", UserWarning, stacklevel=2) # Store results for further analysis return { "langflow_result": langflow_result, "all_types_result": all_types_result, "langflow_duration": langflow_duration, "all_types_duration": all_types_duration, } @pytest.mark.no_blockbuster @pytest.mark.asyncio async def test_result_structure_comparison(self, base_components_path): """Compare the structure and content of results from both functions.""" langflow_result = await import_langflow_components() all_types_result = await aget_all_types_dict(base_components_path) # Check langflow result structure assert isinstance(langflow_result, dict) assert "components" in langflow_result langflow_components = langflow_result["components"] # Check all_types result structure assert isinstance(all_types_result, dict) # Get component counts (informational, non-failing) langflow_count = sum(len(comps) for comps in langflow_components.values()) all_types_count = sum(len(comps) for comps in all_types_result.values()) if all_types_result else 0 print("\nComponent Counts (informational):") print(f"import_langflow_components: {langflow_count} components") print(f"aget_all_types_dict: {all_types_count} components") # Log the comparison but don't fail the test if langflow_count != all_types_count: diff = abs(langflow_count - all_types_count) print(f"Note: Component counts differ by {diff} - this may be due to OS file limits") # Analyze component categories if langflow_components: langflow_categories = list(langflow_components.keys()) print(f"Langflow categories: {sorted(langflow_categories)}") if all_types_result: all_types_categories = list(all_types_result.keys()) print(f"All types categories: {sorted(all_types_categories)}") # Verify each category has proper structure for category, components in langflow_components.items(): assert isinstance(components, dict), f"Category {category} should contain dict of components" @pytest.mark.no_blockbuster @pytest.mark.asyncio async def test_component_template_structure(self): """Test that component templates have expected structure.""" langflow_result = await import_langflow_components() # Check that components have proper template structure for category, components in langflow_result["components"].items(): assert isinstance(components, dict), f"Category {category} should contain dict of components" for comp_name, comp_template in components.items(): assert isinstance(comp_template, dict), f"Component {comp_name} should be a dict" # Check for common template fields if comp_template: # Some might be empty during development # Common fields that should exist in component templates expected_fields = {"display_name", "type", "template"} present_fields = set(comp_template.keys()) # At least some expected fields should be present common_fields = expected_fields.intersection(present_fields) if len(common_fields) == 0 and comp_template: print(f"Warning: Component {comp_name} missing expected fields. Has: {list(present_fields)}") @pytest.mark.no_blockbuster @pytest.mark.asyncio async def test_concurrent_loading(self, base_components_path): """Test concurrent execution of both loading methods.""" # Run both functions concurrently tasks = [ import_langflow_components(), aget_all_types_dict(base_components_path), import_langflow_components(), # Run langflow loader twice to test consistency ] start_time = time.perf_counter() results = await asyncio.gather(*tasks) concurrent_duration = time.perf_counter() - start_time langflow_result1, all_types_result, langflow_result2 = results print(f"\nConcurrent execution took: {concurrent_duration:.4f}s") # Check that both results have the same structure and component counts assert isinstance(langflow_result1, dict) assert isinstance(langflow_result2, dict) assert isinstance(all_types_result, dict) # Check that both langflow results have the same component structure assert "components" in langflow_result1 assert "components" in langflow_result2 # Compare component counts (informational, non-failing) count1 = sum(len(comps) for comps in langflow_result1["components"].values()) count2 = sum(len(comps) for comps in langflow_result2["components"].values()) print(f"Component counts: {count1} vs {count2}") if count1 != count2: print("Note: Component counts differ - this may be due to OS file limits or timing") # Check that category names are the same categories1 = set(langflow_result1["components"].keys()) categories2 = set(langflow_result2["components"].keys()) if categories1 != categories2: missing_in_2 = categories1 - categories2 missing_in_1 = categories2 - categories1 print(f"Category differences: missing in result2: {missing_in_2}, missing in result1: {missing_in_1}") # This is acceptable as long as the main functionality is consistent # Check that component names within categories are the same for category in categories1.intersection(categories2): comps1 = set(langflow_result1["components"][category].keys()) comps2 = set(langflow_result2["components"][category].keys()) if comps1 != comps2: missing_in_2 = comps1 - comps2 missing_in_1 = comps2 - comps1 print( f"Component differences in {category}: " f"missing in result2: {missing_in_2}, missing in result1: {missing_in_1}" ) # The results might not be exactly identical due to timing or loading order # but the core structure should be consistent print("Note: Results may have minor differences due to concurrent loading, but structure is consistent") @pytest.mark.no_blockbuster @pytest.mark.asyncio async def test_memory_efficiency(self, base_components_path): """Test memory usage patterns of both loading methods.""" import gc # Force garbage collection before measuring gc.collect() initial_objects = len(gc.get_objects()) # Load with import_langflow_components langflow_result = await import_langflow_components() after_langflow_objects = len(gc.get_objects()) # Load with aget_all_types_dict all_types_result = await aget_all_types_dict(base_components_path) after_all_types_objects = len(gc.get_objects()) # Calculate object creation langflow_objects_created = after_langflow_objects - initial_objects all_types_objects_created = after_all_types_objects - after_langflow_objects print("\nMemory Analysis:") print(f"Objects created by import_langflow_components: {langflow_objects_created}") print(f"Objects created by aget_all_types_dict: {all_types_objects_created}") # Clean up del langflow_result, all_types_result gc.collect() @pytest.mark.no_blockbuster @pytest.mark.asyncio async def test_error_handling(self): """Test error handling in both loading methods.""" # Test with empty paths list for aget_all_types_dict empty_paths = [] # This should not raise an error, just return empty results result = await aget_all_types_dict(empty_paths) assert isinstance(result, dict), "Should return empty dict for empty paths" # Test with non-existent path - this should NOT raise an error, just return empty results nonexistent_paths = ["/nonexistent/path"] result = await aget_all_types_dict(nonexistent_paths) assert isinstance(result, dict), "Should return empty dict for non-existent paths" assert len(result) == 0, "Should return empty dict for non-existent paths" # Test with empty string path - this SHOULD raise an error empty_string_paths = [""] with pytest.raises(Exception) as exc_info: # noqa: PT011 await aget_all_types_dict(empty_string_paths) assert "path" in str(exc_info.value).lower(), f"Path-related error expected, got: {exc_info.value}" # import_langflow_components should work regardless of external paths result = await import_langflow_components() assert isinstance(result, dict) assert "components" in result @pytest.mark.no_blockbuster @pytest.mark.benchmark @pytest.mark.asyncio async def test_repeated_loading_performance(self, base_components_path): """Test performance of repeated loading operations.""" num_iterations = 5 # Test repeated import_langflow_components calls langflow_times = [] for _ in range(num_iterations): start_time = time.perf_counter() await import_langflow_components() duration = time.perf_counter() - start_time langflow_times.append(duration) # Test repeated aget_all_types_dict calls all_types_times = [] for _ in range(num_iterations): start_time = time.perf_counter() await aget_all_types_dict(base_components_path) duration = time.perf_counter() - start_time all_types_times.append(duration) # Calculate statistics langflow_avg = sum(langflow_times) / len(langflow_times) langflow_min = min(langflow_times) langflow_max = max(langflow_times) all_types_avg = sum(all_types_times) / len(all_types_times) all_types_min = min(all_types_times) all_types_max = max(all_types_times) print(f"\nRepeated Loading Performance ({num_iterations} iterations):") print( f"import_langflow_components - avg: {langflow_avg:.4f}s, min: {langflow_min:.4f}s, max: {langflow_max:.4f}s" ) print(f"aget_all_types_dict - avg: {all_types_avg:.4f}s, min: {all_types_min:.4f}s, max: {all_types_max:.4f}s") # Performance should be reasonably consistent langflow_variance = max(langflow_times) - min(langflow_times) all_types_variance = max(all_types_times) - min(all_types_times) # Variance shouldn't be too high (more than 10x difference between min and max) assert langflow_variance < langflow_avg * 10, ( f"import_langflow_components performance too inconsistent: {langflow_variance}s variance" ) assert all_types_variance < all_types_avg * 10, ( f"aget_all_types_dict performance too inconsistent: {all_types_variance}s variance" ) @pytest.mark.no_blockbuster @pytest.mark.asyncio async def test_components_path_variations(self): """Test aget_all_types_dict with different path configurations.""" test_cases = [ [], # Empty list [BASE_COMPONENTS_PATH] if BASE_COMPONENTS_PATH else [], # Normal case - valid path ] # Test invalid paths separately with proper error handling invalid_test_cases = [ [""], # Empty string path ["/tmp"], # Non-existent or invalid path #noqa: S108 [BASE_COMPONENTS_PATH, "/tmp"] # noqa: S108 if BASE_COMPONENTS_PATH else ["/tmp"], # Mixed valid/invalid paths #noqa: S108 ] # Test valid cases for i, paths in enumerate(test_cases): print(f"\nTesting valid path configuration {i}: {paths}") start_time = time.perf_counter() result = await aget_all_types_dict(paths) duration = time.perf_counter() - start_time assert isinstance(result, dict), f"Result should be dict for paths: {paths}" component_count = sum(len(comps) for comps in result.values()) print(f" Loaded {component_count} components in {duration:.4f}s") # Test invalid cases - different invalid paths behave differently for i, paths in enumerate(invalid_test_cases): print(f"\nTesting invalid path configuration {i}: {paths}") # Empty string paths raise errors, but non-existent paths just return empty results if any(path == "" for path in paths): # Empty string paths should raise an error with pytest.raises((ValueError, OSError, FileNotFoundError)) as exc_info: await aget_all_types_dict(paths) print(f" Expected error for empty string path: {exc_info.value}") assert "path" in str(exc_info.value).lower(), f"Path-related error expected, got: {exc_info.value}" else: # Non-existent paths should return empty results without raising result = await aget_all_types_dict(paths) assert isinstance(result, dict), f"Should return dict for non-existent paths: {paths}" component_count = sum(len(comps) for comps in result.values()) print(f" Non-existent path returned {component_count} components (expected 0)") @pytest.mark.no_blockbuster @pytest.mark.asyncio async def test_comprehensive_performance_summary(self, base_components_path): """Comprehensive test that provides a summary of all performance aspects.""" print("\n" + "=" * 80) print("COMPREHENSIVE COMPONENT LOADING PERFORMANCE SUMMARY") print("=" * 80) # WARM-UP RUNS (discard these timings) print("\nPerforming warm-up runs...") await import_langflow_components() # Warm up imports, thread pools, etc. await aget_all_types_dict(base_components_path) # Warm up custom component loading print("Warm-up completed.") # Now run the actual performance measurements num_runs = 3 langflow_results = [] all_types_results = [] for run in range(num_runs): print(f"\nPerformance Run {run + 1}/{num_runs}") # Time import_langflow_components start_time = time.perf_counter() langflow_result = await import_langflow_components() langflow_duration = time.perf_counter() - start_time langflow_results.append((langflow_duration, langflow_result)) # Time aget_all_types_dict start_time = time.perf_counter() all_types_result = await aget_all_types_dict(base_components_path) all_types_duration = time.perf_counter() - start_time all_types_results.append((all_types_duration, all_types_result)) print(f" import_langflow_components: {langflow_duration:.4f}s") print(f" aget_all_types_dict: {all_types_duration:.4f}s") # Calculate final statistics (excluding warm-up runs) langflow_times = [duration for duration, _ in langflow_results] all_types_times = [duration for duration, _ in all_types_results] print("\nSTEADY-STATE PERFORMANCE (after warm-up):") print("import_langflow_components:") print(f" Average: {sum(langflow_times) / len(langflow_times):.4f}s") print(f" Min: {min(langflow_times):.4f}s") print(f" Max: {max(langflow_times):.4f}s") print("aget_all_types_dict:") print(f" Average: {sum(all_types_times) / len(all_types_times):.4f}s") print(f" Min: {min(all_types_times):.4f}s") print(f" Max: {max(all_types_times):.4f}s") # Component count analysis langflow_component_counts = [] all_types_component_counts = [] for _, result in langflow_results: count = sum(len(comps) for comps in result.get("components", {}).values()) langflow_component_counts.append(count) for _, result in all_types_results: count = sum(len(comps) for comps in result.values()) all_types_component_counts.append(count) print("\nCOMPONENT COUNTS:") print(f"import_langflow_components: {langflow_component_counts}") print(f"aget_all_types_dict: {all_types_component_counts}") # Determine which is faster (based on steady-state performance) avg_langflow = sum(langflow_times) / len(langflow_times) avg_all_types = sum(all_types_times) / len(all_types_times) if avg_langflow < avg_all_types: faster_method = "import_langflow_components" speedup = avg_all_types / avg_langflow else: faster_method = "aget_all_types_dict" speedup = avg_langflow / avg_all_types print("\nSTEADY-STATE PERFORMANCE CONCLUSION:") print(f"Faster method: {faster_method}") print(f"Speedup factor: {speedup:.2f}x") print(f"Timing results: {avg_langflow:.4f}s (langflow), ", f"{avg_all_types:.4f}s (all_types)") print("\nNOTE: These results exclude warm-up runs and represent steady-state performance") print("that users will experience after the first component load.") print("=" * 80) # Log component counts (informational, non-failing) print("\nComponent count consistency:") if langflow_component_counts: min_count = min(langflow_component_counts) max_count = max(langflow_component_counts) if min_count != max_count: print(f"Note: Component counts vary ({min_count}-{max_count}) - may be due to OS file limits") else: print(f"Component counts consistent: {min_count}") assert all(isinstance(result, dict) for _, result in langflow_results), "All langflow results should be dicts" assert all(isinstance(result, dict) for _, result in all_types_results), "All all_types results should be dicts" # Log steady-state performance instead of asserting print(f"Steady-state performance: avg_langflow={avg_langflow:.4f}s, speedup={speedup:.2f}x") @pytest.mark.no_blockbuster @pytest.mark.asyncio async def test_component_differences_analysis(self, base_components_path): """Analyze and report the exact differences between components loaded by both methods.""" print("\n" + "=" * 80) print("COMPONENT DIFFERENCES ANALYSIS") print("=" * 80) # Load components from both methods langflow_result = await import_langflow_components() all_types_result = await aget_all_types_dict(base_components_path) # Extract component data from both results # import_langflow_components returns {"components": {category: {comp_name: comp_data}}} # aget_all_types_dict returns {category: {comp_name: comp_data}} langflow_components = langflow_result.get("components", {}) all_types_components = all_types_result # Build flat dictionaries of all components: {comp_name: category} langflow_flat = {} for category, components in langflow_components.items(): for comp_name in components: langflow_flat[comp_name] = category all_types_flat = {} for category, components in all_types_components.items(): for comp_name in components: all_types_flat[comp_name] = category # Calculate counts langflow_count = len(langflow_flat) all_types_count = len(all_types_flat) print("\nCOMPONENT COUNTS:") print(f"import_langflow_components: {langflow_count} components") print(f"aget_all_types_dict: {all_types_count} components") print(f"Difference: {abs(langflow_count - all_types_count)} components") # Find components that are in one but not the other langflow_only = set(langflow_flat.keys()) - set(all_types_flat.keys()) all_types_only = set(all_types_flat.keys()) - set(langflow_flat.keys()) common_components = set(langflow_flat.keys()) & set(all_types_flat.keys()) print("\nCOMPONENT OVERLAP:") print(f"Common components: {len(common_components)}") print(f"Only in import_langflow_components: {len(langflow_only)}") print(f"Only in aget_all_types_dict: {len(all_types_only)}") # Print detailed differences if langflow_only: print(f"\nCOMPONENTS ONLY IN import_langflow_components ({len(langflow_only)}):") for comp_name in sorted(langflow_only): category = langflow_flat[comp_name] print(f" - {comp_name} (category: {category})") if all_types_only: print(f"\nCOMPONENTS ONLY IN aget_all_types_dict ({len(all_types_only)}):") for comp_name in sorted(all_types_only): category = all_types_flat[comp_name] print(f" - {comp_name} (category: {category})") # Check for category differences for common components category_differences = [] for comp_name in common_components: langflow_cat = langflow_flat[comp_name] all_types_cat = all_types_flat[comp_name] if langflow_cat != all_types_cat: category_differences.append((comp_name, langflow_cat, all_types_cat)) if category_differences: print(f"\nCOMPONENTS WITH DIFFERENT CATEGORIES ({len(category_differences)}):") for comp_name, langflow_cat, all_types_cat in sorted(category_differences): print(f" - {comp_name}: import_langflow='{langflow_cat}' vs aget_all_types='{all_types_cat}'") # Print category summary print("\nCATEGORY SUMMARY:") langflow_categories = set(langflow_components.keys()) all_types_categories = set(all_types_components.keys()) print(f"Categories in import_langflow_components: {sorted(langflow_categories)}") print(f"Categories in aget_all_types_dict: {sorted(all_types_categories)}") categories_only_langflow = langflow_categories - all_types_categories categories_only_all_types = all_types_categories - langflow_categories if categories_only_langflow: print(f"Categories only in import_langflow_components: {sorted(categories_only_langflow)}") if categories_only_all_types: print(f"Categories only in aget_all_types_dict: {sorted(categories_only_all_types)}") print("=" * 80) # Log component counts and differences (informational, non-failing) print("Component loading analysis completed successfully") if langflow_count == 0 and all_types_count == 0: print("Note: Both methods returned 0 components - this may be due to OS file limits") elif len(common_components) == 0 and (langflow_count > 0 or all_types_count > 0): print("Note: No common components found - this may indicate different loading behaviors due to OS limits") @pytest.mark.benchmark async def test_component_loading_performance(self): """Test the performance of component loading.""" await import_langflow_components() @pytest.mark.no_blockbuster @pytest.mark.asyncio async def test_process_single_module_exception_handling(self): """Test that _process_single_module catches all exceptions during module import and component building. This ensures that if a component fails to import or build (e.g., due to network errors, missing dependencies, or initialization failures), it doesn't crash Langflow startup. """ from unittest.mock import patch from lfx.interface.components import _process_single_module print("\n" + "=" * 80) print("TESTING EXCEPTION HANDLING IN _process_single_module") print("=" * 80) # Test 1: ImportError during module import print("\n1. Testing ImportError handling...") with patch("importlib.import_module", side_effect=ImportError("Missing dependency: some_package")): result = _process_single_module("lfx.components.test_module") assert result is None, "Should return None when ImportError occurs" print(" ✓ ImportError handled correctly") # Test 2: AttributeError during module import print("\n2. Testing AttributeError handling...") with patch("importlib.import_module", side_effect=AttributeError("Module has no attribute 'something'")): result = _process_single_module("lfx.components.test_module") assert result is None, "Should return None when AttributeError occurs" print(" ✓ AttributeError handled correctly") # Test 3: ConnectionError (e.g., HTTP 503 from external API) print("\n3. Testing ConnectionError handling (simulating HTTP 503)...") with patch("importlib.import_module", side_effect=ConnectionError("503 Service Unavailable")): result = _process_single_module("lfx.components.nvidia.nvidia") assert result is None, "Should return None when ConnectionError occurs" print(" ✓ ConnectionError handled correctly") # Test 4: Generic HTTPError print("\n4. Testing HTTPError handling...") from urllib3.exceptions import MaxRetryError with patch("importlib.import_module", side_effect=MaxRetryError(None, "", reason="Connection timeout")): result = _process_single_module("lfx.components.test_module") assert result is None, "Should return None when HTTPError occurs" print(" ✓ HTTPError handled correctly") # Test 5: TimeoutError print("\n5. Testing TimeoutError handling...") with patch("importlib.import_module", side_effect=TimeoutError("Request timed out")): result = _process_single_module("lfx.components.test_module") assert result is None, "Should return None when TimeoutError occurs" print(" ✓ TimeoutError handled correctly") # Test 6: Generic Exception print("\n6. Testing generic Exception handling...") with patch("importlib.import_module", side_effect=Exception("Unexpected error during import")): result = _process_single_module("lfx.components.test_module") assert result is None, "Should return None when generic Exception occurs" print(" ✓ Generic Exception handled correctly") # Test 7: RuntimeError (e.g., from component initialization) print("\n7. Testing RuntimeError handling...") with patch("importlib.import_module", side_effect=RuntimeError("Component initialization failed")): result = _process_single_module("lfx.components.test_module") assert result is None, "Should return None when RuntimeError occurs" print(" ✓ RuntimeError handled correctly") # Test 8: ValueError (e.g., from invalid configuration) print("\n8. Testing ValueError handling...") with patch("importlib.import_module", side_effect=ValueError("Invalid configuration")): result = _process_single_module("lfx.components.test_module") assert result is None, "Should return None when ValueError occurs" print(" ✓ ValueError handled correctly") print("\n" + "=" * 80) print("ALL EXCEPTION HANDLING TESTS PASSED") print("Component failures will not crash Langflow startup") print("=" * 80)
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/test_load_components.py", "license": "MIT License", "lines": 528, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/base/langflow/api/v2/mcp.py
import asyncio import json from collections import defaultdict from io import BytesIO from typing import Annotated from fastapi import APIRouter, Body, Depends, HTTPException, UploadFile from lfx.base.agents.utils import safe_cache_get, safe_cache_set from lfx.base.mcp.util import update_tools from langflow.api.utils import CurrentActiveUser, DbSession from langflow.api.v2.files import ( MCP_SERVERS_FILE, download_file, edit_file_name, get_file_by_name, get_mcp_file, upload_user_file, ) from langflow.api.v2.schemas import MCPServerConfig from langflow.logging import logger from langflow.services.deps import get_settings_service, get_shared_component_cache_service, get_storage_service from langflow.services.settings.service import SettingsService from langflow.services.storage.service import StorageService router = APIRouter(tags=["MCP"], prefix="/mcp") # Per-user locks to serialize update_server() calls and prevent lost updates # from the non-atomic read-modify-write cycle on the MCP config file. _update_server_locks: dict[str, asyncio.Lock] = defaultdict(asyncio.Lock) async def upload_server_config( server_config: dict, current_user: CurrentActiveUser, session: DbSession, storage_service: Annotated[StorageService, Depends(get_storage_service)], settings_service: Annotated[SettingsService, Depends(get_settings_service)], ): content_str = json.dumps(server_config) content_bytes = content_str.encode("utf-8") # Convert to bytes file_obj = BytesIO(content_bytes) # Use BytesIO for binary data mcp_file = await get_mcp_file(current_user, extension=True) upload_file = UploadFile(file=file_obj, filename=mcp_file, size=len(content_str)) return await upload_user_file( file=upload_file, session=session, current_user=current_user, storage_service=storage_service, settings_service=settings_service, ) async def get_server_list( current_user: CurrentActiveUser, session: DbSession, storage_service: Annotated[StorageService, Depends(get_storage_service)], settings_service: Annotated[SettingsService, Depends(get_settings_service)], ): # Backwards compatibilty with old format file name mcp_file = await get_mcp_file(current_user) old_format_config_file = await get_file_by_name(MCP_SERVERS_FILE, current_user, session) if old_format_config_file: await edit_file_name(old_format_config_file.id, mcp_file, current_user, session) # Read the server configuration from a file using the files api server_config_file = await get_file_by_name(mcp_file, current_user, session) # Attempt to download the configuration file content try: server_config_bytes = await download_file( server_config_file.id if server_config_file else None, current_user, session, storage_service=storage_service, return_content=True, ) except (FileNotFoundError, HTTPException): if server_config_file: # DB record exists but storage file is missing — likely a transient state # during a concurrent update_server() write cycle. Return empty config # WITHOUT persisting to avoid permanently wiping existing servers. logger.warning( "MCP config file missing from storage for user %s (transient). " "Returning empty config without persisting.", current_user.id, ) return {"mcpServers": {}} # No DB record and no storage file — genuinely first-time use. Create empty config. await upload_server_config( {"mcpServers": {}}, current_user, session, storage_service=storage_service, settings_service=settings_service, ) # Fetch and download again mcp_file = await get_mcp_file(current_user) server_config_file = await get_file_by_name(mcp_file, current_user, session) if not server_config_file: raise HTTPException(status_code=500, detail="Failed to create MCP Servers configuration file") from None server_config_bytes = await download_file( server_config_file.id, current_user, session, storage_service=storage_service, return_content=True, ) # Parse JSON content try: servers = json.loads(server_config_bytes) except json.JSONDecodeError: raise HTTPException(status_code=500, detail="Invalid server configuration file format.") from None return servers async def get_server( server_name: str, current_user: CurrentActiveUser, session: DbSession, storage_service: Annotated[StorageService, Depends(get_storage_service)], settings_service: Annotated[SettingsService, Depends(get_settings_service)], server_list: dict | None = None, ): """Get a specific server configuration.""" if server_list is None: server_list = await get_server_list(current_user, session, storage_service, settings_service) if server_name not in server_list["mcpServers"]: return None return server_list["mcpServers"][server_name] # Define a Get servers endpoint @router.get("/servers") async def get_servers( current_user: CurrentActiveUser, session: DbSession, storage_service: Annotated[StorageService, Depends(get_storage_service)], settings_service: Annotated[SettingsService, Depends(get_settings_service)], *, action_count: bool | None = None, ): """Get the list of available servers.""" import asyncio from lfx.base.mcp.util import MCPStdioClient, MCPStreamableHttpClient server_list = await get_server_list(current_user, session, storage_service, settings_service) if not action_count: # Return only the server names, with mode and toolsCount as None return [{"name": server_name, "mode": None, "toolsCount": None} for server_name in server_list["mcpServers"]] # Check all of the tool counts for each server concurrently async def check_server(server_name: str) -> dict: server_info: dict[str, str | int | None] = {"name": server_name, "mode": None, "toolsCount": None} # Create clients that we control so we can clean them up after mcp_stdio_client = MCPStdioClient() mcp_streamable_http_client = MCPStreamableHttpClient() try: # Get global variables from database for header resolution request_variables = {} try: from sqlmodel import select from langflow.services.auth import utils as auth_utils from langflow.services.database.models.variable.model import Variable # Load variables directly from database and decrypt ALL types (including CREDENTIAL) stmt = select(Variable).where(Variable.user_id == current_user.id) variables = list((await session.exec(stmt)).all()) # Decrypt variables based on type (following the pattern from get_all_decrypted_variables) for variable in variables: if variable.name and variable.value: # Prior to v1.8, both Generic and Credential variables were encrypted. # As such, must attempt to decrypt both types to ensure backwards-compatibility. try: decrypted_value = auth_utils.decrypt_api_key(variable.value) request_variables[variable.name] = decrypted_value except Exception as e: # noqa: BLE001 await logger.aerror( f"Failed to decrypt credential variable '{variable.name}': {e}. " "This credential will not be available for MCP server." ) except Exception as e: # noqa: BLE001 await logger.awarning(f"Failed to load global variables for MCP server test: {e}") mode, tool_list, _ = await update_tools( server_name=server_name, server_config=server_list["mcpServers"][server_name], mcp_stdio_client=mcp_stdio_client, mcp_streamable_http_client=mcp_streamable_http_client, request_variables=request_variables, ) server_info["mode"] = mode.lower() server_info["toolsCount"] = len(tool_list) if len(tool_list) == 0: server_info["error"] = "No tools found" except ValueError as e: # Configuration validation errors, invalid URLs, etc. await logger.aerror(f"Configuration error for server {server_name}: {e}") server_info["error"] = f"Configuration error: {e}" except ConnectionError as e: # Network connection and timeout issues await logger.aerror(f"Connection error for server {server_name}: {e}") server_info["error"] = f"Connection failed: {e}" except (TimeoutError, asyncio.TimeoutError) as e: # Timeout errors await logger.aerror(f"Timeout error for server {server_name}: {e}") server_info["error"] = "Timeout when checking server tools" except OSError as e: # System-level errors (process execution, file access) await logger.aerror(f"System error for server {server_name}: {e}") server_info["error"] = f"System error: {e}" except (KeyError, TypeError) as e: # Data parsing and access errors await logger.aerror(f"Data error for server {server_name}: {e}") server_info["error"] = f"Configuration data error: {e}" except (RuntimeError, ProcessLookupError, PermissionError) as e: # Runtime and process-related errors await logger.aerror(f"Runtime error for server {server_name}: {e}") server_info["error"] = f"Runtime error: {e}" except Exception as e: # noqa: BLE001 # Generic catch-all for other exceptions (including ExceptionGroup) if hasattr(e, "exceptions") and e.exceptions: # Extract the first underlying exception for a more meaningful error message underlying_error = e.exceptions[0] if hasattr(underlying_error, "exceptions"): await logger.aerror( f"Error checking server {server_name}: {underlying_error}, {underlying_error.exceptions}" ) underlying_error = underlying_error.exceptions[0] else: await logger.aexception(f"Error checking server {server_name}: {underlying_error}") server_info["error"] = f"Error loading server: {underlying_error}" else: await logger.aexception(f"Error checking server {server_name}: {e}") server_info["error"] = f"Error loading server: {e}" finally: # Always disconnect clients to prevent mcp-proxy process leaks # These clients spawn subprocesses that need to be explicitly terminated await mcp_stdio_client.disconnect() await mcp_streamable_http_client.disconnect() return server_info # Run all server checks concurrently tasks = [check_server(server) for server in server_list["mcpServers"]] return await asyncio.gather(*tasks, return_exceptions=True) @router.get("/servers/{server_name}") async def get_server_endpoint( server_name: str, current_user: CurrentActiveUser, session: DbSession, storage_service: Annotated[StorageService, Depends(get_storage_service)], settings_service: Annotated[SettingsService, Depends(get_settings_service)], ): """Get a specific server.""" return await get_server(server_name, current_user, session, storage_service, settings_service) async def update_server( server_name: str, server_config: dict, current_user: CurrentActiveUser, session: DbSession, storage_service: Annotated[StorageService, Depends(get_storage_service)], settings_service: Annotated[SettingsService, Depends(get_settings_service)], *, check_existing: bool = False, delete: bool = False, ): async with _update_server_locks[str(current_user.id)]: server_list = await get_server_list(current_user, session, storage_service, settings_service) # Validate server name if check_existing and server_name in server_list["mcpServers"]: raise HTTPException(status_code=500, detail="Server already exists.") # Handle the delete case if delete: if server_name in server_list["mcpServers"]: del server_list["mcpServers"][server_name] else: raise HTTPException(status_code=500, detail="Server not found.") else: server_list["mcpServers"][server_name] = server_config # Upload the updated server configuration # (upload_user_file handles replacing the existing MCP file atomically) await upload_server_config( server_list, current_user, session, storage_service=storage_service, settings_service=settings_service ) shared_component_cache_service = get_shared_component_cache_service() # Clear the servers cache servers = safe_cache_get(shared_component_cache_service, "servers", {}) if isinstance(servers, dict): if server_name in servers: del servers[server_name] safe_cache_set(shared_component_cache_service, "servers", servers) return await get_server( server_name, current_user, session, storage_service, settings_service, server_list=server_list, ) @router.post("/servers/{server_name}") async def add_server( server_name: str, *, server_config: Annotated[MCPServerConfig, Body()], current_user: CurrentActiveUser, session: DbSession, storage_service: Annotated[StorageService, Depends(get_storage_service)], settings_service: Annotated[SettingsService, Depends(get_settings_service)], ): return await update_server( server_name, server_config.model_dump(exclude_unset=True), current_user, session, storage_service, settings_service, check_existing=True, ) @router.patch("/servers/{server_name}") async def update_server_endpoint( server_name: str, *, server_config: Annotated[MCPServerConfig, Body()], current_user: CurrentActiveUser, session: DbSession, storage_service: Annotated[StorageService, Depends(get_storage_service)], settings_service: Annotated[SettingsService, Depends(get_settings_service)], ): return await update_server( server_name, server_config.model_dump(exclude_unset=True), current_user, session, storage_service, settings_service, ) @router.delete("/servers/{server_name}") async def delete_server( server_name: str, current_user: CurrentActiveUser, session: DbSession, storage_service: Annotated[StorageService, Depends(get_storage_service)], settings_service: Annotated[SettingsService, Depends(get_settings_service)], ): return await update_server( server_name, {}, current_user, session, storage_service, settings_service, delete=True, )
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/base/langflow/api/v2/mcp.py", "license": "MIT License", "lines": 334, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
langflow-ai/langflow:src/backend/base/langflow/components/processing/converter.py
# Forward import for converter utilities # We intentionally keep this file, as the redirect to lfx in components/__init__.py # only supports direct imports from lfx.components, not sub-modules. # # This allows imports from langflow.components.processing.converter. to still function. from lfx.components.processing.converter import convert_to_dataframe __all__ = ["convert_to_dataframe"]
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/base/langflow/components/processing/converter.py", "license": "MIT License", "lines": 7, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
langflow-ai/langflow:src/backend/tests/unit/components/processing/test_type_converter_component.py
import json from io import StringIO import pandas as pd import pytest from lfx.components.processing.converter import TypeConverterComponent from lfx.schema.data import Data from lfx.schema.dataframe import DataFrame from lfx.schema.message import Message from tests.base import ComponentTestBaseWithoutClient class TestTypeConverterComponent(ComponentTestBaseWithoutClient): @pytest.fixture def component_class(self): """Return the component class to test.""" return TypeConverterComponent @pytest.fixture def file_names_mapping(self): """Return an empty list since this component doesn't have version-specific files.""" return [] # Message to other types def test_message_to_message(self, component_class): """Test converting Message to Message.""" component = component_class(input_data=Message(text="Hello World"), output_type="Message") result = component.convert_to_message() assert isinstance(result, Message) assert result.text == "Hello World" def test_message_to_data(self, component_class): """Test converting Message to Data.""" component = component_class(input_data=Message(text="Hello"), output_type="Data") result = component.convert_to_data() assert isinstance(result, Data) assert result.data == {"text": "Hello"} def test_message_to_dataframe(self, component_class): """Test converting Message to DataFrame.""" component = component_class(input_data=Message(text="Hello"), output_type="DataFrame") result = component.convert_to_dataframe() assert isinstance(result, DataFrame) assert list(result.columns) == ["text"] assert result.iloc[0]["text"] == "Hello" # Data to other types def test_data_to_message(self, component_class): """Test converting Data to Message.""" component = component_class(input_data=Data(data={"text": "Hello World"}), output_type="Message") result = component.convert_to_message() assert isinstance(result, Message) assert result.text == "Hello World" def test_data_to_data(self, component_class): """Test converting Data to Data.""" component = component_class(input_data=Data(data={"key": "value"}), output_type="Data") result = component.convert_to_data() assert isinstance(result, Data) assert result.data == {"key": "value"} def test_data_to_dataframe(self, component_class): """Test converting Data to DataFrame.""" component = component_class(input_data=Data(data={"text": "Hello World"}), output_type="DataFrame") result = component.convert_to_dataframe() assert isinstance(result, DataFrame) assert "text" in result.columns assert result.iloc[0]["text"] == "Hello World" # DataFrame to other types def test_dataframe_to_message(self, component_class): """Test converting DataFrame to Message.""" df_data = pd.DataFrame({"col1": ["Hello"], "col2": ["World"]}) component = component_class(input_data=DataFrame(data=df_data), output_type="Message") result = component.convert_to_message() assert isinstance(result, Message) assert result.text == "| col1 | col2 |\n|:-------|:-------|\n| Hello | World |" def test_dataframe_to_data(self, component_class): """Test converting DataFrame to Data.""" df_data = pd.DataFrame({"col1": ["Hello"]}) component = component_class(input_data=DataFrame(data=df_data), output_type="Data") result = component.convert_to_data() assert isinstance(result, Data) assert isinstance(result.data, dict) def test_dataframe_to_dataframe(self, component_class): """Test converting DataFrame to DataFrame.""" df_data = pd.DataFrame({"col1": ["Hello"], "col2": ["World"]}) component = component_class(input_data=DataFrame(data=df_data), output_type="DataFrame") result = component.convert_to_dataframe() assert isinstance(result, DataFrame) assert "col1" in result.columns assert "col2" in result.columns assert result.iloc[0]["col1"] == "Hello" assert result.iloc[0]["col2"] == "World" def test_update_outputs(self, component_class): """Test the update_outputs method.""" component = component_class(input_data=Message(text="Hello"), output_type="Message") frontend_node = {"outputs": []} # Test with Message output updated = component.update_outputs(frontend_node, "output_type", "Message") assert len(updated["outputs"]) == 1 assert updated["outputs"][0]["name"] == "message_output" # Test with Data output updated = component.update_outputs(frontend_node, "output_type", "Data") assert len(updated["outputs"]) == 1 assert updated["outputs"][0]["name"] == "data_output" # Test with DataFrame output updated = component.update_outputs(frontend_node, "output_type", "DataFrame") assert len(updated["outputs"]) == 1 assert updated["outputs"][0]["name"] == "dataframe_output" def test_message_with_valid_json_text_to_data(self, component_class): """Test converting Message to Data.""" valid_json_text = '{"foo": "bar"}' component = component_class(input_data=Message(text=valid_json_text), output_type="Data", auto_parse=True) result = component.convert_to_data() assert isinstance(result, Data) assert result.data == json.loads(valid_json_text) def test_message_with_invalid_json_text_to_data(self, component_class): """Test converting Message to Data.""" invalid_json_text = '{"foo", "bar"}' component = component_class(input_data=Message(text=invalid_json_text), output_type="Data", auto_parse=True) result = component.convert_to_data() assert isinstance(result, Data) assert isinstance(result.data["text"], str) assert result.data == {"text": invalid_json_text} def test_message_with_valid_json_array_to_data(self, component_class): """Test converting Message with JSON array to Data.""" valid_json_text = '[{"name": "Ana", "age": 28}, {"name": "Bruno", "age": 34}]' component = component_class(input_data=Message(text=valid_json_text), output_type="Data", auto_parse=True) result = component.convert_to_data() expected_data = {"records": json.loads(valid_json_text)} assert isinstance(result, Data) assert result.data == expected_data def test_message_with_valid_csv_to_data(self, component_class): """Test converting Message with CSV to Data.""" valid_csv_text = "name,age,email\nAna,28,ana@email.com\nBruno,34,bruno@email.com\nCarla,22,carla@email.com\n" component = component_class(input_data=Message(text=valid_csv_text), output_type="Data", auto_parse=True) result = component.convert_to_data() expected_data = { "records": [ {"name": "Ana", "age": 28, "email": "ana@email.com"}, {"name": "Bruno", "age": 34, "email": "bruno@email.com"}, {"name": "Carla", "age": 22, "email": "carla@email.com"}, ] } assert isinstance(result, Data) assert result.data == expected_data def test_message_with_valid_csv_to_dataframe(self, component_class): """Test converting Message to DataFrame.""" valid_csv_text = ( "name,age,email,city\n" "Ana,28,ana@email.com,São Paulo\n" "Bruno,34,bruno@email.com,Rio de Janeiro\n" "Carla,22,carla@email.com,Belo Horizonte\n" "Diego,40,diego@email.com,Curitiba\n" "Elisa,31,elisa@email.com,Porto Alegre\n" ) component = component_class(input_data=Message(text=valid_csv_text), output_type="DataFrame", auto_parse=True) result = component.convert_to_dataframe() expected = pd.read_csv(StringIO(valid_csv_text)) assert isinstance(result, DataFrame) assert list(result.columns) == ["name", "age", "email", "city"] pd.testing.assert_frame_equal(result, expected) def test_message_with_valid_json_object_to_dataframe(self, component_class): """Test converting Message with JSON object to DataFrame.""" valid_json_text = '{"name": "Ana", "age": 28, "email": "ana@email.com", "city": "São Paulo"}' component = component_class(input_data=Message(text=valid_json_text), output_type="DataFrame", auto_parse=True) result = component.convert_to_dataframe() expected_data = [json.loads(valid_json_text)] expected = pd.DataFrame(expected_data) assert isinstance(result, DataFrame) assert list(result.columns) == ["name", "age", "email", "city"] pd.testing.assert_frame_equal(result, expected) def test_message_with_valid_json_array_to_dataframe(self, component_class): """Test converting Message with JSON array to DataFrame.""" valid_json_text = """[ {"name": "Ana", "age": 28, "email": "ana@email.com", "city": "São Paulo"}, {"name": "Bruno", "age": 34, "email": "bruno@email.com", "city": "Rio de Janeiro"}, {"name": "Carla", "age": 22, "email": "carla@email.com", "city": "Belo Horizonte"} ]""" component = component_class(input_data=Message(text=valid_json_text), output_type="DataFrame", auto_parse=True) result = component.convert_to_dataframe() expected_data = json.loads(valid_json_text) expected = pd.DataFrame(expected_data) assert isinstance(result, DataFrame) assert list(result.columns) == ["name", "age", "email", "city"] assert len(result) == 3 pd.testing.assert_frame_equal(result, expected) def test_message_with_compact_json_array_to_dataframe(self, component_class): """Test converting Message with compact JSON array to DataFrame.""" valid_json_text = '[{"name":"Ana","age":28},{"name":"Bruno","age":34},{"name":"Carla","age":22}]' component = component_class(input_data=Message(text=valid_json_text), output_type="DataFrame", auto_parse=True) result = component.convert_to_dataframe() expected_data = json.loads(valid_json_text) expected = pd.DataFrame(expected_data) assert isinstance(result, DataFrame) assert list(result.columns) == ["name", "age"] assert len(result) == 3 pd.testing.assert_frame_equal(result, expected)
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/components/processing/test_type_converter_component.py", "license": "MIT License", "lines": 188, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/tests/unit/components/processing/test_data_operations_component.py
import pytest from lfx.components.processing.data_operations import DataOperationsComponent from lfx.schema import Data from tests.base import ComponentTestBaseWithoutClient class TestDataOperationsComponent(ComponentTestBaseWithoutClient): @pytest.fixture def component_class(self): """Return the component class to test.""" return DataOperationsComponent @pytest.fixture def default_kwargs(self): """Return the default kwargs for the component.""" return { "data": Data(data={"key1": "value1", "key2": "value2", "key3": "value3"}), "actions": [{"name": "Select Keys"}], "select_keys_input": ["key1", "key2"], } @pytest.fixture def file_names_mapping(self): """Return an empty list since this component doesn't have version-specific files.""" return [] def test_select_keys(self): """Test the Select Keys operation.""" component = DataOperationsComponent( data=Data(data={"key1": "value1", "key2": "value2", "key3": "value3"}), operations=[{"name": "Select Keys"}], select_keys_input=["key1", "key2"], ) result = component.as_data() assert isinstance(result, Data) assert "key1" in result.data assert "key2" in result.data assert "key3" not in result.data assert result.data["key1"] == "value1" assert result.data["key2"] == "value2" def test_remove_keys(self): """Test the Remove Keys operation.""" component = DataOperationsComponent( data=Data(data={"key1": "value1", "key2": "value2", "key3": "value3"}), operations=[{"name": "Remove Keys"}], remove_keys_input=["key3"], ) result = component.as_data() assert isinstance(result, Data) assert "key1" in result.data assert "key2" in result.data assert "key3" not in result.data def test_rename_keys(self): """Test the Rename Keys operation.""" component = DataOperationsComponent( data=Data(data={"key1": "value1", "key2": "value2"}), operations=[{"name": "Rename Keys"}], rename_keys_input={"key1": "new_key1"}, ) result = component.as_data() assert isinstance(result, Data) assert "new_key1" in result.data assert "key1" not in result.data assert result.data["new_key1"] == "value1" def test_literal_eval(self): """Test the Literal Eval operation.""" component = DataOperationsComponent( data=Data(data={"list_as_string": "[1, 2, 3]", "dict_as_string": "{'a': 1, 'b': 2}"}), operations=[{"name": "Literal Eval"}], ) result = component.as_data() assert isinstance(result, Data) assert isinstance(result.data["list_as_string"], list) assert result.data["list_as_string"] == [1, 2, 3] assert isinstance(result.data["dict_as_string"], dict) assert result.data["dict_as_string"] == {"a": 1, "b": 2} def test_combine(self): """Test the Combine operation.""" data1 = Data(data={"key1": "value1"}) data2 = Data(data={"key2": "value2"}) component = DataOperationsComponent( data=[data1, data2], operations=[{"name": "Combine"}], ) result = component.as_data() assert isinstance(result, Data) assert "key1" in result.data assert "key2" in result.data assert result.data["key1"] == "value1" assert result.data["key2"] == "value2" def test_combine_with_overlapping_keys(self): """Test the Combine operation with overlapping keys.""" data1 = Data(data={"common_key": "value1", "key1": "value1"}) data2 = Data(data={"common_key": "value2", "key2": "value2"}) component = DataOperationsComponent( data=[data1, data2], operations=[{"name": "Combine"}], ) result = component.as_data() assert isinstance(result, Data) assert result.data["common_key"] == ["value1", "value2"] # Combined string values assert result.data["key1"] == "value1" assert result.data["key2"] == "value2" def test_append_update(self): """Test the Append or Update Data operation.""" component = DataOperationsComponent( data=Data(data={"existing_key": "existing_value"}), operations=[{"name": "Append or Update"}], append_update_data={"new_key": "new_value", "existing_key": "updated_value"}, ) result = component.as_data() assert isinstance(result, Data) assert result.data["existing_key"] == "updated_value" assert result.data["new_key"] == "new_value" def test_filter_values(self): """Test the Filter Values operation.""" nested_data = { "items": [ {"id": 1, "name": "Item 1"}, {"id": 2, "name": "Item 2"}, {"id": 3, "name": "Different Item"}, ] } component = DataOperationsComponent( data=Data(data=nested_data), operations=[{"name": "Filter Values"}], filter_key=["items"], filter_values={"name": "Item"}, operator="contains", ) result = component.as_data() assert isinstance(result, Data) assert len(result.data["items"]) == 3 assert result.data["items"][0]["id"] == 1 assert result.data["items"][1]["id"] == 2 def test_no_actions(self): """Test behavior when no actions are specified.""" component = DataOperationsComponent( data=Data(data={"key1": "value1"}), operations=[], ) result = component.as_data() assert isinstance(result, Data) assert result.data == {} def test_get_normalized_data(self): """Test the get_normalized_data helper method.""" component = DataOperationsComponent( data=Data(data={"key1": "value1"}), operations=[], ) # Add data under the "data" key component.data = Data(data={"test": {"key2": "value2"}}) normalized = component.get_normalized_data() assert normalized == {"test": {"key2": "value2"}} # Test without the "data" key component.data = Data(data={"key3": "value3"}) normalized = component.get_normalized_data() assert normalized == {"key3": "value3"} def test_validate_single_data_with_multiple_data(self): """Test that operations that don't support multiple data objects raise an error.""" component = DataOperationsComponent( data=[Data(data={"key1": "value1"}), Data(data={"key2": "value2"})], operations=[{"name": "Select Keys"}], select_keys_input=["key1"], ) with pytest.raises(ValueError, match="Select Keys operation is not supported for multiple data objects"): component.as_data() def test_update_build_config_clears_input_fields_when_operation_removed(self): """Test that removing the selected operation hides all operation-specific input fields.""" from lfx.schema.dotdict import dotdict component = DataOperationsComponent( data=Data(data={"key1": "value1"}), operations=[], ) # Simulate build_config after "Filter Values" was selected (operation-specific fields visible) build_config = dotdict( { "operations": {"value": [], "show": True}, "data": {"value": None, "show": True}, "filter_key": {"value": [], "show": True}, "operator": {"value": "equals", "show": True}, "filter_values": {"value": {}, "show": True}, "select_keys_input": {"value": [], "show": False}, } ) result = component.update_build_config(build_config, [], "operations") # All operation-specific fields should be hidden when no operation is selected assert result["filter_key"]["show"] is False assert result["operator"]["show"] is False assert result["filter_values"]["show"] is False assert result["select_keys_input"]["show"] is False # Default fields (operations, data) should remain visible assert result["operations"]["show"] is True assert result["data"]["show"] is True
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/components/processing/test_data_operations_component.py", "license": "MIT License", "lines": 189, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/tests/unit/components/bundles/google/test_google_bq_sql_executor_component.py
"""Tests for BigQueryExecutorComponent.""" from __future__ import annotations import json import re from unittest.mock import MagicMock, mock_open, patch import pytest from google.auth.exceptions import RefreshError from google.oauth2.service_account import Credentials from lfx.components.google.google_bq_sql_executor import BigQueryExecutorComponent from pandas import DataFrame from tests.base import ComponentTestBaseWithoutClient class TestBigQueryExecutorComponent(ComponentTestBaseWithoutClient): @pytest.fixture def component_class(self): """Return the component class to test.""" return BigQueryExecutorComponent @pytest.fixture def mock_credentials_json(self): """Return a valid service account JSON string.""" return json.dumps( { "type": "service_account", "project_id": "test-project", "private_key_id": "fake-key-id", "private_key": "-----BEGIN PRIVATE KEY-----\nfake-key\n-----END PRIVATE KEY-----\n", "client_email": "test@project.iam.gserviceaccount.com", "client_id": "123456789", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": ( "https://www.googleapis.com/robot/v1/metadata/x509/test@project.iam.gserviceaccount.com" ), } ) @pytest.fixture def service_account_file(self, tmp_path, mock_credentials_json): """Write service account JSON to a temp file and return its path.""" f = tmp_path / "sa.json" f.write_text(mock_credentials_json) return str(f) @pytest.fixture def default_kwargs(self, service_account_file): """Return default kwargs for component instantiation.""" return { "service_account_json_file": service_account_file, "query": "SELECT 1", } @pytest.fixture def file_names_mapping(self): """No version-specific files for this component.""" return [] @patch.object(Credentials, "from_service_account_file") @patch("lfx.components.google.google_bq_sql_executor.bigquery.Client") def test_execute_sql_success(self, mock_client_cls, mock_from_file, component_class, default_kwargs): """Test successful SQL execution and component side-effects.""" # Arrange mocks mock_creds = MagicMock(spec=Credentials) mock_from_file.return_value = mock_creds # Create a mock row that can be converted to a dict mock_row = MagicMock() mock_row.items.return_value = [("column1", "value1")] mock_row.__iter__.return_value = iter([("column1", "value1")]) mock_row.keys.return_value = ["column1"] mock_row.to_numpy.return_value = ["value1"] # Changed from values to to_numpy mock_row.__getitem__.return_value = "value1" # Create mock result with the mock row mock_result = MagicMock() mock_result.__iter__.return_value = iter([mock_row]) # Create mock job with the mock result mock_job = MagicMock() mock_job.result.return_value = mock_result # Create mock client with the mock job mock_client = MagicMock() mock_client.query.return_value = mock_job mock_client_cls.return_value = mock_client # Instantiate component with defaults component = component_class(**default_kwargs) # Execute result = component.execute_sql() # Verify the result assert isinstance(result, DataFrame) assert len(result) == 1 # Check number of rows assert "column1" in result.columns # Check column exists assert result.iloc[0]["column1"] == "value1" # Check value # Verify the mocks were called correctly mock_from_file.assert_called_once_with(default_kwargs["service_account_json_file"]) mock_client_cls.assert_called_once_with(credentials=mock_creds, project="test-project") mock_client.query.assert_called_once_with(default_kwargs["query"]) @pytest.mark.parametrize("q", ["", " \n\t "]) @patch.object(Credentials, "from_service_account_file") @patch("lfx.components.google.google_bq_sql_executor.bigquery.Client") def test_empty_query_raises(self, mock_client_cls, mock_from_file, component_class, service_account_file, q): """Empty or whitespace-only queries should raise a ValueError.""" # Create a proper mock credentials object mock_creds = MagicMock(spec=Credentials) mock_from_file.return_value = mock_creds # Mock the BigQuery client mock_client = MagicMock() mock_client_cls.return_value = mock_client # Create component with empty/whitespace query component = component_class( service_account_json_file=service_account_file, query=q, ) # Verify that execute_sql raises ValueError for empty/whitespace queries expected_error = "No valid SQL query found in input text." with pytest.raises(ValueError, match=expected_error): component.execute_sql() # Verify that the BigQuery client was not called mock_client.query.assert_not_called() def test_missing_service_account_file(self, component_class): """Non-existent service account file should raise a ValueError.""" component = component_class( service_account_json_file="/no/such/file.json", query="SELECT 1", ) expected_error = "Service account file not found" with pytest.raises(ValueError, match=expected_error): component.execute_sql() def test_invalid_service_account_json(self, component_class): """Invalid JSON in service account file should raise a ValueError.""" with patch("pathlib.Path.open", mock_open(read_data="invalid json")): component = component_class( service_account_json_file="ignored.json", query="SELECT 1", ) expected_error = "Invalid JSON string for service account credentials" with pytest.raises(ValueError, match=expected_error): component.execute_sql() @patch.object(Credentials, "from_service_account_file") @patch("lfx.components.google.google_bq_sql_executor.bigquery.Client") def test_execute_sql_invalid_query(self, mock_client_cls, mock_from_file, component_class, default_kwargs): """SQL execution errors should be wrapped in ValueError.""" mock_from_file.return_value = MagicMock() fake_client = MagicMock() mock_client_cls.return_value = fake_client fake_client.query.side_effect = Exception("Invalid query syntax") component = component_class(**default_kwargs) with pytest.raises(ValueError, match="Error executing BigQuery SQL query: Invalid query syntax"): component.execute_sql() @patch.object(Credentials, "from_service_account_file") @patch("lfx.components.google.google_bq_sql_executor.bigquery.Client") def test_refresh_error_handling(self, mock_client_cls, mock_from_file, component_class, default_kwargs): """RefreshError should produce an authentication ValueError.""" mock_from_file.return_value = MagicMock() fake_client = MagicMock() mock_client_cls.return_value = fake_client fake_client.query.side_effect = RefreshError("Token expired") component = component_class(**default_kwargs) with pytest.raises( ValueError, match=re.escape("Authentication error: Unable to refresh authentication token.") ): component.execute_sql() @patch.object(Credentials, "from_service_account_file") @patch("lfx.components.google.google_bq_sql_executor.bigquery.Client") def test_complex_query_result(self, mock_client_cls, mock_from_file, component_class, default_kwargs): """Complex row structures should be correctly serialized to DataFrame.""" # Arrange mocks mock_creds = MagicMock(spec=Credentials) mock_from_file.return_value = mock_creds # Create mock rows with complex data mock_row1 = MagicMock() mock_row1.items.return_value = [("id", 1), ("name", "Test 1"), ("value", 10.5), ("active", True)] mock_row1.__iter__.return_value = iter([("id", 1), ("name", "Test 1"), ("value", 10.5), ("active", True)]) mock_row1.keys.return_value = ["id", "name", "value", "active"] mock_row1.to_numpy.return_value = [1, "Test 1", 10.5, True] # Changed from values to to_numpy mock_row1.__getitem__.side_effect = lambda key: {"id": 1, "name": "Test 1", "value": 10.5, "active": True}[key] mock_row2 = MagicMock() mock_row2.items.return_value = [("id", 2), ("name", "Test 2"), ("value", 20.75), ("active", False)] mock_row2.__iter__.return_value = iter([("id", 2), ("name", "Test 2"), ("value", 20.75), ("active", False)]) mock_row2.keys.return_value = ["id", "name", "value", "active"] mock_row2.to_numpy.return_value = [2, "Test 2", 20.75, False] # Changed from values to to_numpy mock_row2.__getitem__.side_effect = lambda key: {"id": 2, "name": "Test 2", "value": 20.75, "active": False}[ key ] # Create mock result with the mock rows mock_result = MagicMock() mock_result.__iter__.return_value = iter([mock_row1, mock_row2]) # Create mock job with the mock result mock_job = MagicMock() mock_job.result.return_value = mock_result # Create mock client with the mock job mock_client = MagicMock() mock_client.query.return_value = mock_job mock_client_cls.return_value = mock_client # Instantiate component with defaults component = component_class(**default_kwargs) # Execute result = component.execute_sql() # Verify the result assert isinstance(result, DataFrame) assert len(result) == 2 # Check number of rows assert list(result.columns) == ["id", "name", "value", "active"] # Check columns # Convert DataFrame to dictionary for easier comparison result_dict = result.to_dict(orient="records") # Verify first row assert result_dict[0]["id"] == 1 assert result_dict[0]["name"] == "Test 1" assert result_dict[0]["value"] == 10.5 assert result_dict[0]["active"] is True # Verify second row assert result_dict[1]["id"] == 2 assert result_dict[1]["name"] == "Test 2" assert result_dict[1]["value"] == 20.75 assert result_dict[1]["active"] is False # Verify the mocks were called correctly mock_from_file.assert_called_once_with(default_kwargs["service_account_json_file"]) mock_client_cls.assert_called_once_with(credentials=mock_creds, project="test-project") mock_client.query.assert_called_once_with(default_kwargs["query"]) @patch.object(Credentials, "from_service_account_file") @patch("lfx.components.google.google_bq_sql_executor.bigquery.Client") def test_query_with_sql_code_block(self, mock_client_cls, mock_from_file, component_class, default_kwargs): """Test that queries with SQL code blocks are properly handled.""" mock_from_file.return_value = MagicMock() fake_client = MagicMock() mock_client_cls.return_value = fake_client query_with_code_block = "```sql\nSELECT * FROM table\n```" component = component_class(**{**default_kwargs, "query": query_with_code_block, "clean_query": True}) result = component.execute_sql() # Verify the query was properly cleaned (code block markers removed) fake_client.query.assert_called_once_with("SELECT * FROM table") assert isinstance(result, DataFrame) @patch.object(Credentials, "from_service_account_file") @patch("lfx.components.google.google_bq_sql_executor.bigquery.Client") def test_query_with_whitespace(self, mock_client_cls, mock_from_file, component_class, default_kwargs): """Test that queries with extra whitespace are properly handled.""" # Arrange mocks mock_creds = MagicMock(spec=Credentials) mock_from_file.return_value = mock_creds # Create a mock row that can be converted to a dict mock_row = MagicMock() mock_row.items.return_value = [("column1", "value1")] mock_row.__iter__.return_value = iter([("column1", "value1")]) mock_row.keys.return_value = ["column1"] mock_row.to_numpy.return_value = ["value1"] # Changed from values to to_numpy mock_row.__getitem__.return_value = "value1" # Create mock result with the mock row mock_result = MagicMock() mock_result.__iter__.return_value = iter([mock_row]) # Create mock job with the mock result mock_job = MagicMock() mock_job.result.return_value = mock_result # Create mock client with the mock job mock_client = MagicMock() mock_client.query.return_value = mock_job mock_client_cls.return_value = mock_client query_with_whitespace = " SELECT * FROM table " component = component_class(**{**default_kwargs, "query": query_with_whitespace, "clean_query": True}) result = component.execute_sql() # Verify the query was properly stripped mock_client.query.assert_called_once_with("SELECT * FROM table") assert isinstance(result, DataFrame) assert len(result) == 1 # Check number of rows assert "column1" in result.columns # Check column exists assert result.iloc[0]["column1"] == "value1" # Check value @patch.object(Credentials, "from_service_account_file") @patch("lfx.components.google.google_bq_sql_executor.bigquery.Client") def test_query_with_special_characters(self, mock_client_cls, mock_from_file, component_class, default_kwargs): """Test that queries with special characters are properly handled.""" # Arrange mocks mock_creds = MagicMock(spec=Credentials) mock_from_file.return_value = mock_creds # Create a mock row that can be converted to a dict mock_row = MagicMock() mock_row.items.return_value = [("name", "test_value")] mock_row.__iter__.return_value = iter([("name", "test_value")]) mock_row.keys.return_value = ["name"] mock_row.to_numpy.return_value = ["test_value"] # Changed from values to to_numpy mock_row.__getitem__.return_value = "test_value" # Create mock result with the mock row mock_result = MagicMock() mock_result.__iter__.return_value = iter([mock_row]) # Create mock job with the mock result mock_job = MagicMock() mock_job.result.return_value = mock_result # Create mock client with the mock job mock_client = MagicMock() mock_client.query.return_value = mock_job mock_client_cls.return_value = mock_client query_with_special_chars = "SELECT * FROM project.dataset.table WHERE name LIKE '%test%'" component = component_class(**{**default_kwargs, "query": query_with_special_chars}) result = component.execute_sql() # Verify the query with special characters was passed correctly mock_client.query.assert_called_once_with(query_with_special_chars) assert isinstance(result, DataFrame) assert len(result) == 1 # Check number of rows assert "name" in result.columns # Check column exists assert result.iloc[0]["name"] == "test_value" # Check value @patch.object(Credentials, "from_service_account_file") @patch("lfx.components.google.google_bq_sql_executor.bigquery.Client") def test_query_with_multiple_statements(self, mock_client_cls, mock_from_file, component_class, default_kwargs): """Test that queries with multiple statements are properly handled.""" # Arrange mocks mock_creds = MagicMock(spec=Credentials) mock_from_file.return_value = mock_creds # Create a mock row that can be converted to a dict mock_row = MagicMock() mock_row.items.return_value = [("id", 1)] mock_row.__iter__.return_value = iter([("id", 1)]) mock_row.keys.return_value = ["id"] mock_row.to_numpy.return_value = [1] # Changed from values to to_numpy mock_row.__getitem__.return_value = 1 # Create mock result with the mock row mock_result = MagicMock() mock_result.__iter__.return_value = iter([mock_row]) # Create mock job with the mock result mock_job = MagicMock() mock_job.result.return_value = mock_result # Create mock client with the mock job mock_client = MagicMock() mock_client.query.return_value = mock_job mock_client_cls.return_value = mock_client multi_statement_query = ( "CREATE TABLE IF NOT EXISTS test_table (id INT64);\n" "INSERT INTO test_table VALUES (1);\n" "SELECT * FROM test_table;" ) component = component_class(**{**default_kwargs, "query": multi_statement_query}) result = component.execute_sql() # Verify the multi-statement query was passed correctly mock_client.query.assert_called_once_with(multi_statement_query) assert isinstance(result, DataFrame) assert len(result) == 1 # Check number of rows assert "id" in result.columns # Check column exists assert result.iloc[0]["id"] == 1 # Check value @patch.object(Credentials, "from_service_account_file") @patch("lfx.components.google.google_bq_sql_executor.bigquery.Client") def test_query_with_parameters(self, mock_client_cls, mock_from_file, component_class, default_kwargs): """Test that queries with parameters are properly handled.""" # Arrange mocks mock_creds = MagicMock(spec=Credentials) mock_from_file.return_value = mock_creds # Create a mock row that can be converted to a dict mock_row = MagicMock() mock_row.items.return_value = [("id", 1), ("name", "test_name")] mock_row.__iter__.return_value = iter([("id", 1), ("name", "test_name")]) mock_row.keys.return_value = ["id", "name"] mock_row.to_numpy.return_value = [1, "test_name"] # Changed from values to to_numpy mock_row.__getitem__.side_effect = lambda key: {"id": 1, "name": "test_name"}[key] # Create mock result with the mock row mock_result = MagicMock() mock_result.__iter__.return_value = iter([mock_row]) # Create mock job with the mock result mock_job = MagicMock() mock_job.result.return_value = mock_result # Create mock client with the mock job mock_client = MagicMock() mock_client.query.return_value = mock_job mock_client_cls.return_value = mock_client query_with_params = "SELECT * FROM table WHERE id = @id AND name = @name" component = component_class(**{**default_kwargs, "query": query_with_params}) result = component.execute_sql() # Verify the parameterized query was passed correctly mock_client.query.assert_called_once_with(query_with_params) assert isinstance(result, DataFrame) assert len(result) == 1 # Check number of rows assert list(result.columns) == ["id", "name"] # Check columns assert result.iloc[0]["id"] == 1 # Check id value assert result.iloc[0]["name"] == "test_name" # Check name value def test_missing_project_id_in_credentials(self, component_class, tmp_path): """Test that missing project_id in credentials raises an error.""" # Create a service account JSON without project_id invalid_credentials = { "type": "service_account", "private_key_id": "fake-key-id", "private_key": "-----BEGIN PRIVATE KEY-----\nfake-key\n-----END PRIVATE KEY-----\n", "client_email": "test@project.iam.gserviceaccount.com", "client_id": "123456789", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/test@project.iam.gserviceaccount.com", } # Write invalid credentials to a temp file f = tmp_path / "invalid_sa.json" f.write_text(json.dumps(invalid_credentials)) component = component_class( service_account_json_file=str(f), query="SELECT 1", ) with pytest.raises(ValueError, match="No project_id found in service account credentials file"): component.execute_sql() @patch.object(Credentials, "from_service_account_file") @patch("lfx.components.google.google_bq_sql_executor.bigquery.Client") def test_query_with_quotes(self, mock_client_cls, mock_from_file, component_class, default_kwargs): """Test that queries wrapped in quotes are properly handled.""" # Arrange mocks mock_creds = MagicMock(spec=Credentials) mock_from_file.return_value = mock_creds # Create a mock row that can be converted to a dict mock_row = MagicMock() mock_row.items.return_value = [("column1", "value1")] mock_row.__iter__.return_value = iter([("column1", "value1")]) mock_row.keys.return_value = ["column1"] mock_row.to_numpy.return_value = ["value1"] # Changed from values to to_numpy mock_row.__getitem__.return_value = "value1" # Create mock result with the mock row mock_result = MagicMock() mock_result.__iter__.return_value = iter([mock_row]) # Create mock job with the mock result mock_job = MagicMock() mock_job.result.return_value = mock_result # Create mock client with the mock job mock_client = MagicMock() mock_client.query.return_value = mock_job mock_client_cls.return_value = mock_client # Test with double quotes query_with_double_quotes = '"SELECT * FROM table"' component = component_class(**{**default_kwargs, "query": query_with_double_quotes, "clean_query": True}) result = component.execute_sql() mock_client.query.assert_called_once_with("SELECT * FROM table") assert isinstance(result, DataFrame) # Reset mocks for next test mock_client.reset_mock() # Test with single quotes query_with_single_quotes = "'SELECT * FROM table'" component = component_class(**{**default_kwargs, "query": query_with_single_quotes, "clean_query": True}) result = component.execute_sql() mock_client.query.assert_called_once_with("SELECT * FROM table") assert isinstance(result, DataFrame) # Reset mocks for next test mock_client.reset_mock() # Test with SQL code block query_with_code_block = "```sql\nSELECT * FROM table\n```" component = component_class(**{**default_kwargs, "query": query_with_code_block, "clean_query": True}) result = component.execute_sql() mock_client.query.assert_called_once_with("SELECT * FROM table") assert isinstance(result, DataFrame) # Reset mocks for next test mock_client.reset_mock() # Test with SQL code block and quotes query_with_code_block_and_quotes = '```sql\n"SELECT * FROM table"\n```' component = component_class( **{**default_kwargs, "query": query_with_code_block_and_quotes, "clean_query": True} ) result = component.execute_sql() mock_client.query.assert_called_once_with("SELECT * FROM table") assert isinstance(result, DataFrame) # Reset mocks for next test mock_client.reset_mock() # Test with just backticks query_with_backticks = "`SELECT * FROM table`" component = component_class(**{**default_kwargs, "query": query_with_backticks, "clean_query": True}) result = component.execute_sql() mock_client.query.assert_called_once_with("SELECT * FROM table") assert isinstance(result, DataFrame) # Reset mocks for next test mock_client.reset_mock() # Test with mixed markers query_with_mixed = '```sql\n`"SELECT * FROM table"`\n```' component = component_class(**{**default_kwargs, "query": query_with_mixed, "clean_query": True}) result = component.execute_sql() mock_client.query.assert_called_once_with("SELECT * FROM table") assert isinstance(result, DataFrame) # Reset mocks for next test mock_client.reset_mock() # Test with backticks in the middle of the query query_with_middle_backticks = "SELECT * FROM project.dataset.table" component = component_class(**{**default_kwargs, "query": query_with_middle_backticks, "clean_query": True}) result = component.execute_sql() mock_client.query.assert_called_once_with("SELECT * FROM project.dataset.table") assert isinstance(result, DataFrame) # Reset mocks for next test mock_client.reset_mock() # Test with multiple backticks in the query query_with_multiple_backticks = "SELECT * FROM project.dataset.table WHERE column = 'value'" component = component_class(**{**default_kwargs, "query": query_with_multiple_backticks, "clean_query": True}) result = component.execute_sql() mock_client.query.assert_called_once_with("SELECT * FROM project.dataset.table WHERE column = 'value'") assert isinstance(result, DataFrame)
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/components/bundles/google/test_google_bq_sql_executor_component.py", "license": "MIT License", "lines": 471, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/base/langflow/alembic/versions/66f72f04a1de_add_mcp_support_with_project_settings_.py
"""Add MCP support with project settings in flows Revision ID: 66f72f04a1de Revises: e56d87f8994a Create Date: 2025-04-24 18:42:15.828332 """ from collections.abc import Sequence import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision: str = "66f72f04a1de" down_revision: str | None = "e56d87f8994a" branch_labels: str | Sequence[str] | None = None depends_on: str | Sequence[str] | None = None def upgrade() -> None: conn = op.get_bind() inspector = sa.inspect(conn) # type: ignore column_names = [column["name"] for column in inspector.get_columns("flow")] # ### commands auto generated by Alembic - please adjust! ### with op.batch_alter_table("flow", schema=None) as batch_op: if "mcp_enabled" not in column_names: batch_op.add_column(sa.Column("mcp_enabled", sa.Boolean(), nullable=True)) if "action_name" not in column_names: batch_op.add_column(sa.Column("action_name", sqlmodel.sql.sqltypes.AutoString(), nullable=True)) if "action_description" not in column_names: batch_op.add_column(sa.Column("action_description", sa.Text(), nullable=True)) # ### end Alembic commands ### def downgrade() -> None: conn = op.get_bind() inspector = sa.inspect(conn) # type: ignore column_names = [column["name"] for column in inspector.get_columns("flow")] # ### commands auto generated by Alembic - please adjust! ### with op.batch_alter_table("flow", schema=None) as batch_op: if "action_description" in column_names: batch_op.drop_column("action_description") if "action_name" in column_names: batch_op.drop_column("action_name") if "mcp_enabled" in column_names: batch_op.drop_column("mcp_enabled") # ### end Alembic commands ###
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/base/langflow/alembic/versions/66f72f04a1de_add_mcp_support_with_project_settings_.py", "license": "MIT License", "lines": 40, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
langflow-ai/langflow:src/backend/base/langflow/api/v1/mcp_projects.py
import asyncio import json import os import platform from asyncio.subprocess import create_subprocess_exec from collections.abc import Awaitable, Callable, Sequence from contextvars import ContextVar from datetime import datetime, timezone from ipaddress import ip_address from pathlib import Path from subprocess import CalledProcessError from typing import Annotated, Any, cast from uuid import UUID import anyio from anyio import BrokenResourceError from anyio.abc import TaskGroup, TaskStatus from fastapi import APIRouter, Depends, HTTPException, Request, Response, status from fastapi.responses import HTMLResponse, JSONResponse from lfx.base.mcp.constants import MAX_MCP_SERVER_NAME_LENGTH from lfx.base.mcp.util import sanitize_mcp_name from lfx.log import logger from lfx.services.deps import get_settings_service, session_scope from lfx.services.mcp_composer.service import MCPComposerError, MCPComposerService from lfx.services.schema import ServiceType from mcp import types from mcp.server import NotificationOptions, Server from mcp.server.sse import SseServerTransport from mcp.server.streamable_http_manager import StreamableHTTPSessionManager from sqlalchemy.orm import selectinload from sqlmodel import select from sqlmodel.ext.asyncio.session import AsyncSession from langflow.api.utils import ( CurrentActiveMCPUser, extract_global_variables_from_headers, raise_error_if_astra_cloud_env, ) from langflow.api.utils.mcp import ( auto_configure_starter_projects_mcp, get_composer_streamable_http_url, get_project_sse_url, get_project_streamable_http_url, get_url_by_os, ) from langflow.api.v1.auth_helpers import handle_auth_settings_update from langflow.api.v1.mcp import ResponseNoOp from langflow.api.v1.mcp_utils import ( current_request_variables_ctx, current_user_ctx, handle_call_tool, handle_list_resources, handle_list_tools, handle_mcp_errors, handle_read_resource, ) from langflow.api.v1.schemas import ( AuthSettings, ComposerUrlResponse, MCPInstallRequest, MCPProjectResponse, MCPProjectUpdateRequest, MCPSettings, ) from langflow.services.auth.constants import AUTO_LOGIN_WARNING from langflow.services.auth.mcp_encryption import decrypt_auth_settings, encrypt_auth_settings from langflow.services.database.models import Flow, Folder from langflow.services.database.models.api_key.crud import check_key, create_api_key from langflow.services.database.models.api_key.model import ApiKey, ApiKeyCreate from langflow.services.database.models.user.crud import get_user_by_username from langflow.services.database.models.user.model import User from langflow.services.deps import get_service # Constants ALL_INTERFACES_HOST = "0.0.0.0" # noqa: S104 router = APIRouter(prefix="/mcp/project", tags=["mcp_projects"]) async def verify_project_auth( db: AsyncSession, project_id: UUID, query_param: str, header_param: str, ) -> User: """MCP-specific user authentication that allows fallback to username lookup when not using API key auth. This function provides authentication for MCP endpoints when using MCP Composer and no API key is provided, or checks if the API key is valid. """ settings_service = get_settings_service() result: ApiKey | User | None project = (await db.exec(select(Folder).where(Folder.id == project_id))).first() if not project: raise HTTPException(status_code=404, detail="Project not found") auth_settings: AuthSettings | None = None # Check if this project requires API key only authentication if project.auth_settings: auth_settings = AuthSettings(**project.auth_settings) if (not auth_settings and not settings_service.auth_settings.AUTO_LOGIN) or ( auth_settings and auth_settings.auth_type == "apikey" ): api_key = query_param or header_param if not api_key: raise HTTPException( status_code=401, detail="API key required for this project. Provide x-api-key header or query parameter.", ) # Validate the API key user = await check_key(db, api_key) if not user: raise HTTPException(status_code=401, detail="Invalid API key") # Verify user has access to the project project_access = ( await db.exec(select(Folder).where(Folder.id == project_id, Folder.user_id == user.id)) ).first() if not project_access: raise HTTPException(status_code=404, detail="Project not found") return user # Get the first user if not settings_service.auth_settings.SUPERUSER: raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, detail="Missing superuser username in auth settings", ) # For MCP endpoints, always fall back to username lookup when no API key is provided result = await get_user_by_username(db, settings_service.auth_settings.SUPERUSER) if result: logger.warning(AUTO_LOGIN_WARNING) return result raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Invalid user", ) # Smart authentication dependency that chooses method based on project settings async def verify_project_auth_conditional( project_id: UUID, request: Request, ) -> User: """Choose authentication method based on project settings. - MCP Composer enabled + API key auth: Only allow API keys - All other cases: Use standard MCP auth (JWT + API keys) """ async with session_scope() as session: # Get project to check auth settings project = (await session.exec(select(Folder).where(Folder.id == project_id))).first() if not project: raise HTTPException(status_code=404, detail="Project not found") # Extract token token: str | None = None auth_header = request.headers.get("authorization") if auth_header and auth_header.startswith("Bearer "): token = auth_header[7:] # Extract API keys api_key_query_value = request.query_params.get("x-api-key") api_key_header_value = request.headers.get("x-api-key") # Check if this project requires API key only authentication if get_settings_service().settings.mcp_composer_enabled: return await verify_project_auth(session, project_id, api_key_query_value, api_key_header_value) # For all other cases, use standard MCP authentication (allows JWT + API keys) # Call the MCP auth function directly from langflow.services.auth.utils import get_current_user_mcp user = await get_current_user_mcp( token=token or "", query_param=api_key_query_value, header_param=api_key_header_value, db=session ) # Verify project access project_access = ( await session.exec(select(Folder).where(Folder.id == project_id, Folder.user_id == user.id)) ).first() if not project_access: raise HTTPException(status_code=404, detail="Project not found") return user # Create project-specific context variable current_project_ctx: ContextVar[UUID | None] = ContextVar("current_project_ctx", default=None) # Mapping of project-specific SSE transports project_sse_transports: dict[str, SseServerTransport] = {} def get_project_sse(project_id: UUID | None) -> SseServerTransport: """Get or create an SSE transport for a specific project.""" if not project_id: raise HTTPException(status_code=400, detail="Project ID is required to start MCP server") project_id_str = str(project_id) if project_id_str not in project_sse_transports: project_sse_transports[project_id_str] = SseServerTransport(f"/api/v1/mcp/project/{project_id_str}/") return project_sse_transports[project_id_str] async def _build_project_tools_response( project_id: UUID, current_user: CurrentActiveMCPUser, *, mcp_enabled: bool, ) -> MCPProjectResponse: """Return tool metadata for a project.""" tools: list[MCPSettings] = [] try: async with session_scope() as session: # Fetch the project first to verify it exists and belongs to the current user project = ( await session.exec( select(Folder) .options(selectinload(Folder.flows)) .where(Folder.id == project_id, Folder.user_id == current_user.id) ) ).first() if not project: raise HTTPException(status_code=404, detail="Project not found") # Query flows in the project flows_query = select(Flow).where(Flow.folder_id == project_id, Flow.is_component == False) # noqa: E712 # Optionally filter for MCP-enabled flows only if mcp_enabled: flows_query = flows_query.where(Flow.mcp_enabled == True) # noqa: E712 flows = (await session.exec(flows_query)).all() for flow in flows: if flow.user_id is None: continue # Format the flow name according to MCP conventions (snake_case) flow_name = sanitize_mcp_name(flow.name) # Use action_name and action_description if available, otherwise use defaults name = sanitize_mcp_name(flow.action_name) if flow.action_name else flow_name description = flow.action_description or ( flow.description if flow.description else f"Tool generated from flow: {flow_name}" ) try: tool = MCPSettings( id=flow.id, action_name=name, action_description=description, mcp_enabled=flow.mcp_enabled, # inputSchema=json_schema_from_flow(flow), name=flow.name, description=flow.description, ) tools.append(tool) except Exception as e: # noqa: BLE001 msg = f"Error in listing project tools: {e!s} from flow: {name}" await logger.awarning(msg) continue # Get project-level auth settings but mask sensitive fields for security auth_settings = None if project.auth_settings: # Decrypt to get the settings structure decrypted_settings = decrypt_auth_settings(project.auth_settings) if decrypted_settings: # Mask sensitive fields before sending to frontend masked_settings = decrypted_settings.copy() if masked_settings.get("oauth_client_secret"): masked_settings["oauth_client_secret"] = "*******" # noqa: S105 if masked_settings.get("api_key"): masked_settings["api_key"] = "*******" auth_settings = AuthSettings(**masked_settings) except Exception as e: msg = f"Error listing project tools: {e!s}" await logger.aexception(msg) raise HTTPException(status_code=500, detail=str(e)) from e return MCPProjectResponse(tools=tools, auth_settings=auth_settings) @router.get("/{project_id}") async def list_project_tools( project_id: UUID, current_user: CurrentActiveMCPUser, *, mcp_enabled: bool = True, ) -> Response: """List project MCP tools.""" metadata = await _build_project_tools_response(project_id, current_user, mcp_enabled=mcp_enabled) return JSONResponse(content=metadata.model_dump(mode="json")) ######################################################## # legacy SSE transport routes ######################################################## @router.head( "/{project_id}/sse", response_class=HTMLResponse, dependencies=[Depends(raise_error_if_astra_cloud_env)], ) async def im_alive(project_id: str): # noqa: ARG001 return Response() @router.get( "/{project_id}/sse", response_class=HTMLResponse, dependencies=[Depends(raise_error_if_astra_cloud_env)], ) async def handle_project_sse( project_id: UUID, request: Request, current_user: Annotated[User, Depends(verify_project_auth_conditional)], ): """Handle SSE connections for a specific project.""" async with session_scope() as session: project = ( await session.exec(select(Folder).where(Folder.id == project_id, Folder.user_id == current_user.id)) ).first() if not project: raise HTTPException(status_code=404, detail="Project not found") sse = get_project_sse(project_id) project_server = get_project_mcp_server(project_id) await logger.adebug("Project MCP server name: %s", project_server.server.name) user_token = current_user_ctx.set(current_user) project_token = current_project_ctx.set(project_id) variables = extract_global_variables_from_headers(request.headers) req_vars_token = current_request_variables_ctx.set(variables or None) try: async with sse.connect_sse(request.scope, request.receive, request._send) as streams: # noqa: SLF001 try: await logger.adebug("Starting SSE connection for project %s", project_id) notification_options = NotificationOptions( prompts_changed=True, resources_changed=True, tools_changed=True ) init_options = project_server.server.create_initialization_options(notification_options) try: await project_server.server.run(streams[0], streams[1], init_options) except Exception: # noqa: BLE001 await logger.aexception("Error in project MCP") except BrokenResourceError: await logger.ainfo("Client disconnected from project SSE connection") except asyncio.CancelledError: await logger.ainfo("Project SSE connection was cancelled") raise except Exception: await logger.aexception("Error in project MCP") raise finally: current_user_ctx.reset(user_token) current_project_ctx.reset(project_token) current_request_variables_ctx.reset(req_vars_token) return ResponseNoOp(status_code=200) async def _handle_project_sse_messages( project_id: UUID, request: Request, current_user: User, ): """Handle POST messages for a project-specific MCP server using SSE transport.""" user_token = current_user_ctx.set(current_user) project_token = current_project_ctx.set(project_id) variables = extract_global_variables_from_headers(request.headers) req_vars_token = current_request_variables_ctx.set(variables or None) try: sse = get_project_sse(project_id) await sse.handle_post_message(request.scope, request.receive, request._send) # noqa: SLF001 except BrokenResourceError as e: await logger.ainfo("Project MCP Server disconnected for project %s", project_id) raise HTTPException(status_code=404, detail=f"Project MCP Server disconnected, error: {e}") from e finally: current_user_ctx.reset(user_token) current_project_ctx.reset(project_token) current_request_variables_ctx.reset(req_vars_token) @router.post("/{project_id}", dependencies=[Depends(raise_error_if_astra_cloud_env)]) @router.post("/{project_id}/", dependencies=[Depends(raise_error_if_astra_cloud_env)]) async def handle_project_messages( project_id: UUID, request: Request, current_user: Annotated[User, Depends(verify_project_auth_conditional)], ): """Handle POST messages for a project-specific MCP server.""" return await _handle_project_sse_messages(project_id, request, current_user) ######################################################## # Streamable HTTP transport routes ######################################################## @router.head("/{project_id}/streamable") async def streamable_health(project_id: UUID): # noqa: ARG001 return Response() async def _dispatch_project_streamable_http( project_id: UUID, request: Request, current_user: User, ) -> Response: """Common handler for project-specific Streamable HTTP requests.""" # Lazily initialize the project's Streamable HTTP manager # to pick up new projects as they are created. project_server = get_project_mcp_server(project_id) await project_server.ensure_session_manager_running() user_token = current_user_ctx.set(current_user) project_token = current_project_ctx.set(project_id) variables = extract_global_variables_from_headers(request.headers) request_vars_token = current_request_variables_ctx.set(variables or None) try: await project_server.session_manager.handle_request(request.scope, request.receive, request._send) # noqa: SLF001 except HTTPException: raise except Exception as exc: await logger.aexception(f"Error handling Streamable HTTP request for project {project_id}: {exc!s}") raise HTTPException(status_code=500, detail="Internal server error in project MCP transport") from exc finally: current_request_variables_ctx.reset(request_vars_token) current_project_ctx.reset(project_token) current_user_ctx.reset(user_token) return ResponseNoOp(status_code=200) streamable_http_route_config = { "methods": ["GET", "POST", "DELETE"], "response_class": ResponseNoOp, } @router.api_route("/{project_id}/streamable", **streamable_http_route_config) @router.api_route("/{project_id}/streamable/", **streamable_http_route_config) async def handle_project_streamable_http( project_id: UUID, request: Request, current_user: Annotated[User, Depends(verify_project_auth_conditional)], ): """Handle Streamable HTTP connections for a specific project.""" return await _dispatch_project_streamable_http(project_id, request, current_user) @router.patch("/{project_id}", status_code=200) async def update_project_mcp_settings( project_id: UUID, request: MCPProjectUpdateRequest, current_user: CurrentActiveMCPUser, ): """Update the MCP settings of all flows in a project and project-level auth settings. On MCP Composer failure, this endpoint should return with a 200 status code and an error message in the body of the response to display to the user. """ try: async with session_scope() as session: # Fetch the project first to verify it exists and belongs to the current user project = ( await session.exec( select(Folder) .options(selectinload(Folder.flows)) .where(Folder.id == project_id, Folder.user_id == current_user.id) ) ).first() if not project: raise HTTPException(status_code=404, detail="Project not found") # Track if MCP Composer needs to be started or stopped should_handle_mcp_composer = False should_start_composer = False should_stop_composer = False # Store original auth settings in case we need to rollback original_auth_settings = project.auth_settings # Update project-level auth settings with encryption if "auth_settings" in request.model_fields_set and request.auth_settings is not None: auth_result = handle_auth_settings_update( existing_project=project, new_auth_settings=request.auth_settings, ) should_handle_mcp_composer = auth_result["should_handle_composer"] should_start_composer = auth_result["should_start_composer"] should_stop_composer = auth_result["should_stop_composer"] # Query flows in the project flows = (await session.exec(select(Flow).where(Flow.folder_id == project_id))).all() flows_to_update = {x.id: x for x in request.settings} updated_flows = [] for flow in flows: if flow.user_id is None or flow.user_id != current_user.id: continue if flow.id in flows_to_update: settings_to_update = flows_to_update[flow.id] flow.mcp_enabled = settings_to_update.mcp_enabled flow.action_name = settings_to_update.action_name flow.action_description = settings_to_update.action_description flow.updated_at = datetime.now(timezone.utc) session.add(flow) updated_flows.append(flow) await session.flush() response: dict[str, Any] = { "message": f"Updated MCP settings for {len(updated_flows)} flows and project auth settings" } # Handle MCP Composer start/stop before committing auth settings if should_handle_mcp_composer: # Get MCP Composer service once for all branches mcp_composer_service: MCPComposerService = cast( MCPComposerService, get_service(ServiceType.MCP_COMPOSER_SERVICE) ) if should_start_composer: await logger.adebug( f"Auth settings changed to OAuth for project {project.name} ({project_id}), " "starting MCP Composer" ) if should_use_mcp_composer(project): try: auth_config = await _get_mcp_composer_auth_config(project) await get_or_start_mcp_composer(auth_config, project.name, project_id) composer_streamable_http_url = await get_composer_streamable_http_url(project) composer_sse_url = await get_composer_sse_url(project) # Clear any previous error on success mcp_composer_service.clear_last_error(str(project_id)) response["result"] = { "project_id": str(project_id), "streamable_http_url": composer_streamable_http_url, "legacy_sse_url": composer_sse_url, "sse_url": composer_sse_url, "uses_composer": True, } except MCPComposerError as e: # Don't rollback auth settings - persist them so UI can show the error await logger.awarning(f"MCP Composer failed to start for project {project_id}: {e.message}") # Store the error message so it can be retrieved via composer-url endpoint mcp_composer_service.set_last_error(str(project_id), e.message) response["result"] = { "project_id": str(project_id), "uses_composer": True, "error_message": e.message, } except Exception as e: # Rollback auth settings on unexpected errors await logger.aerror( f"Unexpected error starting MCP Composer for project {project_id}, " f"rolling back auth settings: {e}" ) project.auth_settings = original_auth_settings raise HTTPException(status_code=500, detail=str(e)) from e else: # OAuth is set but MCP Composer is disabled - save settings but return error # Don't rollback - keep the auth settings so they can be used when composer is enabled await logger.aerror( f"PATCH: OAuth set but MCP Composer is disabled in settings for project {project_id}" ) response["result"] = { "project_id": str(project_id), "uses_composer": False, "error_message": "OAuth authentication is set but MCP Composer is disabled in settings", } elif should_stop_composer: await logger.adebug( f"Auth settings changed from OAuth for project {project.name} ({project_id}), " "stopping MCP Composer" ) await mcp_composer_service.stop_project_composer(str(project_id)) # Clear any error when user explicitly disables OAuth mcp_composer_service.clear_last_error(str(project_id)) # Provide direct connection URLs since we're no longer using composer streamable_http_url = await get_project_streamable_http_url(project_id) legacy_sse_url = await get_project_sse_url(project_id) if not streamable_http_url: raise HTTPException(status_code=500, detail="Failed to get direct Streamable HTTP URL") response["result"] = { "project_id": str(project_id), "streamable_http_url": streamable_http_url, "legacy_sse_url": legacy_sse_url, "sse_url": legacy_sse_url, "uses_composer": False, } # Only commit if composer started successfully (or wasn't needed) session.add(project) await session.commit() return response except Exception as e: msg = f"Error updating project MCP settings: {e!s}" await logger.aexception(msg) raise HTTPException(status_code=500, detail=str(e)) from e def is_local_ip(ip_str: str) -> bool: """Check if an IP address is a loopback address (same machine). Args: ip_str: String representation of an IP address Returns: bool: True if the IP is a loopback address, False otherwise """ # Check if it's exactly "localhost" if ip_str == "localhost": return True # Check if it's exactly "0.0.0.0" (which binds to all interfaces) if ip_str == ALL_INTERFACES_HOST: return True try: # Convert string to IP address object ip = ip_address(ip_str) # Check if it's a loopback address (127.0.0.0/8 for IPv4, ::1 for IPv6) return bool(ip.is_loopback) except ValueError: # If the IP address is invalid, default to False return False def get_client_ip(request: Request) -> str: """Extract the client IP address from a FastAPI request. Args: request: FastAPI Request object Returns: str: The client's IP address """ # Check for X-Forwarded-For header (common when behind proxies) forwarded_for = request.headers.get("X-Forwarded-For") if forwarded_for: # The client IP is the first one in the list return forwarded_for.split(",")[0].strip() # If no proxy headers, use the client's direct IP if request.client: return request.client.host # Fallback if we can't determine the IP - use a non-local IP return "255.255.255.255" # Non-routable IP that will never be local @router.post("/{project_id}/install") async def install_mcp_config( project_id: UUID, body: MCPInstallRequest, request: Request, current_user: CurrentActiveMCPUser, ): """Install MCP server configuration for Cursor, Windsurf, or Claude.""" # Check if the request is coming from a local IP address client_ip = get_client_ip(request) if not is_local_ip(client_ip): raise HTTPException(status_code=500, detail="MCP configuration can only be installed from a local connection") removed_servers: list[str] = [] # Track removed servers for reinstallation try: project = await verify_project_access(project_id, current_user) # Check if project requires API key authentication and generate if needed generated_api_key = None # Determine if we need to generate an API key should_generate_api_key = False if not get_settings_service().settings.mcp_composer_enabled: # When MCP_COMPOSER is disabled, check auth settings or fallback to auto_login setting settings_service = get_settings_service() if project.auth_settings: # Project has auth settings - check if it requires API key if project.auth_settings.get("auth_type") == "apikey": should_generate_api_key = True elif not settings_service.auth_settings.AUTO_LOGIN: # No project auth settings but auto_login is disabled - generate API key should_generate_api_key = True elif project.auth_settings: # When MCP_COMPOSER is enabled, only generate if auth_type is "apikey" if project.auth_settings.get("auth_type") == "apikey": should_generate_api_key = True # Get settings service to build the SSE URL settings_service = get_settings_service() if settings_service.auth_settings.AUTO_LOGIN and not settings_service.auth_settings.SUPERUSER: # Without a superuser fallback, require API key auth for MCP installs. should_generate_api_key = True settings = settings_service.settings host = settings.host or None port = settings.port or None if not host or not port: raise HTTPException(status_code=500, detail="Host and port are not set in settings") # Determine command and args based on operating system os_type = platform.system() use_mcp_composer = should_use_mcp_composer(project) connection_urls: list[str] transport_mode = (body.transport or "sse").lower() if transport_mode not in {"sse", "streamablehttp"}: raise HTTPException(status_code=400, detail="Invalid transport. Use 'sse' or 'streamablehttp'.") if use_mcp_composer: try: auth_config = await _get_mcp_composer_auth_config(project) await get_or_start_mcp_composer(auth_config, project.name, project_id) composer_streamable_http_url = await get_composer_streamable_http_url(project) sse_url = await get_composer_sse_url(project) connection_urls = [composer_streamable_http_url, sse_url] except MCPComposerError as e: await logger.aerror( f"Failed to start MCP Composer for project '{project.name}' ({project_id}): {e.message}" ) raise HTTPException(status_code=500, detail=e.message) from e except Exception as e: error_msg = f"Failed to start MCP Composer for project '{project.name}' ({project_id}): {e!s}" await logger.aerror(error_msg) error_detail = "Failed to start MCP Composer. See logs for details." raise HTTPException(status_code=500, detail=error_detail) from e # For OAuth/MCP Composer, use the special format settings = get_settings_service().settings command = "uvx" args = [ f"mcp-composer{settings.mcp_composer_version}", "--mode", "http", "--endpoint", composer_streamable_http_url, "--sse-url", sse_url, "--client_auth_type", "oauth", "--disable-composer-tools", ] else: # For non-OAuth (API key or no auth), use mcp-proxy streamable_http_url = await get_project_streamable_http_url(project_id) legacy_sse_url = await get_project_sse_url(project_id) command = "uvx" args = ["mcp-proxy"] # Check if we need to add Langflow API key headers # Necessary only when Project API Key Authentication is enabled # Generate a Langflow API key for auto-install if needed # Only add API key headers for projects with "apikey" auth type (not "none" or OAuth) if should_generate_api_key: async with session_scope() as api_key_session: api_key_create = ApiKeyCreate(name=f"MCP Server {project.name}") api_key_response = await create_api_key(api_key_session, api_key_create, current_user.id) langflow_api_key = api_key_response.api_key args.extend(["--headers", "x-api-key", langflow_api_key]) # Add the target URL for mcp-proxy based on requested transport proxy_target_url = streamable_http_url if transport_mode == "streamablehttp" else legacy_sse_url if transport_mode == "streamablehttp": args.extend(["--transport", "streamablehttp"]) args.append(proxy_target_url) connection_urls = [streamable_http_url, legacy_sse_url] if os_type == "Windows" and not use_mcp_composer: # Only wrap in cmd for Windows when using mcp-proxy command = "cmd" args = ["/c", "uvx", *args] await logger.adebug("Windows detected, using cmd command") name = project.name server_name = f"lf-{sanitize_mcp_name(name)[: (MAX_MCP_SERVER_NAME_LENGTH - 4)]}" # Create the MCP configuration server_config: dict[str, Any] = { "command": command, "args": args, } mcp_config = {"mcpServers": {server_name: server_config}} await logger.adebug("Installing MCP config for project: %s (server name: %s)", project.name, server_name) # Get the config file path and check if client is available try: config_path = await get_config_path(body.client.lower()) except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) from e # Check if the client application is available (config directory exists) if not config_path.parent.exists(): raise HTTPException( status_code=400, detail=f"{body.client.capitalize()} is not installed on this system. " f"Please install {body.client.capitalize()} first.", ) # Create parent directories if they don't exist config_path.parent.mkdir(parents=True, exist_ok=True) # Read existing config if it exists existing_config = {} if config_path.exists(): try: with config_path.open("r") as f: existing_config = json.load(f) except json.JSONDecodeError: # If file exists but is invalid JSON, start fresh existing_config = {"mcpServers": {}} # Ensure mcpServers section exists if "mcpServers" not in existing_config: existing_config["mcpServers"] = {} # Remove stale entries that point to the same Langflow URLs (e.g. after the project is renamed) existing_config, removed_servers = remove_server_by_urls(existing_config, connection_urls) if removed_servers: await logger.adebug("Removed existing MCP servers with same SSE URL for reinstall: %s", removed_servers) # Merge new config with existing config existing_config["mcpServers"].update(mcp_config["mcpServers"]) # Write the updated config with config_path.open("w") as f: json.dump(existing_config, f, indent=2) except HTTPException: raise except Exception as e: msg = f"Error installing MCP configuration: {e!s}" await logger.aexception(msg) raise HTTPException(status_code=500, detail=str(e)) from e else: action = "reinstalled" if removed_servers else "installed" message = f"Successfully {action} MCP configuration for {body.client}" if removed_servers: message += f" (replaced existing servers: {', '.join(removed_servers)})" if generated_api_key: auth_type = "API key" if get_settings_service().settings.mcp_composer_enabled else "legacy API key" message += f" with {auth_type} authentication (key name: 'MCP Project {project.name} - {body.client}')" await logger.adebug(message) return {"message": message} @router.get("/{project_id}/composer-url") async def get_project_composer_url( project_id: UUID, current_user: CurrentActiveMCPUser, ) -> ComposerUrlResponse: """Get the MCP Composer URL for a specific project. On failure, this endpoint should return with a 200 status code and an error message in the body of the response to display to the user. """ try: project = await verify_project_access(project_id, current_user) mcp_composer_service: MCPComposerService = cast( MCPComposerService, get_service(ServiceType.MCP_COMPOSER_SERVICE) ) if not should_use_mcp_composer(project): streamable_http_url = await get_project_streamable_http_url(project_id) legacy_sse_url = await get_project_sse_url(project_id) # Check if there's a recent error from a failed OAuth attempt last_error = mcp_composer_service.get_last_error(str(project_id)) # Always return the regular MCP URLs so the UI can fall back to manual installation instructions. response_payload: dict[str, Any] = { "project_id": str(project_id), "uses_composer": False, "streamable_http_url": streamable_http_url, "legacy_sse_url": legacy_sse_url, } # If there's a recent error, return it even though OAuth is not currently active # This happens when OAuth was attempted but rolled back due to an error if last_error: response_payload["error_message"] = last_error return ComposerUrlResponse(**response_payload) auth_config = await _get_mcp_composer_auth_config(project) try: await get_or_start_mcp_composer(auth_config, project.name, project_id) composer_streamable_http_url = await get_composer_streamable_http_url(project) composer_sse_url = await get_composer_sse_url(project) # Clear any previous error on success mcp_composer_service.clear_last_error(str(project_id)) return ComposerUrlResponse( project_id=str(project_id), uses_composer=True, streamable_http_url=composer_streamable_http_url, legacy_sse_url=composer_sse_url, ) except MCPComposerError as e: await logger.aerror( "Failed to obtain MCP Composer URL for project %s (%s): %s", project.name, project_id, e.message, ) return ComposerUrlResponse( project_id=str(project_id), uses_composer=True, error_message=e.message, ) except Exception as e: # noqa: BLE001 await logger.aerror(f"Unexpected error getting composer URL: {e}") return ComposerUrlResponse( project_id=str(project_id), uses_composer=True, error_message="Failed to start MCP Composer. See logs for details.", ) except Exception as e: # noqa: BLE001 msg = f"Error getting composer URL for project {project_id}: {e!s}" await logger.aerror(msg) return ComposerUrlResponse( project_id=str(project_id), uses_composer=True, error_message="Failed to get MCP Composer URL. See logs for details.", ) @router.get("/{project_id}/installed") async def check_installed_mcp_servers( project_id: UUID, current_user: CurrentActiveMCPUser, ): """Check if MCP server configuration is installed for this project in Cursor, Windsurf, or Claude.""" try: # Verify project exists and user has access async with session_scope() as session: project = ( await session.exec(select(Folder).where(Folder.id == project_id, Folder.user_id == current_user.id)) ).first() if not project: raise HTTPException(status_code=404, detail="Project not found") project = await verify_project_access(project_id, current_user) if should_use_mcp_composer(project): project_streamable_url = await get_composer_streamable_http_url(project) project_sse_url = await get_composer_sse_url(project) else: project_streamable_url = await get_project_streamable_http_url(project_id) project_sse_url = await get_project_sse_url(project_id) await logger.adebug( "Checking for installed MCP servers for project: %s (SSE URL: %s)", project.name, project_sse_url ) # Define supported clients clients = ["cursor", "windsurf", "claude"] results = [] for client_name in clients: try: # Get config path for this client config_path = await get_config_path(client_name) available = config_path.parent.exists() installed = False await logger.adebug("Checking %s config at: %s (exists: %s)", client_name, config_path, available) # If config file exists, check if project is installed if available: try: with config_path.open("r") as f: config_data = json.load(f) if config_contains_server_url(config_data, [project_streamable_url, project_sse_url]): await logger.adebug( "Found %s config with matching URL for project %s", client_name, project.name ) installed = True else: await logger.adebug( "%s config exists but no server with URL: %s (available servers: %s)", client_name, project_sse_url, list(config_data.get("mcpServers", {}).keys()), ) except json.JSONDecodeError: await logger.awarning("Failed to parse %s config JSON at: %s", client_name, config_path) # available is True but installed remains False due to parse error else: await logger.adebug("%s config path not found or doesn't exist: %s", client_name, config_path) # Add result for this client results.append({"name": client_name, "installed": installed, "available": available}) except Exception as e: # noqa: BLE001 # If there's an error getting config path or checking the client, # mark it as not available and not installed await logger.awarning("Error checking %s configuration: %s", client_name, str(e)) results.append({"name": client_name, "installed": False, "available": False}) except Exception as e: msg = f"Error checking MCP configuration: {e!s}" await logger.aexception(msg) raise HTTPException(status_code=500, detail=str(e)) from e return results def _normalize_url_list(urls: Sequence[str] | str) -> list[str]: """Ensure URL inputs are always handled as a list of strings.""" if isinstance(urls, str): return [urls] try: return [str(url) for url in urls] except TypeError as exc: error_msg = "urls must be a sequence of strings or a single string" raise TypeError(error_msg) from exc def _args_reference_urls(args: Sequence[Any] | None, urls: list[str]) -> bool: """Check whether the given args list references any of the provided URLs.""" if not args or not urls: return False return bool({arg for arg in args if isinstance(arg, str)}.intersection(urls)) def config_contains_server_url(config_data: dict, urls: Sequence[str] | str) -> bool: """Check if any MCP server in the config uses one of the specified URLs.""" normalized_urls = _normalize_url_list(urls) if not normalized_urls: return False mcp_servers = config_data.get("mcpServers", {}) for server_name, server_config in mcp_servers.items(): if _args_reference_urls(server_config.get("args", []), normalized_urls): logger.debug("Found matching server URL in server: %s", server_name) return True return False async def get_composer_sse_url(project: Folder) -> str: """Get the SSE URL for a project using MCP Composer.""" auth_config = await _get_mcp_composer_auth_config(project) composer_host = auth_config.get("oauth_host") composer_port = auth_config.get("oauth_port") if not composer_host or not composer_port: error_msg = "OAuth host and port are required to get the SSE URL for MCP Composer" raise ValueError(error_msg) composer_sse_url = f"http://{composer_host}:{composer_port}/sse" return await get_url_by_os(composer_host, composer_port, composer_sse_url) async def get_config_path(client: str) -> Path: """Get the configuration file path for a given client and operating system.""" os_type = platform.system() is_wsl = os_type == "Linux" and "microsoft" in platform.uname().release.lower() if client.lower() == "cursor": return Path.home() / ".cursor" / "mcp.json" if client.lower() == "windsurf": return Path.home() / ".codeium" / "windsurf" / "mcp_config.json" if client.lower() == "claude": if os_type == "Darwin": # macOS return Path.home() / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json" if os_type == "Windows" or is_wsl: # Windows or WSL (Claude runs on Windows host) if is_wsl: # In WSL, we need to access the Windows APPDATA directory try: # First try to get the Windows username proc = await create_subprocess_exec( "/mnt/c/Windows/System32/cmd.exe", "/c", "echo %USERNAME%", stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stdout, _stderr = await proc.communicate() if proc.returncode == 0 and stdout.strip(): windows_username = stdout.decode().strip() return Path( f"/mnt/c/Users/{windows_username}/AppData/Roaming/Claude/claude_desktop_config.json" ) # Fallback: try to find the Windows user directory users_dir = Path("/mnt/c/Users") if users_dir.exists(): # Get the first non-system user directory user_dirs = [ d for d in users_dir.iterdir() if d.is_dir() and not d.name.startswith(("Default", "Public", "All Users")) ] if user_dirs: return user_dirs[0] / "AppData" / "Roaming" / "Claude" / "claude_desktop_config.json" if not Path("/mnt/c").exists(): msg = "Windows C: drive not mounted at /mnt/c in WSL" raise ValueError(msg) msg = "Could not find valid Windows user directory in WSL" raise ValueError(msg) except (OSError, CalledProcessError) as e: await logger.awarning("Failed to determine Windows user path in WSL: %s", str(e)) msg = f"Could not determine Windows Claude config path in WSL: {e!s}" raise ValueError(msg) from e # Regular Windows return Path(os.environ["APPDATA"]) / "Claude" / "claude_desktop_config.json" msg = "Unsupported operating system for Claude configuration" raise ValueError(msg) msg = "Unsupported client" raise ValueError(msg) def remove_server_by_urls(config_data: dict, urls: Sequence[str] | str) -> tuple[dict, list[str]]: """Remove any MCP servers that use one of the specified URLs from config data. Returns: tuple: (updated_config, list_of_removed_server_names) """ normalized_urls = _normalize_url_list(urls) if not normalized_urls: return config_data, [] if "mcpServers" not in config_data: return config_data, [] removed_servers: list[str] = [] servers_to_remove: list[str] = [] # Find servers to remove for server_name, server_config in config_data["mcpServers"].items(): if _args_reference_urls(server_config.get("args", []), normalized_urls): servers_to_remove.append(server_name) # Remove the servers for server_name in servers_to_remove: del config_data["mcpServers"][server_name] removed_servers.append(server_name) logger.debug("Removed existing server with matching SSE URL: %s", server_name) return config_data, removed_servers async def _get_mcp_composer_auth_config(project) -> dict: """Get MCP Composer authentication configuration from project settings. Args: project: The project object containing auth_settings Returns: dict: The decrypted authentication configuration Raises: HTTPException: If MCP Composer is not enabled or auth config is missing """ auth_config = None if project.auth_settings: decrypted_settings = decrypt_auth_settings(project.auth_settings) if decrypted_settings: auth_config = decrypted_settings if not auth_config: error_message = "Auth config is missing. Please check your settings and try again." raise ValueError(error_message) return auth_config # Project-specific MCP server instance for handling project-specific tools class ProjectMCPServer: def __init__(self, project_id: UUID): self.project_id = project_id self.server = Server(f"langflow-mcp-project-{project_id}") # TODO: implement an environment variable to enable/disable stateless mode self.session_manager = StreamableHTTPSessionManager(self.server, stateless=True) # since we lazily initialize the session manager's lifecycle # via .run(), which can only be called once, otherwise an error is raised, # we use the lock to prevent race conditions on concurrent requests to prevent such an error self._manager_lock = anyio.Lock() self._manager_started = False # whether or not the session manager is running # Register handlers that filter by project @self.server.list_tools() @handle_mcp_errors async def handle_list_project_tools(): """Handle listing tools for this specific project.""" return await handle_list_tools(project_id=self.project_id, mcp_enabled_only=True) @self.server.list_prompts() async def handle_list_prompts(): return [] @self.server.list_resources() async def handle_list_project_resources(): """Handle listing resources for this specific project.""" return await handle_list_resources(project_id=self.project_id) @self.server.read_resource() async def handle_read_project_resource(uri: str) -> bytes: """Handle resource read requests for this specific project.""" return await handle_read_resource(uri=uri) @self.server.call_tool() @handle_mcp_errors async def handle_call_project_tool(name: str, arguments: dict) -> list[types.TextContent]: """Handle tool execution requests for this specific project.""" return await handle_call_tool( name=name, arguments=arguments, server=self.server, project_id=self.project_id, is_action=True, ) async def ensure_session_manager_running(self) -> None: """Start the project's Streamable HTTP manager if needed.""" if self._manager_started: return async with self._manager_lock: if self._manager_started: return try: task_group = get_project_task_group() await task_group.start_task(self._run_session_manager) await logger.adebug("Streamable HTTP manager started for project %s", self.project_id) except Exception as e: await logger.aexception(f"Failed to start session manager for project {self.project_id}: {e}") raise async def _run_session_manager(self, *, task_status: TaskStatus[None] = anyio.TASK_STATUS_IGNORED): """Own the lifecycle of the project's Streamable HTTP session manager.""" try: async with self.session_manager.run(): self._manager_started = True # set flag before unblocking task (ensures waiting requests proceed) task_status.started() # unblock await anyio.sleep_forever() except anyio.get_cancelled_exc_class(): await logger.adebug(f"Streamable HTTP manager cancelled for project {self.project_id}") except Exception as e: await logger.aexception(f"Error in session manager for project {self.project_id}: {e}") raise finally: self._manager_started = False await logger.adebug(f"Streamable HTTP manager stopped for project {self.project_id}") # Cache of project MCP servers project_mcp_servers: dict[str, ProjectMCPServer] = {} # Due to the lazy initialization of the project MCP servers' # streamable-http session managers, we implement a global # task group (AnyIO) manager for the session managers. # This ensures that each session manager's .run() context manager is # entered and exited from the same coroutine, otherwise Asyncio will raise a RuntimeError. class ProjectTaskGroup: """Manage the dynamically created MCP project servers' streamable-http session managers. Utilizes an AnyIO TaskGroup to manage the lifecycle of the streamable-http session managers. This ensures that each session manager's .run() context manager is entered and exited from the same coroutine, otherwise Asyncio will raise a RuntimeError. """ def __init__(self) -> None: self._started = False self._start_stop_lock = anyio.Lock() self._task_group: TaskGroup | None = None self._tg_task: asyncio.Task | None = None self._tg_ready = anyio.Event() async def _start_tg(self) -> None: """Background task that owns the task group lifecycle. This ensures __aenter__ and __aexit__ happen in the same task. """ async with anyio.create_task_group() as tg: self._task_group = tg self._tg_ready.set() await anyio.sleep_forever() async def start(self) -> None: """Create the project task group.""" async with self._start_stop_lock: if self._started: return self._tg_ready = anyio.Event() self._tg_task = asyncio.create_task(self._start_tg()) await self._tg_ready.wait() self._started = True async def stop(self) -> None: """Close the shared project task group and signal all servers to shut down.""" async with self._start_stop_lock: if not self._started: return try: # https://anyio.readthedocs.io/en/stable/cancellation.html, https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.cancel self._task_group.cancel_scope.cancel() # type: ignore[union-attr] await self._tg_task # type: ignore[misc] except Exception as e: # noqa: BLE001 await logger.aexception(f"Failed to stop project task group: {e}") finally: self._cleanup() await logger.adebug("Project MCP task group stopped") async def start_task(self, func: Callable[..., Awaitable[Any]], *args) -> Any: if not self._started or self._task_group is None: msg = "MCP project task group not initialized. Call start_project_task_group() first." raise RuntimeError(msg) return await self._task_group.start(func, *args) def _cleanup(self) -> None: """Cleanup the project task group.""" self._task_group = None self._tg_task = None self._tg_ready = None self._started = False project_mcp_servers.clear() _project_task_group = ProjectTaskGroup() async def start_project_task_group() -> None: """Initialize the shared project task group.""" await _project_task_group.start() def get_project_task_group() -> ProjectTaskGroup: """Get the project task group manager.""" return _project_task_group async def stop_project_task_group() -> None: """Close the shared project task group.""" await _project_task_group.stop() def get_project_mcp_server(project_id: UUID | None) -> ProjectMCPServer: """Get or create an MCP server for a specific project.""" if project_id is None: error_message = "Project ID cannot be None when getting project MCP server" raise ValueError(error_message) project_id_str = str(project_id) if project_id_str not in project_mcp_servers: project_mcp_servers[project_id_str] = ProjectMCPServer(project_id) return project_mcp_servers[project_id_str] # Note: Shutdown is handled by stop_project_task_group() in main.py lifespan # This handler was removed because ProjectMCPServer doesn't have stop_session_manager() # Session managers are managed centrally by ProjectTaskGroup async def register_project_with_composer(project: Folder): """Register a project with MCP Composer by starting a dedicated composer instance.""" try: mcp_composer_service: MCPComposerService = cast( "MCPComposerService", get_service(ServiceType.MCP_COMPOSER_SERVICE) ) settings = get_settings_service().settings if not settings.host or not settings.port: error_msg = "Langflow host and port must be set in settings to register project with MCP Composer" raise ValueError(error_msg) if not project.id: error_msg = "Project must have an ID to register with MCP Composer" raise ValueError(error_msg) streamable_http_url = await get_project_streamable_http_url(project.id) legacy_sse_url = await get_project_sse_url(project.id) auth_config = await _get_mcp_composer_auth_config(project) error_message = await mcp_composer_service.start_project_composer( project_id=str(project.id), streamable_http_url=streamable_http_url, auth_config=auth_config, legacy_sse_url=legacy_sse_url, ) if error_message is not None: raise RuntimeError(error_message) await logger.adebug(f"Registered project {project.name} ({project.id}) with MCP Composer") except Exception as e: # noqa: BLE001 await logger.awarning(f"Failed to register project {project.id} with MCP Composer: {e}") async def init_mcp_servers(): """Initialize MCP servers for all projects.""" try: settings_service = get_settings_service() async with session_scope() as session: projects = (await session.exec(select(Folder))).all() for project in projects: try: # Auto-enable API key auth for projects without auth settings or with "none" auth # when AUTO_LOGIN is false if not settings_service.auth_settings.AUTO_LOGIN: should_update_to_apikey = False if not project.auth_settings: # No auth settings at all should_update_to_apikey = True # Check if existing auth settings have auth_type "none" elif project.auth_settings.get("auth_type") == "none": should_update_to_apikey = True if should_update_to_apikey: default_auth = {"auth_type": "apikey"} project.auth_settings = encrypt_auth_settings(default_auth) session.add(project) await logger.ainfo( f"Auto-enabled API key authentication for existing project {project.name} " f"({project.id}) due to AUTO_LOGIN=false" ) # WARN: If oauth projects exist in the database and the MCP Composer is disabled, # these projects will be reset to "apikey" or "none" authentication, erasing all oauth settings. if ( not settings_service.settings.mcp_composer_enabled and project.auth_settings and project.auth_settings.get("auth_type") == "oauth" ): # Reset OAuth projects to appropriate auth type based on AUTO_LOGIN setting fallback_auth_type = "apikey" if not settings_service.auth_settings.AUTO_LOGIN else "none" clean_auth = AuthSettings(auth_type=fallback_auth_type) project.auth_settings = clean_auth.model_dump(exclude_none=True) session.add(project) await logger.adebug( f"Updated OAuth project {project.name} ({project.id}) to use {fallback_auth_type} " f"authentication because MCP Composer is disabled" ) get_project_sse(project.id) get_project_mcp_server(project.id) await logger.adebug(f"Initialized MCP server for project: {project.name} ({project.id})") # Only register with MCP Composer if OAuth authentication is configured if get_settings_service().settings.mcp_composer_enabled and project.auth_settings: auth_type = project.auth_settings.get("auth_type") if auth_type == "oauth": await logger.adebug( f"Starting MCP Composer for OAuth project {project.name} ({project.id}) on startup" ) await register_project_with_composer(project) except Exception as e: # noqa: BLE001 msg = f"Failed to initialize MCP server for project {project.id}: {e}" await logger.aexception(msg) # Continue to next project even if this one fails # Auto-configure starter projects with MCP server settings if enabled await auto_configure_starter_projects_mcp(session) except Exception as e: # noqa: BLE001 msg = f"Failed to initialize MCP servers: {e}" await logger.aexception(msg) async def verify_project_access(project_id: UUID, current_user: CurrentActiveMCPUser) -> Folder: """Verify project exists and user has access.""" async with session_scope() as session: project = ( await session.exec(select(Folder).where(Folder.id == project_id, Folder.user_id == current_user.id)) ).first() if not project: raise HTTPException(status_code=404, detail="Project not found") return project def should_use_mcp_composer(project: Folder) -> bool: """Check if project uses OAuth authentication and MCP Composer is enabled.""" # If MCP Composer is disabled globally, never use it regardless of project settings if not get_settings_service().settings.mcp_composer_enabled: return False return project.auth_settings is not None and project.auth_settings.get("auth_type", "") == "oauth" async def get_or_start_mcp_composer(auth_config: dict, project_name: str, project_id: UUID) -> None: """Get MCP Composer or start it if not running. Raises: MCPComposerError: If MCP Composer fails to start """ from lfx.services.mcp_composer.service import MCPComposerConfigError mcp_composer_service: MCPComposerService = cast("MCPComposerService", get_service(ServiceType.MCP_COMPOSER_SERVICE)) # Prepare current auth config for comparison settings = get_settings_service().settings if not settings.host or not settings.port: error_msg = "Langflow host and port must be set in settings to register project with MCP Composer" raise ValueError(error_msg) streamable_http_url = await get_project_streamable_http_url(project_id) legacy_sse_url = await get_project_sse_url(project_id) if not auth_config: error_msg = f"Auth config is required to start MCP Composer for project {project_name}" raise MCPComposerConfigError(error_msg, str(project_id)) await mcp_composer_service.start_project_composer( str(project_id), streamable_http_url, auth_config, legacy_sse_url=legacy_sse_url, )
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/base/langflow/api/v1/mcp_projects.py", "license": "MIT License", "lines": 1285, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
langflow-ai/langflow:src/backend/base/langflow/api/v1/projects.py
import io import json import zipfile from datetime import datetime, timezone from typing import Annotated, cast from urllib.parse import quote from uuid import UUID import orjson from fastapi import APIRouter, BackgroundTasks, Depends, File, HTTPException, Query, Response, UploadFile, status from fastapi.encoders import jsonable_encoder from fastapi.responses import StreamingResponse from fastapi_pagination import Params from fastapi_pagination.ext.sqlmodel import apaginate from lfx.log.logger import logger from lfx.services.mcp_composer.service import MCPComposerService from sqlalchemy import or_, update from sqlalchemy.orm import selectinload from sqlmodel import select from langflow.api.utils import CurrentActiveUser, DbSession, cascade_delete_flow, custom_params, remove_api_keys from langflow.api.utils.mcp.config_utils import validate_mcp_server_for_project from langflow.api.v1.auth_helpers import handle_auth_settings_update from langflow.api.v1.flows import create_flows from langflow.api.v1.mcp_projects import ( get_project_sse_url, # noqa: F401 get_project_streamable_http_url, register_project_with_composer, ) from langflow.api.v1.schemas import FlowListCreate from langflow.api.v2.mcp import update_server from langflow.helpers.flow import generate_unique_flow_name from langflow.helpers.folders import generate_unique_folder_name from langflow.initial_setup.constants import ASSISTANT_FOLDER_NAME, STARTER_FOLDER_NAME from langflow.services.auth.mcp_encryption import encrypt_auth_settings from langflow.services.database.models.api_key.crud import create_api_key from langflow.services.database.models.api_key.model import ApiKeyCreate from langflow.services.database.models.flow.model import Flow, FlowCreate, FlowRead from langflow.services.database.models.folder.constants import DEFAULT_FOLDER_NAME from langflow.services.database.models.folder.model import ( Folder, FolderCreate, FolderRead, FolderReadWithFlows, FolderUpdate, ) from langflow.services.database.models.folder.pagination_model import FolderWithPaginatedFlows from langflow.services.deps import get_service, get_settings_service, get_storage_service from langflow.services.schema import ServiceType router = APIRouter(prefix="/projects", tags=["Projects"]) @router.post("/", response_model=FolderRead, status_code=201) async def create_project( *, session: DbSession, project: FolderCreate, current_user: CurrentActiveUser, ): try: new_project = Folder.model_validate(project, from_attributes=True) new_project.user_id = current_user.id # First check if the project.name is unique # there might be flows with name like: "MyFlow", "MyFlow (1)", "MyFlow (2)" # so we need to check if the name is unique with `like` operator # if we find a flow with the same name, we add a number to the end of the name # based on the highest number found if ( await session.exec( statement=select(Folder).where(Folder.name == new_project.name).where(Folder.user_id == current_user.id) ) ).first(): project_results = await session.exec( select(Folder).where( Folder.name.like(f"{new_project.name}%"), # type: ignore[attr-defined] Folder.user_id == current_user.id, ) ) if project_results: project_names = [project.name for project in project_results] # TODO: this throws an error if the name contains non-numeric content in parentheses project_numbers = [int(name.split("(")[-1].split(")")[0]) for name in project_names if "(" in name] if project_numbers: new_project.name = f"{new_project.name} ({max(project_numbers) + 1})" else: new_project.name = f"{new_project.name} (1)" settings_service = get_settings_service() # If AUTO_LOGIN is false, automatically enable API key authentication default_auth = {"auth_type": "none"} if not settings_service.auth_settings.AUTO_LOGIN and not new_project.auth_settings: default_auth = {"auth_type": "apikey"} new_project.auth_settings = encrypt_auth_settings(default_auth) await logger.adebug( f"Auto-enabled API key authentication for project {new_project.name} " f"({new_project.id}) due to AUTO_LOGIN=false" ) session.add(new_project) await session.flush() await session.refresh(new_project) # Auto-register MCP server for this project with configured default auth if get_settings_service().settings.add_projects_to_mcp_servers: try: # Build Streamable HTTP URL (preferred transport) and legacy SSE URL (for docs/errors) streamable_http_url = await get_project_streamable_http_url(new_project.id) # legacy SSE URL # sse_url = await get_project_sse_url(new_project.id) # Prepare server config based on auth type same as new project if default_auth.get("auth_type", "none") == "apikey": # Create API key for API key authentication api_key_name = f"MCP Project {new_project.name} - default" unmasked_api_key = await create_api_key(session, ApiKeyCreate(name=api_key_name), current_user.id) # Starting v>=1.7.1, we use Streamable HTTP transport by default command = "uvx" args = [ "mcp-proxy", "--transport", "streamablehttp", "--headers", "x-api-key", unmasked_api_key.api_key, streamable_http_url, ] elif default_auth.get("auth_type", "none") == "oauth": msg = "OAuth authentication is not yet implemented for MCP server creation during project creation." logger.warning(msg) raise HTTPException(status_code=501, detail=msg) else: # default_auth_type == "none" # No authentication - direct connection command = "uvx" args = [ "mcp-proxy", "--transport", "streamablehttp", streamable_http_url, ] server_config = {"command": command, "args": args} # Validate MCP server for this project validation_result = await validate_mcp_server_for_project( new_project.id, new_project.name, current_user, session, get_storage_service(), get_settings_service(), operation="create", ) # Handle conflicts if validation_result.has_conflict: await logger.aerror(validation_result.conflict_message) raise HTTPException( status_code=409, # Conflict - semantically correct for name conflicts detail=validation_result.conflict_message, ) # Log if updating existing server if validation_result.should_skip: msg = ( f"MCP server '{validation_result.server_name}' " f"already exists for project {new_project.id}, updating" ) await logger.adebug(msg) server_name = validation_result.server_name await update_server( server_name, server_config, current_user, session, get_storage_service(), get_settings_service(), ) except HTTPException: # Re-raise HTTP validation errors (conflicts, etc.) raise except NotImplementedError: msg = "OAuth as default MCP authentication type is not yet implemented" await logger.aerror(msg) raise except Exception as e: # noqa: BLE001 msg = f"Failed to auto-register MCP server for project {new_project.id}: {e}" await logger.aexception(msg, exc_info=True) if project.components_list: update_statement_components = ( update(Flow).where(Flow.id.in_(project.components_list)).values(folder_id=new_project.id) # type: ignore[attr-defined] ) await session.exec(update_statement_components) if project.flows_list: update_statement_flows = ( update(Flow).where(Flow.id.in_(project.flows_list)).values(folder_id=new_project.id) # type: ignore[attr-defined] ) await session.exec(update_statement_flows) # Convert to FolderRead while session is still active to avoid detached instance errors folder_read = FolderRead.model_validate(new_project, from_attributes=True) except HTTPException: # Re-raise HTTP exceptions (like 409 conflicts) without modification raise except Exception as e: raise HTTPException(status_code=500, detail=str(e)) from e return folder_read @router.get("/", response_model=list[FolderRead], status_code=200) async def read_projects( *, session: DbSession, current_user: CurrentActiveUser, ): try: projects = ( await session.exec( select(Folder).where( or_(Folder.user_id == current_user.id, Folder.user_id == None) # noqa: E711 ) ) ).all() projects = [project for project in projects if project.name != STARTER_FOLDER_NAME] sorted_projects = sorted(projects, key=lambda x: x.name != DEFAULT_FOLDER_NAME) # Convert to FolderRead while session is still active to avoid detached instance errors return [FolderRead.model_validate(project, from_attributes=True) for project in sorted_projects] except Exception as e: raise HTTPException(status_code=500, detail=str(e)) from e @router.get("/{project_id}", response_model=FolderWithPaginatedFlows | FolderReadWithFlows, status_code=200) async def read_project( *, session: DbSession, project_id: UUID, current_user: CurrentActiveUser, params: Annotated[Params | None, Depends(custom_params)], page: Annotated[int | None, Query()] = None, size: Annotated[int | None, Query()] = None, is_component: bool = False, is_flow: bool = False, search: str = "", ): try: project = ( await session.exec( select(Folder) .options(selectinload(Folder.flows)) .where(Folder.id == project_id, Folder.user_id == current_user.id) ) ).first() except Exception as e: if "No result found" in str(e): raise HTTPException(status_code=404, detail="Project not found") from e raise HTTPException(status_code=500, detail=str(e)) from e if not project: raise HTTPException(status_code=404, detail="Project not found") try: # Check if pagination is explicitly requested by the user (both page and size provided) if page is not None and size is not None: stmt = select(Flow).where(Flow.folder_id == project_id) if Flow.updated_at is not None: stmt = stmt.order_by(Flow.updated_at.desc()) # type: ignore[attr-defined] if is_component: stmt = stmt.where(Flow.is_component == True) # noqa: E712 if is_flow: stmt = stmt.where(Flow.is_component == False) # noqa: E712 if search: stmt = stmt.where(Flow.name.like(f"%{search}%")) # type: ignore[attr-defined] import warnings with warnings.catch_warnings(): warnings.filterwarnings( "ignore", category=DeprecationWarning, module=r"fastapi_pagination\.ext\.sqlalchemy" ) paginated_flows = await apaginate(session, stmt, params=params) return FolderWithPaginatedFlows(folder=FolderRead.model_validate(project), flows=paginated_flows) # If no pagination requested, return all flows for the current user flows_from_current_user_in_project = [flow for flow in project.flows if flow.user_id == current_user.id] project.flows = flows_from_current_user_in_project # Convert to FolderReadWithFlows while session is still active to avoid detached instance errors return FolderReadWithFlows.model_validate(project, from_attributes=True) except Exception as e: raise HTTPException(status_code=500, detail=str(e)) from e @router.patch("/{project_id}", response_model=FolderRead, status_code=200) async def update_project( *, session: DbSession, project_id: UUID, project: FolderUpdate, # Assuming FolderUpdate is a Pydantic model defining updatable fields current_user: CurrentActiveUser, background_tasks: BackgroundTasks, ): try: existing_project = ( await session.exec(select(Folder).where(Folder.id == project_id, Folder.user_id == current_user.id)) ).first() except Exception as e: raise HTTPException(status_code=500, detail=str(e)) from e if not existing_project: raise HTTPException(status_code=404, detail="Project not found") result = await session.exec( select(Flow.id, Flow.is_component).where(Flow.folder_id == existing_project.id, Flow.user_id == current_user.id) ) flows_and_components = result.all() project.flows = [flow_id for flow_id, is_component in flows_and_components if not is_component] project.components = [flow_id for flow_id, is_component in flows_and_components if is_component] try: # Track if MCP Composer needs to be started or stopped should_start_mcp_composer = False should_stop_mcp_composer = False # Check if auth_settings is being updated if "auth_settings" in project.model_fields_set: # Check if auth_settings was explicitly provided auth_result = handle_auth_settings_update( existing_project=existing_project, new_auth_settings=project.auth_settings, ) should_start_mcp_composer = auth_result["should_start_composer"] should_stop_mcp_composer = auth_result["should_stop_composer"] # Handle other updates if project.name and project.name != existing_project.name: old_project_name = existing_project.name existing_project.name = project.name # Update corresponding MCP server name if auto-add is enabled if get_settings_service().settings.add_projects_to_mcp_servers: try: # Validate old server (for this specific project) old_validation = await validate_mcp_server_for_project( existing_project.id, old_project_name, current_user, session, get_storage_service(), get_settings_service(), operation="update", ) # Validate new server name (check for conflicts) new_validation = await validate_mcp_server_for_project( existing_project.id, project.name, current_user, session, get_storage_service(), get_settings_service(), operation="update", ) # Only proceed if server names would be different if old_validation.server_name != new_validation.server_name: # Check if new server name would conflict with different project if new_validation.has_conflict: await logger.aerror(new_validation.conflict_message) raise HTTPException( status_code=409, # Conflict - semantically correct for name conflicts detail=new_validation.conflict_message, ) # If old server exists and matches this project, proceed with rename if old_validation.server_exists and old_validation.project_id_matches: # Remove the old server await update_server( old_validation.server_name, {}, # Empty config for deletion current_user, session, get_storage_service(), get_settings_service(), delete=True, ) # Add server with new name and existing config await update_server( new_validation.server_name, old_validation.existing_config or {}, current_user, session, get_storage_service(), get_settings_service(), ) msg = ( f"Updated MCP server name from {old_validation.server_name} " f"to {new_validation.server_name}" ) await logger.adebug(msg) else: msg = ( f"Old MCP server '{old_validation.server_name}' " "not found for this project, skipping rename" ) await logger.adebug(msg) except HTTPException: # Re-raise HTTP validation errors (conflicts, etc.) raise except Exception as e: # noqa: BLE001 # Log but don't fail the project update if MCP server handling fails msg = f"Failed to handle MCP server name update for project rename: {e}" await logger.awarning(msg) if project.description is not None: existing_project.description = project.description if project.parent_id is not None: existing_project.parent_id = project.parent_id session.add(existing_project) await session.flush() await session.refresh(existing_project) # Start MCP Composer if auth changed to OAuth if should_start_mcp_composer: msg = ( f"Auth settings changed to OAuth for project {existing_project.name} ({existing_project.id}), " "starting MCP Composer" ) await logger.adebug(msg) background_tasks.add_task(register_project_with_composer, existing_project) # Stop MCP Composer if auth changed FROM OAuth to something else elif should_stop_mcp_composer: msg = ( f"Auth settings changed from OAuth for project {existing_project.name} ({existing_project.id}), " "stopping MCP Composer" ) await logger.ainfo(msg) # Get the MCP Composer service and stop the project's composer mcp_composer_service: MCPComposerService = cast( MCPComposerService, get_service(ServiceType.MCP_COMPOSER_SERVICE) ) await mcp_composer_service.stop_project_composer(str(existing_project.id)) concat_project_components = project.components + project.flows flows_ids = (await session.exec(select(Flow.id).where(Flow.folder_id == existing_project.id))).all() excluded_flows = list(set(flows_ids) - set(project.flows)) my_collection_project = (await session.exec(select(Folder).where(Folder.name == DEFAULT_FOLDER_NAME))).first() if my_collection_project: update_statement_my_collection = ( update(Flow).where(Flow.id.in_(excluded_flows)).values(folder_id=my_collection_project.id) # type: ignore[attr-defined] ) await session.exec(update_statement_my_collection) if concat_project_components: update_statement_components = ( update(Flow).where(Flow.id.in_(concat_project_components)).values(folder_id=existing_project.id) # type: ignore[attr-defined] ) await session.exec(update_statement_components) # Convert to FolderRead while session is still active to avoid detached instance errors folder_read = FolderRead.model_validate(existing_project, from_attributes=True) except HTTPException: # Re-raise HTTP exceptions (like 409 conflicts) without modification raise except Exception as e: raise HTTPException(status_code=500, detail=str(e)) from e return folder_read @router.delete("/{project_id}", status_code=204) async def delete_project( *, session: DbSession, project_id: UUID, current_user: CurrentActiveUser, ): try: flows = ( await session.exec(select(Flow).where(Flow.folder_id == project_id, Flow.user_id == current_user.id)) ).all() if len(flows) > 0: for flow in flows: await cascade_delete_flow(session, flow.id) project = ( await session.exec(select(Folder).where(Folder.id == project_id, Folder.user_id == current_user.id)) ).first() except Exception as e: raise HTTPException(status_code=500, detail=str(e)) from e if not project: raise HTTPException(status_code=404, detail="Project not found") # Prevent deletion of the Langflow Assistant folder if project.name == ASSISTANT_FOLDER_NAME: msg = f"Cannot delete the '{ASSISTANT_FOLDER_NAME}' folder, that contains pre-built flows." await logger.adebug(msg) raise HTTPException( status_code=403, detail=msg, ) # Check if project has OAuth authentication and stop MCP Composer if needed if project.auth_settings and project.auth_settings.get("auth_type") == "oauth": try: mcp_composer_service: MCPComposerService = cast( MCPComposerService, get_service(ServiceType.MCP_COMPOSER_SERVICE) ) await mcp_composer_service.stop_project_composer(str(project_id)) await logger.adebug(f"Stopped MCP Composer for deleted OAuth project {project.name} ({project_id})") except Exception as e: # noqa: BLE001 # Log but don't fail the deletion if MCP Composer cleanup fails await logger.aerror(f"Failed to stop MCP Composer for deleted project {project_id}: {e}") # Delete corresponding MCP server if auto-add was enabled if get_settings_service().settings.add_projects_to_mcp_servers: try: # Validate MCP server for this specific project validation_result = await validate_mcp_server_for_project( project_id, project.name, current_user, session, get_storage_service(), get_settings_service(), operation="delete", ) # Only delete if server exists and matches this project ID if validation_result.server_exists and validation_result.project_id_matches: await update_server( validation_result.server_name, {}, # Empty config for deletion current_user, session, get_storage_service(), get_settings_service(), delete=True, ) msg = ( f"Deleted MCP server {validation_result.server_name} for " f"deleted project {project.name} ({project_id})" ) await logger.adebug(msg) elif validation_result.server_exists and not validation_result.project_id_matches: msg = ( f"MCP server '{validation_result.server_name}' exists but belongs to different project, " "skipping deletion" ) await logger.adebug(msg) else: msg = f"No MCP server found for deleted project {project.name} ({project_id})" await logger.adebug(msg) except Exception as e: # noqa: BLE001 # Log but don't fail the project deletion if MCP server handling fails await logger.awarning(f"Failed to handle MCP server cleanup for deleted project {project_id}: {e}") try: await session.delete(project) return Response(status_code=status.HTTP_204_NO_CONTENT) except Exception as e: raise HTTPException(status_code=500, detail=str(e)) from e @router.get("/download/{project_id}", status_code=200) async def download_file( *, session: DbSession, project_id: UUID, current_user: CurrentActiveUser, ): """Download all flows from project as a zip file.""" try: query = select(Folder).where(Folder.id == project_id, Folder.user_id == current_user.id) result = await session.exec(query) project = result.first() if not project: raise HTTPException(status_code=404, detail="Project not found") flows_query = select(Flow).where(Flow.folder_id == project_id) flows_result = await session.exec(flows_query) flows = [FlowRead.model_validate(flow, from_attributes=True) for flow in flows_result.all()] if not flows: raise HTTPException(status_code=404, detail="No flows found in project") flows_without_api_keys = [remove_api_keys(flow.model_dump()) for flow in flows] zip_stream = io.BytesIO() with zipfile.ZipFile(zip_stream, "w") as zip_file: for flow in flows_without_api_keys: flow_json = json.dumps(jsonable_encoder(flow)) zip_file.writestr(f"{flow['name']}.json", flow_json.encode("utf-8")) zip_stream.seek(0) current_time = datetime.now(tz=timezone.utc).astimezone().strftime("%Y%m%d_%H%M%S") filename = f"{current_time}_{project.name}_flows.zip" # URL encode filename handle non-ASCII (ex. Cyrillic) encoded_filename = quote(filename) return StreamingResponse( zip_stream, media_type="application/x-zip-compressed", headers={"Content-Disposition": f"attachment; filename*=UTF-8''{encoded_filename}"}, ) except Exception as e: if "No result found" in str(e): raise HTTPException(status_code=404, detail="Project not found") from e raise HTTPException(status_code=500, detail=str(e)) from e @router.post("/upload/", response_model=list[FlowRead], status_code=201) async def upload_file( *, session: DbSession, file: Annotated[UploadFile, File(...)], current_user: CurrentActiveUser, ): """Upload flows from a file.""" contents = await file.read() data = orjson.loads(contents) if not data: raise HTTPException(status_code=400, detail="No flows found in the file") project_name = await generate_unique_folder_name(data["folder_name"], current_user.id, session) data["folder_name"] = project_name project = FolderCreate(name=data["folder_name"], description=data["folder_description"]) new_project = Folder.model_validate(project, from_attributes=True) new_project.id = None new_project.user_id = current_user.id settings_service = get_settings_service() # If AUTO_LOGIN is false, automatically enable API key authentication if not settings_service.auth_settings.AUTO_LOGIN and not new_project.auth_settings: default_auth = {"auth_type": "apikey"} new_project.auth_settings = encrypt_auth_settings(default_auth) await logger.adebug( f"Auto-enabled API key authentication for uploaded project {new_project.name} " f"({new_project.id}) due to AUTO_LOGIN=false" ) session.add(new_project) await session.flush() await session.refresh(new_project) del data["folder_name"] del data["folder_description"] if "flows" in data: flow_list = FlowListCreate(flows=[FlowCreate(**flow) for flow in data["flows"]]) else: raise HTTPException(status_code=400, detail="No flows found in the data") # Now we set the user_id for all flows for flow in flow_list.flows: flow_name = await generate_unique_flow_name(flow.name, current_user.id, session) flow.name = flow_name flow.user_id = current_user.id flow.folder_id = new_project.id return await create_flows(session=session, flow_list=flow_list, current_user=current_user)
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/base/langflow/api/v1/projects.py", "license": "MIT License", "lines": 593, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
langflow-ai/langflow:src/backend/tests/unit/api/v1/test_mcp.py
import asyncio from unittest.mock import AsyncMock, MagicMock, patch from uuid import uuid4 import pytest from fastapi import HTTPException, status from httpx import AsyncClient from langflow.services.auth.utils import get_password_hash from langflow.services.database.models.user import User # Mark all tests in this module as asyncio pytestmark = pytest.mark.asyncio @pytest.fixture def mock_user(): return User( id=uuid4(), username="testuser", password=get_password_hash("testpassword"), is_active=True, is_superuser=False ) @pytest.fixture def mock_mcp_server(): with patch("langflow.api.v1.mcp.server") as mock: # Basic mocking for server attributes potentially accessed during endpoint calls mock.request_context = MagicMock() mock.request_context.meta = MagicMock() mock.request_context.meta.progressToken = "test_token" mock.request_context.session = AsyncMock() mock.create_initialization_options = MagicMock() mock.run = AsyncMock() yield mock @pytest.fixture async def mock_streamable_http_manager(): """Provide a mocked Streamable HTTP manager without starting the real transport.""" manager = AsyncMock() async def fake_handle_request(_scope, _receive, send): await send( { "type": "http.response.start", "status": status.HTTP_200_OK, "headers": [], } ) await send( { "type": "http.response.body", "body": b"", "more_body": False, } ) manager.handle_request = AsyncMock(side_effect=fake_handle_request) with patch("langflow.api.v1.mcp.get_streamable_http_manager", return_value=manager): yield manager @pytest.fixture def mock_sse_transport(): with patch("langflow.api.v1.mcp.sse") as mock: mock.connect_sse = AsyncMock() mock.handle_post_message = AsyncMock() yield mock class _DummyRunContext: """Async context manager that records when StreamableHTTP enters/exits the session.""" def __init__(self, entered_event: asyncio.Event, exited_event: asyncio.Event): self._entered_event = entered_event self._exited_event = exited_event async def __aenter__(self): self._entered_event.set() return self async def __aexit__(self, exc_type, exc, tb): """Mark the context as exited without suppressing exceptions.""" self._exited_event.set() return False class _FailingRunContext: """Async context manager that raises on enter to simulate startup failures.""" def __init__(self, exc: Exception): self._exc = exc async def __aenter__(self): raise self._exc async def __aexit__(self, exc_type, exc, tb): return False # Fixture to mock the current user context variable needed for auth in /sse GET @pytest.fixture(autouse=True) def mock_current_user_ctx(mock_user): with patch("langflow.api.v1.mcp.current_user_ctx") as mock: mock.get.return_value = mock_user mock.set = MagicMock(return_value="dummy_token") # Return a dummy token for reset mock.reset = MagicMock() yield mock # Test the HEAD /sse endpoint (checks server availability) async def test_mcp_sse_head_endpoint(client: AsyncClient): """Test HEAD /sse endpoint returns 200 OK.""" response = await client.head("api/v1/mcp/sse") assert response.status_code == status.HTTP_200_OK # Test the HEAD /sse endpoint without authentication async def test_mcp_sse_head_endpoint_no_auth(client: AsyncClient): """Test HEAD /sse endpoint without authentication returns 200 OK (HEAD requests don't require auth).""" response = await client.head("api/v1/mcp/sse") assert response.status_code == status.HTTP_200_OK async def test_mcp_sse_get_endpoint_invalid_auth(client: AsyncClient): """Test GET /sse endpoint with invalid authentication returns 401.""" headers = {"Authorization": "Bearer invalid_token"} response = await client.get("api/v1/mcp/sse", headers=headers) assert response.status_code == status.HTTP_401_UNAUTHORIZED async def test_mcp_sse_post_endpoint(client: AsyncClient, mock_sse_transport): """Test POST / endpoint for SSE transport succeeds without auth.""" response = await client.post("api/v1/mcp/", json={"type": "test"}) assert response.status_code == status.HTTP_200_OK mock_sse_transport.handle_post_message.assert_called_once() async def test_mcp_post_endpoint_success(client: AsyncClient, logged_in_headers, mock_sse_transport): """Test POST / endpoint successfully handles MCP messages with auth.""" test_message = {"type": "test", "content": "message"} response = await client.post("api/v1/mcp/", headers=logged_in_headers, json=test_message) assert response.status_code == status.HTTP_200_OK mock_sse_transport.handle_post_message.assert_called_once() async def test_mcp_post_endpoint_no_auth(client: AsyncClient): """Test POST / endpoint without authentication returns 400 (current behavior).""" response = await client.post("api/v1/mcp/", json={}) assert response.status_code == status.HTTP_400_BAD_REQUEST async def test_mcp_post_endpoint_invalid_json(client: AsyncClient, logged_in_headers): """Test POST / endpoint with invalid JSON returns 400.""" response = await client.post("api/v1/mcp/", headers=logged_in_headers, content="invalid json") assert response.status_code == status.HTTP_400_BAD_REQUEST async def test_mcp_sse_post_endpoint_disconnect_error(client: AsyncClient, mock_sse_transport): """Test POST / endpoint handles disconnection errors correctly for SSE.""" mock_sse_transport.handle_post_message.side_effect = BrokenPipeError("Simulated disconnect") response = await client.post("api/v1/mcp/", json={"type": "test"}) assert response.status_code == status.HTTP_404_NOT_FOUND mock_sse_transport.handle_post_message.assert_called_once() async def test_mcp_post_endpoint_disconnect_error(client: AsyncClient, logged_in_headers, mock_sse_transport): """Test POST / endpoint handles disconnection errors correctly with auth.""" mock_sse_transport.handle_post_message.side_effect = BrokenPipeError("Simulated disconnect") response = await client.post("api/v1/mcp/", headers=logged_in_headers, json={"type": "test"}) assert response.status_code == status.HTTP_404_NOT_FOUND assert "MCP Server disconnected" in response.json()["detail"] mock_sse_transport.handle_post_message.assert_called_once() async def test_mcp_sse_post_endpoint_server_error(client: AsyncClient, mock_sse_transport): """Test POST / endpoint handles server errors correctly for SSE.""" mock_sse_transport.handle_post_message.side_effect = Exception("Internal server error") response = await client.post("api/v1/mcp/", json={"type": "test"}) assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR async def test_mcp_post_endpoint_server_error(client: AsyncClient, logged_in_headers, mock_sse_transport): """Test POST / endpoint handles server errors correctly with auth.""" mock_sse_transport.handle_post_message.side_effect = Exception("Internal server error") response = await client.post("api/v1/mcp/", headers=logged_in_headers, json={"type": "test"}) assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR assert "Internal server error" in response.json()["detail"] # Streamable HTTP tests async def test_mcp_streamable_post_endpoint( client: AsyncClient, logged_in_headers, mock_streamable_http_manager, ): """Test POST /streamable endpoint successfully handles MCP messages.""" test_message = {"type": "test", "content": "message"} response = await client.post("api/v1/mcp/streamable", headers=logged_in_headers, json=test_message) assert response.status_code == status.HTTP_200_OK mock_streamable_http_manager.handle_request.assert_called_once() async def test_mcp_streamable_post_endpoint_no_auth(client: AsyncClient): """Test POST /streamable endpoint without authentication returns 403 Forbidden.""" response = await client.post("api/v1/mcp/streamable", json={}) assert response.status_code == status.HTTP_403_FORBIDDEN async def test_mcp_streamable_post_endpoint_disconnect_error( client: AsyncClient, logged_in_headers, mock_streamable_http_manager ): """Test POST /streamable endpoint handles disconnection errors correctly.""" mock_streamable_http_manager.handle_request.side_effect = BrokenPipeError("Simulated disconnect") response = await client.post("api/v1/mcp/streamable", headers=logged_in_headers, json={"type": "test"}) assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR mock_streamable_http_manager.handle_request.assert_called_once() async def test_mcp_streamable_post_endpoint_server_error( client: AsyncClient, logged_in_headers, mock_streamable_http_manager ): """Test POST /streamable endpoint handles server errors correctly.""" mock_streamable_http_manager.handle_request.side_effect = Exception("Internal server error") response = await client.post("api/v1/mcp/streamable", headers=logged_in_headers, json={"type": "test"}) assert response.status_code == status.HTTP_500_INTERNAL_SERVER_ERROR # Tests for GET and DELETE on /streamable endpoint async def test_mcp_streamable_get_endpoint( client: AsyncClient, logged_in_headers, mock_streamable_http_manager, ): """Test GET /streamable endpoint successfully handles MCP messages.""" response = await client.get("api/v1/mcp/streamable", headers=logged_in_headers) assert response.status_code == status.HTTP_200_OK mock_streamable_http_manager.handle_request.assert_called_once() async def test_mcp_streamable_delete_endpoint( client: AsyncClient, logged_in_headers, mock_streamable_http_manager, ): """Test DELETE /streamable endpoint successfully handles MCP messages.""" response = await client.delete("api/v1/mcp/streamable", headers=logged_in_headers) assert response.status_code == status.HTTP_200_OK mock_streamable_http_manager.handle_request.assert_called_once() async def test_mcp_streamable_get_endpoint_no_auth(client: AsyncClient): """Test GET /streamable endpoint without authentication returns 403 Forbidden.""" response = await client.get("api/v1/mcp/streamable") assert response.status_code == status.HTTP_403_FORBIDDEN async def test_mcp_streamable_delete_endpoint_no_auth(client: AsyncClient): """Test DELETE /streamable endpoint without authentication returns 403 Forbidden.""" response = await client.delete("api/v1/mcp/streamable") assert response.status_code == status.HTTP_403_FORBIDDEN async def test_streamable_http_start_stop_lifecycle(): """Ensure StreamableHTTP starts and stops its session manager cleanly.""" from langflow.api.v1.mcp import StreamableHTTP entered = asyncio.Event() exited = asyncio.Event() manager_instance = MagicMock() manager_instance.run.return_value = _DummyRunContext(entered, exited) with ( patch("langflow.api.v1.mcp.StreamableHTTPSessionManager", return_value=manager_instance), patch("langflow.api.v1.mcp.logger.adebug", new_callable=AsyncMock), ): streamable_http = StreamableHTTP() await streamable_http.start() assert streamable_http.get_manager() is manager_instance assert entered.is_set(), "session manager never entered run()" await streamable_http.stop() assert exited.is_set(), "session manager never exited run()" async def test_streamable_http_start_failure_keeps_manager_unavailable(): """Ensure failures while starting the session manager propagate and keep manager unavailable.""" from langflow.api.v1.mcp import StreamableHTTP failure = RuntimeError("boom") manager_instance = MagicMock() manager_instance.run.return_value = _FailingRunContext(failure) with ( patch("langflow.api.v1.mcp.StreamableHTTPSessionManager", return_value=manager_instance), patch("langflow.api.v1.mcp.logger.adebug", new_callable=AsyncMock), patch("langflow.api.v1.mcp.logger.aexception", new_callable=AsyncMock), ): streamable_http = StreamableHTTP() with pytest.raises(RuntimeError): await streamable_http.start() with pytest.raises(HTTPException): streamable_http.get_manager() async def test_streamable_http_start_failure_surfaces_exception_once(): """Verify StreamableHTTP.start surfaces the exact exception raised by _start_session_manager.""" from langflow.api.v1.mcp import StreamableHTTP failure = RuntimeError("failed to run session manager") manager_instance = MagicMock() manager_instance.run.return_value = _FailingRunContext(failure) async_logger = AsyncMock() with ( patch("langflow.api.v1.mcp.StreamableHTTPSessionManager", return_value=manager_instance), patch("langflow.api.v1.mcp.logger.aexception", new=async_logger), ): streamable_http = StreamableHTTP() with pytest.raises(RuntimeError) as exc_info: await streamable_http.start() assert str(exc_info.value) == "Error in Streamable HTTP session manager: failed to run session manager" assert exc_info.value.__cause__ is failure assert async_logger.await_count == 1 expected_message = ( "Error starting Streamable HTTP session manager: " "Error in Streamable HTTP session manager: failed to run session manager" ) assert async_logger.await_args_list[0].args[0] == expected_message # Tests for find_validation_error function @pytest.mark.asyncio(loop_scope="session") async def test_find_validation_error_with_pydantic_error(): """Test that find_validation_error correctly identifies ValidationError.""" import pydantic from langflow.api.v1.mcp import find_validation_error # Create a pydantic ValidationError by catching it validation_error = None try: class TestModel(pydantic.BaseModel): required_field: str TestModel() # This will raise ValidationError except pydantic.ValidationError as e: validation_error = e assert validation_error is not None # Wrap it in another exception nested_error = ValueError("Wrapper") nested_error.__cause__ = validation_error found = find_validation_error(nested_error) assert found is validation_error @pytest.mark.asyncio(loop_scope="session") async def test_find_validation_error_without_pydantic_error(): """Test that find_validation_error returns None for non-pydantic errors.""" from langflow.api.v1.mcp import find_validation_error error = ValueError("Test error") assert find_validation_error(error) is None @pytest.mark.asyncio(loop_scope="session") async def test_find_validation_error_with_context(): """Test that find_validation_error searches __context__ chain.""" import pydantic from langflow.api.v1.mcp import find_validation_error # Create a pydantic ValidationError by catching it validation_error = None try: class TestModel(pydantic.BaseModel): required_field: str TestModel() except pydantic.ValidationError as e: validation_error = e assert validation_error is not None # Wrap it using __context__ instead of __cause__ nested_error = ValueError("Wrapper") nested_error.__context__ = validation_error found = find_validation_error(nested_error) assert found is validation_error # Tests for context token management async def test_mcp_sse_context_token_management(mock_current_user_ctx): """Test that context token is properly set and reset.""" # The mock is set up in the fixture, verify it's being called mock_current_user_ctx.set.assert_not_called() # Not called yet mock_current_user_ctx.reset.assert_not_called() # Not called yet # Test for find_validation_error usage in SSE endpoint @pytest.mark.asyncio(loop_scope="session") async def test_mcp_sse_validation_error_logged(): """Test that the find_validation_error function is available for SSE endpoint error handling.""" # This is a simpler test that verifies the find_validation_error function # is available and could be used by the SSE endpoint if needed # The actual usage in a real SSE connection is tested through integration tests import pydantic from langflow.api.v1.mcp import find_validation_error # Verify the function exists and works validation_error = None try: class TestModel(pydantic.BaseModel): required_field: str TestModel() except pydantic.ValidationError as e: validation_error = e assert validation_error is not None wrapped_error = RuntimeError("Wrapper") wrapped_error.__cause__ = validation_error # The function should be able to find the validation error in the chain found = find_validation_error(wrapped_error) assert found is validation_error
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/api/v1/test_mcp.py", "license": "MIT License", "lines": 326, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/tests/unit/api/v1/test_mcp_projects.py
import asyncio import json from contextlib import asynccontextmanager from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock, patch from uuid import uuid4 import pytest from fastapi import HTTPException, status from httpx import AsyncClient from langflow.api.v1.mcp_projects import ( ProjectMCPServer, _args_reference_urls, get_project_mcp_server, get_project_sse, init_mcp_servers, project_mcp_servers, project_sse_transports, ) from langflow.services.auth.utils import create_user_longterm_token, get_password_hash from langflow.services.database.models.flow import Flow from langflow.services.database.models.folder import Folder from langflow.services.database.models.user.model import User from langflow.services.deps import get_settings_service from lfx.services.deps import session_scope from mcp.server.sse import SseServerTransport from sqlmodel import select from tests.unit.utils.mcp import project_session_manager_lifespan # Mark all tests in this module as asyncio pytestmark = pytest.mark.asyncio @pytest.mark.parametrize( ("args", "urls", "expected"), [ (None, ["https://langflow.local/sse"], False), ([], ["https://langflow.local/sse"], False), ([123, {"url": "foo"}], ["https://langflow.local/sse"], False), (["https://langflow.local/sse", 42], ["https://langflow.local/sse"], True), (["alpha", "beta"], [], False), ], ) def test_args_reference_urls_filters_strings_only(args, urls, expected): assert _args_reference_urls(args, urls) is expected def test_args_reference_urls_matches_non_last_string_argument(): args = ["match-me", "other"] urls = ["match-me"] assert _args_reference_urls(args, urls) is True @pytest.fixture def mock_project(active_user): """Fixture to provide a mock project linked to the active user.""" return Folder(id=uuid4(), name="Test Project", user_id=active_user.id) @pytest.fixture def mock_flow(active_user, mock_project): """Fixture to provide a mock flow linked to the active user and project.""" return Flow( id=uuid4(), name="Test Flow", description="Test Description", mcp_enabled=True, action_name="test_action", action_description="Test Action Description", folder_id=mock_project.id, user_id=active_user.id, ) @pytest.fixture def mock_project_mcp_server(): with patch("langflow.api.v1.mcp_projects.ProjectMCPServer") as mock: server_instance = MagicMock() server_instance.server = MagicMock() server_instance.server.name = "test-server" server_instance.server.run = AsyncMock() server_instance.server.create_initialization_options = MagicMock() mock.return_value = server_instance yield server_instance class AsyncContextManagerMock: """Mock class that implements async context manager protocol.""" async def __aenter__(self): return (MagicMock(), MagicMock()) async def __aexit__(self, exc_type, exc_val, exc_tb): # No teardown required for this mock context manager in tests pass @pytest.fixture def mock_sse_transport(): with patch("langflow.api.v1.mcp_projects.SseServerTransport") as mock: transport_instance = MagicMock() # Create an async context manager for connect_sse connect_sse_mock = AsyncContextManagerMock() transport_instance.connect_sse = MagicMock(return_value=connect_sse_mock) transport_instance.handle_post_message = AsyncMock() mock.return_value = transport_instance yield transport_instance @pytest.fixture def mock_streamable_http_manager(): """Mock StreamableHTTPSessionManager used by ProjectMCPServer.""" with patch("langflow.api.v1.mcp_projects.StreamableHTTPSessionManager") as mock_class: manager_instance = MagicMock() # Mock the run() method to return an async context manager async_cm = AsyncContextManagerMock() manager_instance.run = MagicMock(return_value=async_cm) async def _fake_handle_request(scope, receive, send): # noqa: ARG001 await send({"type": "http.response.start", "status": 200, "headers": []}) await send({"type": "http.response.body", "body": b"", "more_body": False}) manager_instance.handle_request = AsyncMock(side_effect=_fake_handle_request) # Make the class constructor return our mocked instance mock_class.return_value = manager_instance yield manager_instance @pytest.fixture(autouse=True) def mock_current_user_ctx(active_user): with patch("langflow.api.v1.mcp_projects.current_user_ctx") as mock: mock.get.return_value = active_user mock.set = MagicMock(return_value="dummy_token") mock.reset = MagicMock() yield mock @pytest.fixture(autouse=True) def mock_current_project_ctx(mock_project): with patch("langflow.api.v1.mcp_projects.current_project_ctx") as mock: mock.get.return_value = mock_project.id mock.set = MagicMock(return_value="dummy_token") mock.reset = MagicMock() yield mock @pytest.fixture async def other_test_user(): """Fixture for creating another test user.""" user_id = uuid4() async with session_scope() as session: user = User( id=user_id, username="other_test_user", password=get_password_hash("testpassword"), is_active=True, is_superuser=False, ) session.add(user) await session.flush() await session.refresh(user) yield user # Clean up async with session_scope() as session: user = await session.get(User, user_id) if user: await session.delete(user) @pytest.fixture async def other_test_project(other_test_user): """Fixture for creating a project for another test user.""" project_id = uuid4() async with session_scope() as session: project = Folder(id=project_id, name="Other Test Project", user_id=other_test_user.id) session.add(project) await session.flush() await session.refresh(project) yield project # Clean up async with session_scope() as session: project = await session.get(Folder, project_id) if project: await session.delete(project) @pytest.fixture(autouse=True) def disable_mcp_composer_by_default(): """Auto-fixture to disable MCP Composer for all tests by default.""" with patch("langflow.api.v1.mcp_projects.get_settings_service") as mock_get_settings: from langflow.services.deps import get_settings_service real_service = get_settings_service() # Create a mock that returns False for mcp_composer_enabled but delegates everything else mock_service = MagicMock() mock_service.settings = MagicMock() mock_service.settings.mcp_composer_enabled = False # Copy any other settings that might be needed mock_service.auth_settings = real_service.auth_settings mock_get_settings.return_value = mock_service yield @pytest.fixture def enable_mcp_composer(): """Fixture to explicitly enable MCP Composer for specific tests.""" with patch("langflow.api.v1.mcp_projects.get_settings_service") as mock_get_settings: from langflow.services.deps import get_settings_service real_service = get_settings_service() mock_service = MagicMock() mock_service.settings = MagicMock() mock_service.settings.mcp_composer_enabled = True # Copy any other settings that might be needed mock_service.auth_settings = real_service.auth_settings mock_get_settings.return_value = mock_service yield True async def test_handle_project_streamable_messages_success( client: AsyncClient, user_test_project, mock_streamable_http_manager, logged_in_headers ): """Test successful handling of project messages over Streamable HTTP.""" response = await client.post( f"api/v1/mcp/project/{user_test_project.id}/streamable", headers=logged_in_headers, json={"type": "test", "content": "message"}, ) assert response.status_code == status.HTTP_200_OK # With StreamableHTTPSessionManager, it calls handle_request, not handle_post_message mock_streamable_http_manager.handle_request.assert_called_once() async def test_handle_project_messages_success( client: AsyncClient, user_test_project, mock_sse_transport, logged_in_headers ): """Test successful handling of project messages over SSE.""" response = await client.post( f"api/v1/mcp/project/{user_test_project.id}", headers=logged_in_headers, json={"type": "test", "content": "message"}, ) assert response.status_code == status.HTTP_200_OK mock_sse_transport.handle_post_message.assert_called_once() async def test_update_project_mcp_settings_invalid_json(client: AsyncClient, user_test_project, logged_in_headers): """Test updating MCP settings with invalid JSON.""" response = await client.patch( f"api/v1/mcp/project/{user_test_project.id}", headers=logged_in_headers, json="invalid" ) assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY @pytest.fixture async def test_flow_for_update(active_user, user_test_project): """Fixture to provide a real flow for testing MCP settings updates.""" flow_id = uuid4() flow_data = { "id": flow_id, "name": "Test Flow For Update", "description": "Test flow that will be updated", "mcp_enabled": True, "action_name": "original_action", "action_description": "Original description", "folder_id": user_test_project.id, "user_id": active_user.id, } # Create the flow in the database async with session_scope() as session: flow = Flow(**flow_data) session.add(flow) await session.flush() await session.refresh(flow) yield flow # Clean up async with session_scope() as session: # Get the flow from the database flow = await session.get(Flow, flow_id) if flow: await session.delete(flow) async def test_update_project_mcp_settings_success( client: AsyncClient, user_test_project, test_flow_for_update, logged_in_headers ): """Test successful update of MCP settings using real database.""" # Create settings for updating the flow json_payload = { "settings": [ { "id": str(test_flow_for_update.id), "action_name": "updated_action", "action_description": "Updated description", "mcp_enabled": False, "name": test_flow_for_update.name, "description": test_flow_for_update.description, } ], "auth_settings": { "auth_type": "none", "api_key": None, "iam_endpoint": None, "username": None, "password": None, "bearer_token": None, }, } # Make the real PATCH request response = await client.patch( f"api/v1/mcp/project/{user_test_project.id}", headers=logged_in_headers, json=json_payload ) # Assert response assert response.status_code == 200 assert "Updated MCP settings for 1 flows" in response.json()["message"] # Verify the flow was actually updated in the database async with session_scope() as session: updated_flow = await session.get(Flow, test_flow_for_update.id) assert updated_flow is not None assert updated_flow.action_name == "updated_action" assert updated_flow.action_description == "Updated description" assert updated_flow.mcp_enabled is False async def test_update_project_mcp_settings_invalid_project(client: AsyncClient, logged_in_headers): """Test accessing an invalid project ID.""" # We're using the GET endpoint since it works correctly and tests the same security constraints # Generate a random UUID that doesn't exist in the database nonexistent_project_id = uuid4() # Try to access the project response = await client.get(f"api/v1/mcp/project/{nonexistent_project_id}/sse", headers=logged_in_headers) # Verify the response assert response.status_code == 404 assert response.json()["detail"] == "Project not found" async def test_update_project_mcp_settings_other_user_project( client: AsyncClient, other_test_project, logged_in_headers ): """Test accessing a project belonging to another user.""" # We're using the GET endpoint since it works correctly and tests the same security constraints # This test disables MCP Composer to test JWT token-based access control # Try to access the other user's project using active_user's credentials response = await client.get(f"api/v1/mcp/project/{other_test_project.id}/sse", headers=logged_in_headers) # Verify the response assert response.status_code == 404 assert response.json()["detail"] == "Project not found" async def test_update_project_mcp_settings_other_user_project_with_composer( client: AsyncClient, other_test_project, logged_in_headers, enable_mcp_composer ): """Test accessing a project belonging to another user when MCP Composer is enabled.""" # When MCP Composer is enabled, JWT tokens are not accepted for MCP endpoints assert enable_mcp_composer # Fixture ensures MCP Composer is enabled # Try to access the other user's project using active_user's JWT credentials response = await client.get(f"api/v1/mcp/project/{other_test_project.id}/sse", headers=logged_in_headers) # Verify the response - should get 401 because JWT tokens aren't accepted assert response.status_code == 401 assert "API key required" in response.json()["detail"] async def test_update_project_mcp_settings_empty_settings(client: AsyncClient, user_test_project, logged_in_headers): """Test updating MCP settings with empty settings list.""" # Use real database objects instead of mocks to avoid the coroutine issue # Empty settings list json_payload = { "settings": [], "auth_settings": { "auth_type": "none", "api_key": None, "iam_endpoint": None, "username": None, "password": None, "bearer_token": None, }, } # Make the request to the actual endpoint response = await client.patch( f"api/v1/mcp/project/{user_test_project.id}", headers=logged_in_headers, json=json_payload ) # Verify response - the real endpoint should handle empty settings correctly assert response.status_code == 200 assert "Updated MCP settings for 0 flows" in response.json()["message"] async def test_user_can_only_access_own_projects(client: AsyncClient, other_test_project, logged_in_headers): """Test that a user can only access their own projects.""" # Try to access the other user's project using first user's credentials response = await client.get(f"api/v1/mcp/project/{other_test_project.id}/sse", headers=logged_in_headers) # Should fail with 404 as first user cannot see second user's project assert response.status_code == 404 assert response.json()["detail"] == "Project not found" async def test_user_data_isolation_with_real_db( client: AsyncClient, logged_in_headers, other_test_user, other_test_project ): """Test that users can only access their own MCP projects using a real database session.""" # Create a flow for the other test user in their project second_flow_id = uuid4() # Use real database session just for flow creation and cleanup async with session_scope() as session: # Create a flow in the other user's project second_flow = Flow( id=second_flow_id, name="Second User Flow", description="This flow belongs to the second user", mcp_enabled=True, action_name="second_user_action", action_description="Second user action description", folder_id=other_test_project.id, user_id=other_test_user.id, ) # Add flow to database session.add(second_flow) try: # Test that first user can't see the project response = await client.get(f"api/v1/mcp/project/{other_test_project.id}/sse", headers=logged_in_headers) # Should fail with 404 assert response.status_code == 404 assert response.json()["detail"] == "Project not found" # First user attempts to update second user's flow settings # Note: We're not testing the PATCH endpoint because it has the coroutine error # Instead, verify permissions via the GET endpoint finally: # Clean up flow async with session_scope() as session: second_flow = await session.get(Flow, second_flow_id) if second_flow: await session.delete(second_flow) @pytest.fixture async def user_test_project(active_user): """Fixture for creating a project for the active user.""" project_id = uuid4() async with session_scope() as session: project = Folder(id=project_id, name="User Test Project", user_id=active_user.id) session.add(project) await session.flush() await session.refresh(project) yield project # Clean up async with session_scope() as session: project = await session.get(Folder, project_id) if project: await session.delete(project) @pytest.fixture async def user_test_flow(active_user, user_test_project): """Fixture for creating a flow for the active user.""" flow_id = uuid4() async with session_scope() as session: flow = Flow( id=flow_id, name="User Test Flow", description="This flow belongs to the active user", mcp_enabled=True, action_name="user_action", action_description="User action description", folder_id=user_test_project.id, user_id=active_user.id, ) session.add(flow) await session.flush() await session.refresh(flow) yield flow # Clean up async with session_scope() as session: flow = await session.get(Flow, flow_id) if flow: await session.delete(flow) async def test_user_can_update_own_flow_mcp_settings( client: AsyncClient, logged_in_headers, user_test_project, user_test_flow ): """Test that a user can update MCP settings for their own flows using real database.""" # User attempts to update their own flow settings json_payload = { "settings": [ { "id": str(user_test_flow.id), "action_name": "updated_user_action", "action_description": "Updated user action description", "mcp_enabled": False, "name": "User Test Flow", "description": "This flow belongs to the active user", } ], "auth_settings": { "auth_type": "none", "api_key": None, "iam_endpoint": None, "username": None, "password": None, "bearer_token": None, }, } # Make the PATCH request to update settings response = await client.patch( f"api/v1/mcp/project/{user_test_project.id}", headers=logged_in_headers, json=json_payload ) # Should succeed as the user owns this project and flow assert response.status_code == 200 assert "Updated MCP settings for 1 flows" in response.json()["message"] # Verify the flow was actually updated in the database async with session_scope() as session: updated_flow = await session.get(Flow, user_test_flow.id) assert updated_flow is not None assert updated_flow.action_name == "updated_user_action" assert updated_flow.action_description == "Updated user action description" assert updated_flow.mcp_enabled is False async def test_update_project_auth_settings_encryption( client: AsyncClient, user_test_project, test_flow_for_update, logged_in_headers ): """Test that sensitive auth_settings fields are encrypted when stored.""" # Create settings with sensitive data json_payload = { "settings": [ { "id": str(test_flow_for_update.id), "action_name": "test_action", "action_description": "Test description", "mcp_enabled": True, "name": test_flow_for_update.name, "description": test_flow_for_update.description, } ], "auth_settings": { "auth_type": "oauth", "oauth_host": "localhost", "oauth_port": "3000", "oauth_server_url": "http://localhost:3000", "oauth_callback_path": "/callback", "oauth_client_id": "test-client-id", "oauth_client_secret": "test-oauth-secret-value-456", "oauth_auth_url": "https://oauth.example.com/auth", "oauth_token_url": "https://oauth.example.com/token", "oauth_mcp_scope": "read write", "oauth_provider_scope": "user:email", }, } # Send the update request response = await client.patch( f"/api/v1/mcp/project/{user_test_project.id}", json=json_payload, headers=logged_in_headers, ) assert response.status_code == 200 # Verify the sensitive data is encrypted in the database async with session_scope() as session: updated_project = await session.get(Folder, user_test_project.id) assert updated_project is not None assert updated_project.auth_settings is not None # Check that sensitive field is encrypted (not plaintext) stored_value = updated_project.auth_settings.get("oauth_client_secret") assert stored_value is not None assert stored_value != "test-oauth-secret-value-456" # Should be encrypted # The encrypted value should be a base64-like string (Fernet token) assert len(stored_value) > 50 # Encrypted values are longer # Now test that the GET endpoint returns the data (SecretStr will be masked) response = await client.get( f"/api/v1/mcp/project/{user_test_project.id}", headers=logged_in_headers, ) assert response.status_code == 200 data = response.json() # SecretStr fields are masked in the response for security assert data["auth_settings"]["oauth_client_secret"] == "**********" # noqa: S105 assert data["auth_settings"]["oauth_client_id"] == "test-client-id" assert data["auth_settings"]["auth_type"] == "oauth" # Verify that decryption is working by checking the actual decrypted value in the backend from langflow.services.auth.mcp_encryption import decrypt_auth_settings async with session_scope() as session: project = await session.get(Folder, user_test_project.id) decrypted_settings = decrypt_auth_settings(project.auth_settings) assert decrypted_settings["oauth_client_secret"] == "test-oauth-secret-value-456" # noqa: S105 async def test_project_sse_creation(user_test_project): """Test that SSE transport and MCP server are correctly created for a project.""" # Test getting an SSE transport for the first time project_id = user_test_project.id project_id_str = str(project_id) # Ensure there's no SSE transport for this project yet if project_id_str in project_sse_transports: del project_sse_transports[project_id_str] # Get an SSE transport sse_transport = get_project_sse(project_id) # Verify the transport was created correctly assert project_id_str in project_sse_transports assert sse_transport is project_sse_transports[project_id_str] assert isinstance(sse_transport, SseServerTransport) # Test getting an MCP server for the first time if project_id_str in project_mcp_servers: del project_mcp_servers[project_id_str] # Get an MCP server mcp_server = get_project_mcp_server(project_id) # Verify the server was created correctly assert project_id_str in project_mcp_servers assert mcp_server is project_mcp_servers[project_id_str] assert isinstance(mcp_server, ProjectMCPServer) assert mcp_server.project_id == project_id assert mcp_server.server.name == f"langflow-mcp-project-{project_id}" # Test that getting the same SSE transport and MCP server again returns the cached instances sse_transport2 = get_project_sse(project_id) mcp_server2 = get_project_mcp_server(project_id) assert sse_transport2 is sse_transport assert mcp_server2 is mcp_server # Yield control to the event loop to satisfy async usage in this test await asyncio.sleep(0) async def test_project_session_manager_lifespan_handles_cleanup(user_test_project, monkeypatch): """Session manager contexts should be cleaned up automatically via shared lifespan stack.""" project_mcp_servers.clear() lifecycle_events: list[str] = [] @asynccontextmanager async def fake_run(): lifecycle_events.append("enter") try: yield finally: lifecycle_events.append("exit") monkeypatch.setattr( "langflow.api.v1.mcp_projects.StreamableHTTPSessionManager.run", lambda self: fake_run(), # noqa: ARG005 ) async with project_session_manager_lifespan(): server = get_project_mcp_server(user_test_project.id) await server.ensure_session_manager_running() assert lifecycle_events == ["enter"] assert lifecycle_events == ["enter", "exit"] def _prepare_install_test_env(monkeypatch, tmp_path, filename="cursor.json"): config_path = tmp_path / filename config_path.parent.mkdir(parents=True, exist_ok=True) monkeypatch.setattr("langflow.api.v1.mcp_projects.get_client_ip", lambda request: "127.0.0.1") # noqa: ARG005 async def fake_get_config_path(client_name): # noqa: ARG001 return config_path monkeypatch.setattr("langflow.api.v1.mcp_projects.get_config_path", fake_get_config_path) monkeypatch.setattr("langflow.api.v1.mcp_projects.platform.system", lambda: "Linux") monkeypatch.setattr("langflow.api.v1.mcp_projects.should_use_mcp_composer", lambda project: False) # noqa: ARG005 async def fake_streamable(project_id): return f"https://langflow.local/api/v1/mcp/project/{project_id}/streamable" async def fake_sse(project_id): return f"https://langflow.local/api/v1/mcp/project/{project_id}/sse" monkeypatch.setattr("langflow.api.v1.mcp_projects.get_project_streamable_http_url", fake_streamable) monkeypatch.setattr("langflow.api.v1.mcp_projects.get_project_sse_url", fake_sse) class DummyAuth: AUTO_LOGIN = True SUPERUSER = True dummy_settings = SimpleNamespace(host="localhost", port=9999, mcp_composer_enabled=False) dummy_service = SimpleNamespace(settings=dummy_settings, auth_settings=DummyAuth()) monkeypatch.setattr("langflow.api.v1.mcp_projects.get_settings_service", lambda: dummy_service) return config_path async def test_install_mcp_config_defaults_to_sse_transport( client: AsyncClient, user_test_project, logged_in_headers, tmp_path, monkeypatch, ): config_path = _prepare_install_test_env(monkeypatch, tmp_path, "cursor_sse.json") response = await client.post( f"/api/v1/mcp/project/{user_test_project.id}/install", headers=logged_in_headers, json={"client": "cursor"}, ) assert response.status_code == status.HTTP_200_OK installed_config = json.loads(config_path.read_text()) server_name = "lf-user_test_project" args = installed_config["mcpServers"][server_name]["args"] assert "--transport" not in args assert args[-1].endswith("/sse") async def test_install_mcp_config_streamable_transport( client: AsyncClient, user_test_project, logged_in_headers, tmp_path, monkeypatch, ): config_path = _prepare_install_test_env(monkeypatch, tmp_path, "cursor_streamable.json") response = await client.post( f"/api/v1/mcp/project/{user_test_project.id}/install", headers=logged_in_headers, json={"client": "cursor", "transport": "streamablehttp"}, ) assert response.status_code == status.HTTP_200_OK installed_config = json.loads(config_path.read_text()) server_name = "lf-user_test_project" args = installed_config["mcpServers"][server_name]["args"] assert "--transport" in args assert "streamablehttp" in args assert args[-1].endswith("/streamable") async def test_init_mcp_servers(user_test_project, other_test_project): """Test the initialization of MCP servers for all projects.""" # Clear existing caches project_sse_transports.clear() project_mcp_servers.clear() # Test the initialization function await init_mcp_servers() # Verify that both test projects have SSE transports and MCP servers initialized project1_id = str(user_test_project.id) project2_id = str(other_test_project.id) # Both projects should have SSE transports created assert project1_id in project_sse_transports assert project2_id in project_sse_transports # Both projects should have MCP servers created assert project1_id in project_mcp_servers assert project2_id in project_mcp_servers # Verify the correct configuration assert isinstance(project_sse_transports[project1_id], SseServerTransport) assert isinstance(project_sse_transports[project2_id], SseServerTransport) assert isinstance(project_mcp_servers[project1_id], ProjectMCPServer) assert isinstance(project_mcp_servers[project2_id], ProjectMCPServer) assert project_mcp_servers[project1_id].project_id == user_test_project.id assert project_mcp_servers[project2_id].project_id == other_test_project.id async def test_init_mcp_servers_error_handling(): """Test that init_mcp_servers handles SSE errors correctly and continues initialization.""" # Clear existing caches project_sse_transports.clear() project_mcp_servers.clear() # Create a mock to simulate an error when initializing one project original_get_project_sse = get_project_sse def mock_get_project_sse(project_id): # Raise an exception for the first project only if not project_sse_transports: # Only for the first project msg = "Test error for project SSE creation" raise ValueError(msg) return original_get_project_sse(project_id) # Apply the patch with patch("langflow.api.v1.mcp_projects.get_project_sse", side_effect=mock_get_project_sse): # This should not raise any exception, as the error should be caught await init_mcp_servers() async def test_init_mcp_servers_error_handling_streamable(): """Test that init_mcp_servers handles MCP server errors correctly and continues initialization.""" # Clear existing caches project_mcp_servers.clear() # Create a mock to simulate an error when initializing one project original_get_project_mcp_server = get_project_mcp_server def mock_get_project_mcp_server(project_id): # Raise an exception for the first project only if not project_mcp_servers: # Only for the first project msg = "Test error for project MCP server creation" raise ValueError(msg) return original_get_project_mcp_server(project_id) # Apply the patch with patch("langflow.api.v1.mcp_projects.get_project_mcp_server", side_effect=mock_get_project_mcp_server): # This should not raise any exception, as the error should be caught await init_mcp_servers() async def test_list_project_tools_with_mcp_enabled_filter( client: AsyncClient, user_test_project, active_user, logged_in_headers ): """Test that the list_project_tools endpoint correctly filters by mcp_enabled parameter.""" # Create two flows: one with mcp_enabled=True and one with mcp_enabled=False enabled_flow_id = uuid4() disabled_flow_id = uuid4() async with session_scope() as session: # Create an MCP-enabled flow enabled_flow = Flow( id=enabled_flow_id, name="Enabled Flow", description="This flow is MCP enabled", mcp_enabled=True, action_name="enabled_action", action_description="Enabled action description", folder_id=user_test_project.id, user_id=active_user.id, ) # Create an MCP-disabled flow disabled_flow = Flow( id=disabled_flow_id, name="Disabled Flow", description="This flow is MCP disabled", mcp_enabled=False, action_name="disabled_action", action_description="Disabled action description", folder_id=user_test_project.id, user_id=active_user.id, ) session.add(enabled_flow) session.add(disabled_flow) await session.flush() try: # Test 1: With mcp_enabled=True (default), should only return enabled flows response = await client.get( f"/api/v1/mcp/project/{user_test_project.id}", headers=logged_in_headers, ) assert response.status_code == 200 data = response.json() assert "tools" in data tools = data["tools"] # Should only include the enabled flow assert len(tools) == 1 assert tools[0]["name"] == "Enabled Flow" assert tools[0]["action_name"] == "enabled_action" # Test 2: With mcp_enabled=True explicitly, should only return enabled flows response = await client.get( f"/api/v1/mcp/project/{user_test_project.id}?mcp_enabled=true", headers=logged_in_headers, ) assert response.status_code == 200 data = response.json() tools = data["tools"] assert len(tools) == 1 assert tools[0]["name"] == "Enabled Flow" # Test 3: With mcp_enabled=False, should return all flows response = await client.get( f"/api/v1/mcp/project/{user_test_project.id}?mcp_enabled=false", headers=logged_in_headers, ) assert response.status_code == 200 data = response.json() tools = data["tools"] # Should include both flows assert len(tools) == 2 flow_names = {tool["name"] for tool in tools} assert "Enabled Flow" in flow_names assert "Disabled Flow" in flow_names finally: # Clean up flows async with session_scope() as session: enabled_flow = await session.get(Flow, enabled_flow_id) if enabled_flow: await session.delete(enabled_flow) disabled_flow = await session.get(Flow, disabled_flow_id) if disabled_flow: await session.delete(disabled_flow) async def test_list_project_tools_response_structure(client: AsyncClient, user_test_project, logged_in_headers): """Test that the list_project_tools endpoint returns the correct MCPProjectResponse structure.""" response = await client.get( f"/api/v1/mcp/project/{user_test_project.id}", headers=logged_in_headers, ) assert response.status_code == 200 data = response.json() # Verify response structure matches MCPProjectResponse assert "tools" in data assert "auth_settings" in data assert isinstance(data["tools"], list) # Verify tool structure if len(data["tools"]) > 0: tool = data["tools"][0] assert "id" in tool assert "name" in tool assert "description" in tool assert "action_name" in tool assert "action_description" in tool assert "mcp_enabled" in tool @pytest.mark.asyncio async def test_mcp_longterm_token_fails_without_superuser(): """When AUTO_LOGIN is false and no superuser exists, creating a long-term token should raise 400. This simulates a clean DB with AUTO_LOGIN disabled and without provisioning a superuser. """ settings_service = get_settings_service() settings_service.auth_settings.AUTO_LOGIN = False # Ensure no superuser exists in DB async with session_scope() as session: result = await session.exec(select(User).where(User.is_superuser == True)) # noqa: E712 users = result.all() for user in users: await session.delete(user) # Now attempt to create long-term token -> expect HTTPException 400 async with session_scope() as session: with pytest.raises(HTTPException, match="Auto login required to create a long-term token"): await create_user_longterm_token(session)
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/api/v1/test_mcp_projects.py", "license": "MIT License", "lines": 802, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/tests/unit/api/v1/test_projects.py
import io import json import zipfile from unittest.mock import MagicMock, patch from uuid import uuid4 import pytest from fastapi import status from httpx import AsyncClient from langflow.initial_setup.constants import STARTER_FOLDER_NAME from langflow.services.database.models.flow.model import Flow, FlowCreate from langflow.services.deps import session_scope CYRILLIC_NAME = "Новый проект" CYRILLIC_DESC = "Описание проекта с кириллицей" # noqa: RUF001 @pytest.fixture def basic_case(): return { "name": "New Project", "description": "", "flows_list": [], "components_list": [], } async def test_create_project(client: AsyncClient, logged_in_headers, basic_case): response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) result = response.json() assert response.status_code == status.HTTP_201_CREATED assert isinstance(result, dict), "The result must be a dictionary" assert "name" in result, "The dictionary must contain a key called 'name'" assert "description" in result, "The dictionary must contain a key called 'description'" assert "id" in result, "The dictionary must contain a key called 'id'" assert "parent_id" in result, "The dictionary must contain a key called 'parent_id'" async def test_read_projects(client: AsyncClient, logged_in_headers): response = await client.get("api/v1/projects/", headers=logged_in_headers) result = response.json() assert response.status_code == status.HTTP_200_OK assert isinstance(result, list), "The result must be a list" assert len(result) > 0, "The list must not be empty" async def test_read_project(client: AsyncClient, logged_in_headers, basic_case): # Create a project first response_ = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) id_ = response_.json()["id"] # Get the project response = await client.get(f"api/v1/projects/{id_}", headers=logged_in_headers) result = response.json() # The response structure may be different depending on whether pagination is enabled if isinstance(result, dict) and "folder" in result: # Handle paginated project response folder_data = result["folder"] assert response.status_code == status.HTTP_200_OK assert isinstance(folder_data, dict), "The folder data must be a dictionary" assert "name" in folder_data, "The dictionary must contain a key called 'name'" assert "description" in folder_data, "The dictionary must contain a key called 'description'" assert "id" in folder_data, "The dictionary must contain a key called 'id'" elif isinstance(result, dict) and "project" in result: # Handle paginated project response project_data = result["project"] assert response.status_code == status.HTTP_200_OK assert isinstance(project_data, dict), "The project data must be a dictionary" assert "name" in project_data, "The dictionary must contain a key called 'name'" assert "description" in project_data, "The dictionary must contain a key called 'description'" assert "id" in project_data, "The dictionary must contain a key called 'id'" else: # Handle direct project response assert response.status_code == status.HTTP_200_OK assert isinstance(result, dict), "The result must be a dictionary" assert "name" in result, "The dictionary must contain a key called 'name'" assert "description" in result, "The dictionary must contain a key called 'description'" assert "id" in result, "The dictionary must contain a key called 'id'" async def test_update_project(client: AsyncClient, logged_in_headers, basic_case): update_case = basic_case.copy() update_case["name"] = "Updated Project" # Create a project first response_ = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) id_ = response_.json()["id"] # Update the project response = await client.patch(f"api/v1/projects/{id_}", json=update_case, headers=logged_in_headers) result = response.json() assert response.status_code == status.HTTP_200_OK assert isinstance(result, dict), "The result must be a dictionary" assert "name" in result, "The dictionary must contain a key called 'name'" assert "description" in result, "The dictionary must contain a key called 'description'" assert "id" in result, "The dictionary must contain a key called 'id'" assert "parent_id" in result, "The dictionary must contain a key called 'parent_id'" async def test_create_project_validation_error(client: AsyncClient, logged_in_headers, basic_case): invalid_case = basic_case.copy() invalid_case.pop("name") response = await client.post("api/v1/projects/", json=invalid_case, headers=logged_in_headers) assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY async def test_delete_project_then_404(client: AsyncClient, logged_in_headers, basic_case): create_resp = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) proj_id = create_resp.json()["id"] del_resp = await client.delete(f"api/v1/projects/{proj_id}", headers=logged_in_headers) assert del_resp.status_code == status.HTTP_204_NO_CONTENT get_resp = await client.get(f"api/v1/projects/{proj_id}", headers=logged_in_headers) assert get_resp.status_code == status.HTTP_404_NOT_FOUND async def test_read_project_invalid_id_format(client: AsyncClient, logged_in_headers): bad_id = "not-a-uuid" response = await client.get(f"api/v1/projects/{bad_id}", headers=logged_in_headers) assert response.status_code in (status.HTTP_422_UNPROCESSABLE_ENTITY, status.HTTP_400_BAD_REQUEST) async def test_read_projects_pagination(client: AsyncClient, logged_in_headers): response = await client.get("api/v1/projects/?limit=1&offset=0", headers=logged_in_headers) assert response.status_code == status.HTTP_200_OK result = response.json() if isinstance(result, list): assert len(result) <= 1 else: assert "items" in result assert result.get("limit") == 1 async def test_read_projects_empty(client: AsyncClient, logged_in_headers): # Ensure DB is clean by fetching with a random header that forces each test transactional isolation random_headers = {**logged_in_headers, "X-Transaction-ID": str(uuid4())} response = await client.get("api/v1/projects/", headers=random_headers) if response.json(): pytest.skip("Pre-existing projects found; skipping empty list assertion") assert response.status_code == status.HTTP_200_OK assert response.json() == [] async def test_create_and_read_project_cyrillic(client: AsyncClient, logged_in_headers): """Ensure that the API correctly handles non-ASCII (Cyrillic) characters during project creation and retrieval.""" payload = { "name": CYRILLIC_NAME, "description": CYRILLIC_DESC, "flows_list": [], "components_list": [], } # Create the project with Cyrillic characters create_resp = await client.post("api/v1/projects/", json=payload, headers=logged_in_headers) assert create_resp.status_code == status.HTTP_201_CREATED created = create_resp.json() assert created["name"] == CYRILLIC_NAME assert created["description"] == CYRILLIC_DESC proj_id = created["id"] # Fetch the project back to verify round-trip UTF-8 integrity get_resp = await client.get(f"api/v1/projects/{proj_id}", headers=logged_in_headers) assert get_resp.status_code == status.HTTP_200_OK fetched = get_resp.json() # Handle potential pagination/envelope variations already seen in other tests if isinstance(fetched, dict) and "folder" in fetched: fetched = fetched["folder"] elif isinstance(fetched, dict) and "project" in fetched: fetched = fetched["project"] assert fetched["name"] == CYRILLIC_NAME assert fetched["description"] == CYRILLIC_DESC async def test_update_project_preserves_flows(client: AsyncClient, logged_in_headers): """Test that renaming a project preserves all associated flows (regression test for flow loss bug).""" # Create a project project_payload = { "name": "Project with Flows", "description": "Testing flow preservation", "flows_list": [], "components_list": [], } create_resp = await client.post("api/v1/projects/", json=project_payload, headers=logged_in_headers) assert create_resp.status_code == status.HTTP_201_CREATED project = create_resp.json() project_id = project["id"] # Create flows in the project flow1_payload = { "name": "Test Flow 1", "description": "First test flow", "folder_id": project_id, "data": {"nodes": [], "edges": []}, "is_component": False, } flow2_payload = { "name": "Test Flow 2", "description": "Second test flow", "folder_id": project_id, "data": {"nodes": [], "edges": []}, "is_component": False, } flow1_resp = await client.post("api/v1/flows/", json=flow1_payload, headers=logged_in_headers) flow2_resp = await client.post("api/v1/flows/", json=flow2_payload, headers=logged_in_headers) assert flow1_resp.status_code == status.HTTP_201_CREATED assert flow2_resp.status_code == status.HTTP_201_CREATED flow1_id = flow1_resp.json()["id"] flow2_id = flow2_resp.json()["id"] # Get project to verify flows are associated get_resp = await client.get(f"api/v1/projects/{project_id}", headers=logged_in_headers) assert get_resp.status_code == status.HTTP_200_OK project_data = get_resp.json() # Current behavior: all flows (including components) are in the flows field flows_before = project_data.get("flows", []) # Filter only actual flows (not components) actual_flows_before = [f for f in flows_before if not f.get("is_component", False)] assert len(actual_flows_before) == 2 flow_ids_before = [f["id"] for f in actual_flows_before] assert str(flow1_id) in flow_ids_before assert str(flow2_id) in flow_ids_before # Update project name (the bug scenario) update_payload = {"name": "Renamed Project with Flows", "description": "Testing flow preservation after rename"} update_resp = await client.patch(f"api/v1/projects/{project_id}", json=update_payload, headers=logged_in_headers) assert update_resp.status_code == status.HTTP_200_OK # Verify project was renamed updated_project = update_resp.json() assert updated_project["name"] == "Renamed Project with Flows" # Critical test: Verify flows are still associated after rename get_after_resp = await client.get(f"api/v1/projects/{project_id}", headers=logged_in_headers) assert get_after_resp.status_code == status.HTTP_200_OK project_after = get_after_resp.json() flows_after = project_after.get("flows", []) actual_flows_after = [f for f in flows_after if not f.get("is_component", False)] # This was the bug: flows were being lost after project rename assert len(actual_flows_after) == 2, f"Expected 2 flows after rename, got {len(actual_flows_after)}. Flows lost!" flow_ids_after = [f["id"] for f in actual_flows_after] assert str(flow1_id) in flow_ids_after, "Flow 1 was lost after project rename!" assert str(flow2_id) in flow_ids_after, "Flow 2 was lost after project rename!" # Verify individual flows still exist and are accessible flow1_get_resp = await client.get(f"api/v1/flows/{flow1_id}", headers=logged_in_headers) flow2_get_resp = await client.get(f"api/v1/flows/{flow2_id}", headers=logged_in_headers) assert flow1_get_resp.status_code == status.HTTP_200_OK assert flow2_get_resp.status_code == status.HTTP_200_OK # Verify flows still reference the correct project flow1_data = flow1_get_resp.json() flow2_data = flow2_get_resp.json() assert str(flow1_data["folder_id"]) == str(project_id) assert str(flow2_data["folder_id"]) == str(project_id) async def test_update_project_preserves_components(client: AsyncClient, logged_in_headers): """Test that renaming a project preserves all associated components.""" # Create a project project_payload = { "name": "Project with Components", "description": "Testing component preservation", "flows_list": [], "components_list": [], } create_resp = await client.post("api/v1/projects/", json=project_payload, headers=logged_in_headers) assert create_resp.status_code == status.HTTP_201_CREATED project = create_resp.json() project_id = project["id"] # Create components in the project comp1_payload = { "name": "Test Component 1", "description": "First test component", "folder_id": project_id, "data": {"nodes": [], "edges": []}, "is_component": True, # This makes it a component } comp2_payload = { "name": "Test Component 2", "description": "Second test component", "folder_id": project_id, "data": {"nodes": [], "edges": []}, "is_component": True, # This makes it a component } comp1_resp = await client.post("api/v1/flows/", json=comp1_payload, headers=logged_in_headers) comp2_resp = await client.post("api/v1/flows/", json=comp2_payload, headers=logged_in_headers) assert comp1_resp.status_code == status.HTTP_201_CREATED assert comp2_resp.status_code == status.HTTP_201_CREATED comp1_id = comp1_resp.json()["id"] comp2_id = comp2_resp.json()["id"] # Get project to verify components are associated get_resp = await client.get(f"api/v1/projects/{project_id}", headers=logged_in_headers) assert get_resp.status_code == status.HTTP_200_OK project_data = get_resp.json() # Current behavior: all flows (including components) are in the flows field flows_before = project_data.get("flows", []) # Filter only components components_before = [f for f in flows_before if f.get("is_component", False)] assert len(components_before) == 2 component_ids_before = [c["id"] for c in components_before] assert str(comp1_id) in component_ids_before assert str(comp2_id) in component_ids_before # Update project name update_payload = {"name": "Renamed Project with Components"} update_resp = await client.patch(f"api/v1/projects/{project_id}", json=update_payload, headers=logged_in_headers) assert update_resp.status_code == status.HTTP_200_OK # Verify components are still associated after rename get_after_resp = await client.get(f"api/v1/projects/{project_id}", headers=logged_in_headers) assert get_after_resp.status_code == status.HTTP_200_OK project_after = get_after_resp.json() flows_after = project_after.get("flows", []) components_after = [f for f in flows_after if f.get("is_component", False)] assert len(components_after) == 2, ( f"Expected 2 components after rename, got {len(components_after)}. Components lost!" ) component_ids_after = [c["id"] for c in components_after] assert str(comp1_id) in component_ids_after, "Component 1 was lost after project rename!" assert str(comp2_id) in component_ids_after, "Component 2 was lost after project rename!" async def test_update_project_preserves_mixed_flows_and_components(client: AsyncClient, logged_in_headers): """Test that renaming a project preserves both flows and components correctly.""" # Create a project project_payload = { "name": "Mixed Project", "description": "Testing mixed flows and components preservation", "flows_list": [], "components_list": [], } create_resp = await client.post("api/v1/projects/", json=project_payload, headers=logged_in_headers) assert create_resp.status_code == status.HTTP_201_CREATED project = create_resp.json() project_id = project["id"] # Create flows and components flow_payload = { "name": "Regular Flow", "description": "A regular flow", "folder_id": project_id, "data": {"nodes": [], "edges": []}, "is_component": False, } component_payload = { "name": "Custom Component", "description": "A custom component", "folder_id": project_id, "data": {"nodes": [], "edges": []}, "is_component": True, } flow_resp = await client.post("api/v1/flows/", json=flow_payload, headers=logged_in_headers) comp_resp = await client.post("api/v1/flows/", json=component_payload, headers=logged_in_headers) assert flow_resp.status_code == status.HTTP_201_CREATED assert comp_resp.status_code == status.HTTP_201_CREATED flow_id = flow_resp.json()["id"] comp_id = comp_resp.json()["id"] # Verify initial state get_resp = await client.get(f"api/v1/projects/{project_id}", headers=logged_in_headers) project_data = get_resp.json() flows_before = project_data.get("flows", []) actual_flows_before = [f for f in flows_before if not f.get("is_component", False)] components_before = [f for f in flows_before if f.get("is_component", False)] assert len(actual_flows_before) == 1 assert len(components_before) == 1 # Update project update_payload = {"name": "Renamed Mixed Project"} update_resp = await client.patch(f"api/v1/projects/{project_id}", json=update_payload, headers=logged_in_headers) assert update_resp.status_code == status.HTTP_200_OK # Verify both flows and components preserved get_after_resp = await client.get(f"api/v1/projects/{project_id}", headers=logged_in_headers) project_after = get_after_resp.json() flows_after = project_after.get("flows", []) actual_flows_after = [f for f in flows_after if not f.get("is_component", False)] components_after = [f for f in flows_after if f.get("is_component", False)] assert len(actual_flows_after) == 1, "Flow was lost after project rename!" assert len(components_after) == 1, "Component was lost after project rename!" flow_id_after = actual_flows_after[0]["id"] comp_id_after = components_after[0]["id"] assert str(flow_id) == flow_id_after assert str(comp_id) == comp_id_after # MCP-related tests class TestProjectMCPIntegration: """Test MCP integration features in projects API.""" @pytest.fixture def mock_mcp_settings_enabled(self): """Mock settings with MCP auto-add enabled.""" with patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings: mock_service = MagicMock() mock_service.settings.add_projects_to_mcp_servers = True mock_service.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_service yield mock_service @pytest.fixture def mock_mcp_settings_disabled(self): """Mock settings with MCP auto-add disabled.""" with patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings: mock_service = MagicMock() mock_service.settings.add_projects_to_mcp_servers = False mock_service.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_service yield mock_service async def test_create_project_with_mcp_auto_add_disabled( self, client: AsyncClient, logged_in_headers, basic_case, mock_mcp_settings_disabled, # noqa: ARG002 ): """Test project creation when MCP auto-add is disabled.""" response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) result = response.json() assert response.status_code == status.HTTP_201_CREATED assert "name" in result assert result["name"] == basic_case["name"] async def test_create_project_with_mcp_auto_add_enabled_success( self, client: AsyncClient, logged_in_headers, basic_case, mock_mcp_settings_enabled, # noqa: ARG002 ): """Test successful project creation with MCP server auto-add.""" with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.get_project_streamable_http_url") as mock_streamable_url, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate, patch("langflow.api.v1.projects.update_server") as mock_update_server, patch("langflow.api.v1.projects.create_api_key") as mock_create_api_key, patch("langflow.api.v1.projects.get_storage_service") as mock_storage, ): # Setup mocks mock_streamable_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/streamable" mock_storage.return_value = MagicMock() # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings # Mock API key creation mock_api_key_response = MagicMock() mock_api_key_response.api_key = "test-api-key-123" # pragma: allowlist secret mock_create_api_key.return_value = mock_api_key_response # Mock validation - no conflict mock_validation_result = MagicMock() mock_validation_result.has_conflict = False mock_validation_result.should_skip = False mock_validation_result.server_name = "lf-new-project" mock_validate.return_value = mock_validation_result mock_update_server.return_value = None response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) result = response.json() assert response.status_code == status.HTTP_201_CREATED assert "name" in result # Verify MCP server creation was attempted mock_validate.assert_called_once() mock_update_server.assert_called_once() async def test_create_project_with_mcp_auto_add_enabled_success_legacy_sse( self, client: AsyncClient, logged_in_headers, basic_case, mock_mcp_settings_enabled, # noqa: ARG002 ): """Legacy SSE test for project creation with MCP server auto-add.""" with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.get_project_sse_url") as mock_sse_url, patch("langflow.api.v1.projects.get_project_streamable_http_url") as mock_streamable_url, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate, patch("langflow.api.v1.projects.update_server") as mock_update_server, patch("langflow.api.v1.projects.create_api_key") as mock_create_api_key, patch("langflow.api.v1.projects.get_storage_service") as mock_storage, ): # Setup mocks mock_sse_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/sse" mock_streamable_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/streamable" mock_storage.return_value = MagicMock() # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings # Mock API key creation mock_api_key_response = MagicMock() mock_api_key_response.api_key = "test-api-key-123" # pragma: allowlist secret mock_create_api_key.return_value = mock_api_key_response # Mock validation - no conflict mock_validation_result = MagicMock() mock_validation_result.has_conflict = False mock_validation_result.should_skip = False mock_validation_result.server_name = "lf-new-project" mock_validate.return_value = mock_validation_result mock_update_server.return_value = None response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) result = response.json() assert response.status_code == status.HTTP_201_CREATED assert "name" in result # Verify MCP server creation was attempted mock_validate.assert_called_once() mock_update_server.assert_called_once() async def test_create_project_with_mcp_server_conflict( self, client: AsyncClient, logged_in_headers, basic_case, mock_mcp_settings_enabled, # noqa: ARG002 ): """Test project creation failure due to MCP server name conflict.""" with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.get_project_streamable_http_url") as mock_streamable_url, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate, patch("langflow.api.v1.projects.get_storage_service") as mock_storage, ): # Setup mocks mock_streamable_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/streamable" mock_storage.return_value = MagicMock() # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings # Mock validation - has conflict mock_validation_result = MagicMock() mock_validation_result.has_conflict = True mock_validation_result.conflict_message = ( "MCP server name conflict: 'lf-new-project' already exists " "for a different project. Cannot create MCP server for project " "'New Project' (ID: test-project-id)" ) mock_validate.return_value = mock_validation_result # The validation function should raise the HTTPException during project creation response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) assert response.status_code == status.HTTP_409_CONFLICT response_data = response.json() assert "detail" in response_data assert mock_validation_result.conflict_message == response_data["detail"] # Verify validation was called with correct parameters mock_validate.assert_called_once() async def test_create_project_with_mcp_server_conflict_legacy_sse( self, client: AsyncClient, logged_in_headers, basic_case, mock_mcp_settings_enabled, # noqa: ARG002 ): """Legacy SSE test verifying project creation failure due to MCP server name conflict.""" with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.get_project_sse_url") as mock_sse_url, patch("langflow.api.v1.projects.get_project_streamable_http_url") as mock_streamable_url, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate, patch("langflow.api.v1.projects.get_storage_service") as mock_storage, ): # Setup mocks mock_sse_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/sse" mock_streamable_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/streamable" mock_storage.return_value = MagicMock() # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings # Mock validation - has conflict mock_validation_result = MagicMock() mock_validation_result.has_conflict = True mock_validation_result.conflict_message = ( "MCP server name conflict: 'lf-new-project' already exists " "for a different project. Cannot create MCP server for project " "'New Project' (ID: test-project-id)" ) mock_validate.return_value = mock_validation_result response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) assert response.status_code == status.HTTP_409_CONFLICT response_data = response.json() assert "detail" in response_data assert mock_validation_result.conflict_message == response_data["detail"] # Verify validation was called with correct parameters mock_validate.assert_called_once() async def test_create_project_oauth_not_implemented( self, client: AsyncClient, logged_in_headers, basic_case, mock_mcp_settings_enabled, # noqa: ARG002 ): """Test project creation with OAuth auth type raises NotImplementedError.""" oauth_case = basic_case.copy() oauth_case["auth_settings"] = {"auth_type": "oauth"} with ( patch("langflow.api.v1.projects.get_project_streamable_http_url") as mock_streamable_url, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate, patch("langflow.api.v1.projects.get_storage_service") as mock_storage, ): # Setup mocks to trigger OAuth path mock_streamable_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/streamable" mock_storage.return_value = MagicMock() # Mock validation - no conflict but OAuth case will raise NotImplementedError mock_validation_result = MagicMock() mock_validation_result.has_conflict = False mock_validation_result.should_skip = False mock_validation_result.server_name = "lf-new-project" mock_validate.return_value = mock_validation_result response = await client.post("api/v1/projects/", json=oauth_case, headers=logged_in_headers) # Should still create project but log error about OAuth assert response.status_code == status.HTTP_201_CREATED async def test_create_project_oauth_not_implemented_legacy_sse( self, client: AsyncClient, logged_in_headers, basic_case, mock_mcp_settings_enabled, # noqa: ARG002 ): """Legacy SSE test verifying OAuth paths raise NotImplementedError during project creation.""" oauth_case = basic_case.copy() oauth_case["auth_settings"] = {"auth_type": "oauth"} with ( patch("langflow.api.v1.projects.get_project_sse_url") as mock_sse_url, patch("langflow.api.v1.projects.get_project_streamable_http_url") as mock_streamable_url, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate, patch("langflow.api.v1.projects.get_storage_service") as mock_storage, ): # Setup mocks to trigger OAuth path mock_sse_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/sse" mock_streamable_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/streamable" mock_storage.return_value = MagicMock() # Mock validation - no conflict but OAuth case will raise NotImplementedError mock_validation_result = MagicMock() mock_validation_result.has_conflict = False mock_validation_result.should_skip = False mock_validation_result.server_name = "lf-new-project" mock_validate.return_value = mock_validation_result response = await client.post("api/v1/projects/", json=oauth_case, headers=logged_in_headers) # Should still create project but log error about OAuth assert response.status_code == status.HTTP_201_CREATED async def test_update_project_name_with_mcp_server_update( self, client: AsyncClient, logged_in_headers, basic_case, mock_mcp_settings_enabled, # noqa: ARG002 ): """Test project rename with MCP server name update.""" # First create a project with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.get_project_streamable_http_url"), patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate_create, patch("langflow.api.v1.projects.update_server"), patch("langflow.api.v1.projects.create_api_key"), patch("langflow.api.v1.projects.get_storage_service"), ): # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings mock_validation_create = MagicMock() mock_validation_create.has_conflict = False mock_validation_create.should_skip = False mock_validation_create.server_name = "lf-new-project" mock_validate_create.return_value = mock_validation_create create_response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) project_id = create_response.json()["id"] # Now update the project name update_case = {"name": "Updated Project Name", "description": "Updated description"} with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate, patch("langflow.api.v1.projects.update_server") as mock_update_server, patch("langflow.api.v1.projects.get_storage_service") as mock_storage, ): # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings mock_storage.return_value = MagicMock() # Mock old server validation mock_old_validation = MagicMock() mock_old_validation.server_exists = True mock_old_validation.project_id_matches = True mock_old_validation.server_name = "lf-new-project" mock_old_validation.existing_config = {"command": "uvx", "args": ["mcp-proxy", "old-url"]} # Mock new server validation mock_new_validation = MagicMock() mock_new_validation.has_conflict = False mock_new_validation.server_name = "lf-updated-project-name" mock_validate.side_effect = [mock_old_validation, mock_new_validation] response = await client.patch(f"api/v1/projects/{project_id}", json=update_case, headers=logged_in_headers) assert response.status_code == status.HTTP_200_OK result = response.json() assert result["name"] == "Updated Project Name" # Should validate both old and new server names assert mock_validate.call_count == 2 # Should update server twice (delete old, create new) assert mock_update_server.call_count == 2 async def test_update_project_name_with_mcp_server_update_legacy_sse( self, client: AsyncClient, logged_in_headers, basic_case, mock_mcp_settings_enabled, # noqa: ARG002 ): """Legacy SSE test for project rename with MCP server name update.""" # First create a project with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.get_project_sse_url") as mock_sse_url, patch("langflow.api.v1.projects.get_project_streamable_http_url") as mock_streamable_url, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate_create, patch("langflow.api.v1.projects.update_server"), patch("langflow.api.v1.projects.create_api_key"), patch("langflow.api.v1.projects.get_storage_service"), ): # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings mock_sse_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/sse" mock_streamable_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/streamable" mock_validation_create = MagicMock() mock_validation_create.has_conflict = False mock_validation_create.should_skip = False mock_validation_create.server_name = "lf-new-project" mock_validate_create.return_value = mock_validation_create create_response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) project_id = create_response.json()["id"] # Now update the project name update_case = {"name": "Updated Project Name", "description": "Updated description"} with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate, patch("langflow.api.v1.projects.update_server") as mock_update_server, patch("langflow.api.v1.projects.get_storage_service") as mock_storage, ): # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings mock_storage.return_value = MagicMock() # Mock old server validation mock_old_validation = MagicMock() mock_old_validation.server_exists = True mock_old_validation.project_id_matches = True mock_old_validation.server_name = "lf-new-project" mock_old_validation.existing_config = {"command": "uvx", "args": ["mcp-proxy", "old-url"]} # Mock new server validation mock_new_validation = MagicMock() mock_new_validation.has_conflict = False mock_new_validation.server_name = "lf-updated-project-name" mock_validate.side_effect = [mock_old_validation, mock_new_validation] response = await client.patch(f"api/v1/projects/{project_id}", json=update_case, headers=logged_in_headers) assert response.status_code == status.HTTP_200_OK result = response.json() assert result["name"] == "Updated Project Name" # Should validate both old and new server names assert mock_validate.call_count == 2 # Should update server twice (delete old, create new) assert mock_update_server.call_count == 2 async def test_update_project_name_with_mcp_conflict( self, client: AsyncClient, logged_in_headers, basic_case, mock_mcp_settings_enabled, # noqa: ARG002 ): """Test project rename with MCP server name conflict.""" # Create project first with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.get_project_streamable_http_url"), patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate_create, patch("langflow.api.v1.projects.update_server"), patch("langflow.api.v1.projects.create_api_key"), patch("langflow.api.v1.projects.get_storage_service"), ): # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings mock_validation_create = MagicMock() mock_validation_create.has_conflict = False mock_validation_create.should_skip = False mock_validation_create.server_name = "lf-new-project" mock_validate_create.return_value = mock_validation_create create_response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) project_id = create_response.json()["id"] # Try to update to conflicting name update_case = {"name": "Conflicting Project"} with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate, patch("langflow.api.v1.projects.get_storage_service") as mock_storage, ): # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings mock_storage.return_value = MagicMock() # Mock old server validation - exists and matches mock_old_validation = MagicMock() mock_old_validation.server_exists = True mock_old_validation.project_id_matches = True mock_old_validation.server_name = "lf-new-project" # Mock new server validation - has conflict mock_new_validation = MagicMock() mock_new_validation.has_conflict = True mock_new_validation.conflict_message = "Server name conflict with different project" mock_new_validation.server_name = "lf-conflicting-project" mock_validate.side_effect = [mock_old_validation, mock_new_validation] response = await client.patch(f"api/v1/projects/{project_id}", json=update_case, headers=logged_in_headers) assert response.status_code == status.HTTP_409_CONFLICT assert "conflict" in response.json()["detail"].lower() async def test_update_project_name_with_mcp_conflict_legacy_sse( self, client: AsyncClient, logged_in_headers, basic_case, mock_mcp_settings_enabled, # noqa: ARG002 ): """Legacy SSE test for project rename with MCP server name conflict.""" # Create project first with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.get_project_sse_url") as mock_sse_url, patch("langflow.api.v1.projects.get_project_streamable_http_url") as mock_streamable_url, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate_create, patch("langflow.api.v1.projects.update_server"), patch("langflow.api.v1.projects.create_api_key"), patch("langflow.api.v1.projects.get_storage_service"), ): # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings mock_sse_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/sse" mock_streamable_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/streamable" mock_validation_create = MagicMock() mock_validation_create.has_conflict = False mock_validation_create.should_skip = False mock_validation_create.server_name = "lf-new-project" mock_validate_create.return_value = mock_validation_create create_response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) project_id = create_response.json()["id"] # Try to update to conflicting name update_case = {"name": "Conflicting Project"} with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate, patch("langflow.api.v1.projects.get_storage_service") as mock_storage, ): # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings mock_storage.return_value = MagicMock() # Mock old server validation - exists and matches mock_old_validation = MagicMock() mock_old_validation.server_exists = True mock_old_validation.project_id_matches = True mock_old_validation.server_name = "lf-new-project" # Mock new server validation - has conflict mock_new_validation = MagicMock() mock_new_validation.has_conflict = True mock_new_validation.conflict_message = "Server name conflict with different project" mock_new_validation.server_name = "lf-conflicting-project" mock_validate.side_effect = [mock_old_validation, mock_new_validation] response = await client.patch(f"api/v1/projects/{project_id}", json=update_case, headers=logged_in_headers) assert response.status_code == status.HTTP_409_CONFLICT assert "conflict" in response.json()["detail"].lower() async def test_delete_project_with_mcp_server_cleanup( self, client: AsyncClient, logged_in_headers, basic_case, mock_mcp_settings_enabled, # noqa: ARG002 ): """Test project deletion with MCP server cleanup.""" # Create project first with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.get_project_streamable_http_url"), patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate_create, patch("langflow.api.v1.projects.update_server"), patch("langflow.api.v1.projects.create_api_key"), patch("langflow.api.v1.projects.get_storage_service"), ): # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings mock_validation_create = MagicMock() mock_validation_create.has_conflict = False mock_validation_create.should_skip = False mock_validation_create.server_name = "lf-new-project" mock_validate_create.return_value = mock_validation_create create_response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) project_id = create_response.json()["id"] # Delete the project with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate, patch("langflow.api.v1.projects.update_server") as mock_update_server, patch("langflow.api.v1.projects.get_storage_service") as mock_storage, ): # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings mock_storage.return_value = MagicMock() # Mock validation - server exists and matches this project mock_validation = MagicMock() mock_validation.server_exists = True mock_validation.project_id_matches = True mock_validation.server_name = "lf-new-project" mock_validate.return_value = mock_validation response = await client.delete(f"api/v1/projects/{project_id}", headers=logged_in_headers) assert response.status_code == status.HTTP_204_NO_CONTENT # Should validate server for deletion mock_validate.assert_called_once() # Should call update_server with delete=True mock_update_server.assert_called_once() _, kwargs = mock_update_server.call_args assert kwargs.get("delete") is True async def test_delete_project_with_mcp_server_cleanup_legacy_sse( self, client: AsyncClient, logged_in_headers, basic_case, mock_mcp_settings_enabled, # noqa: ARG002 ): """Legacy SSE test for project deletion with MCP server cleanup.""" # Create project first with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.get_project_sse_url") as mock_sse_url, patch("langflow.api.v1.projects.get_project_streamable_http_url") as mock_streamable_url, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate_create, patch("langflow.api.v1.projects.update_server"), patch("langflow.api.v1.projects.create_api_key"), patch("langflow.api.v1.projects.get_storage_service"), ): # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings mock_sse_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/sse" mock_streamable_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/streamable" mock_validation_create = MagicMock() mock_validation_create.has_conflict = False mock_validation_create.should_skip = False mock_validation_create.server_name = "lf-new-project" mock_validate_create.return_value = mock_validation_create create_response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) project_id = create_response.json()["id"] # Delete the project with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate, patch("langflow.api.v1.projects.update_server") as mock_update_server, patch("langflow.api.v1.projects.get_storage_service") as mock_storage, ): # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings mock_storage.return_value = MagicMock() # Mock validation - server exists and matches this project mock_validation = MagicMock() mock_validation.server_exists = True mock_validation.project_id_matches = True mock_validation.server_name = "lf-new-project" mock_validate.return_value = mock_validation response = await client.delete(f"api/v1/projects/{project_id}", headers=logged_in_headers) assert response.status_code == status.HTTP_204_NO_CONTENT # Should validate server for deletion mock_validate.assert_called_once() # Should call update_server with delete=True mock_update_server.assert_called_once() _, kwargs = mock_update_server.call_args assert kwargs.get("delete") is True async def test_delete_project_mcp_server_different_project( self, client: AsyncClient, logged_in_headers, basic_case, mock_mcp_settings_enabled, # noqa: ARG002 ): """Test project deletion when MCP server belongs to different project.""" # Create project first with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.get_project_streamable_http_url"), patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate_create, patch("langflow.api.v1.projects.update_server"), patch("langflow.api.v1.projects.create_api_key"), patch("langflow.api.v1.projects.get_storage_service"), ): # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings mock_validation_create = MagicMock() mock_validation_create.has_conflict = False mock_validation_create.should_skip = False mock_validation_create.server_name = "lf-new-project" mock_validate_create.return_value = mock_validation_create create_response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) project_id = create_response.json()["id"] # Delete the project with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate, patch("langflow.api.v1.projects.update_server") as mock_update_server, patch("langflow.api.v1.projects.get_storage_service") as mock_storage, ): # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings mock_storage.return_value = MagicMock() # Mock validation - server exists but belongs to different project mock_validation = MagicMock() mock_validation.server_exists = True mock_validation.project_id_matches = False mock_validation.server_name = "lf-new-project" mock_validate.return_value = mock_validation response = await client.delete(f"api/v1/projects/{project_id}", headers=logged_in_headers) assert response.status_code == status.HTTP_204_NO_CONTENT # Should validate server but not delete it mock_validate.assert_called_once() mock_update_server.assert_not_called() async def test_delete_project_mcp_server_different_project_legacy_sse( self, client: AsyncClient, logged_in_headers, basic_case, mock_mcp_settings_enabled, # noqa: ARG002 ): """Legacy SSE test for project deletion when MCP server belongs to different project.""" # Create project first with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.get_project_sse_url") as mock_sse_url, patch("langflow.api.v1.projects.get_project_streamable_http_url") as mock_streamable_url, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate_create, patch("langflow.api.v1.projects.update_server"), patch("langflow.api.v1.projects.create_api_key"), patch("langflow.api.v1.projects.get_storage_service"), ): # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings mock_sse_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/sse" mock_streamable_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/streamable" mock_validation_create = MagicMock() mock_validation_create.has_conflict = False mock_validation_create.should_skip = False mock_validation_create.server_name = "lf-new-project" mock_validate_create.return_value = mock_validation_create create_response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) project_id = create_response.json()["id"] # Delete the project with ( patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate, patch("langflow.api.v1.projects.update_server") as mock_update_server, patch("langflow.api.v1.projects.get_storage_service") as mock_storage, ): # Mock settings to enable MCP auto-add mock_settings = MagicMock() mock_settings.settings.add_projects_to_mcp_servers = True mock_settings.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_settings mock_storage.return_value = MagicMock() # Mock validation - server exists but belongs to different project mock_validation = MagicMock() mock_validation.server_exists = True mock_validation.project_id_matches = False mock_validation.server_name = "lf-new-project" mock_validate.return_value = mock_validation response = await client.delete(f"api/v1/projects/{project_id}", headers=logged_in_headers) assert response.status_code == status.HTTP_204_NO_CONTENT # Should validate server but not delete it mock_validate.assert_called_once() mock_update_server.assert_not_called() async def test_create_project_auto_login_disabled_adds_api_key_auth( self, client: AsyncClient, logged_in_headers, basic_case ): """Test that projects get API key auth when AUTO_LOGIN is disabled.""" with patch("langflow.api.v1.projects.get_settings_service") as mock_get_settings: mock_service = MagicMock() mock_service.settings.add_projects_to_mcp_servers = False # Disable MCP to focus on auth mock_service.auth_settings.AUTO_LOGIN = False mock_get_settings.return_value = mock_service with patch("langflow.api.v1.projects.encrypt_auth_settings") as mock_encrypt: mock_encrypt.return_value = {"auth_type": "apikey"} response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) assert response.status_code == status.HTTP_201_CREATED # Verify encrypt_auth_settings was called with apikey auth mock_encrypt.assert_called_once_with({"auth_type": "apikey"}) async def test_project_mcp_exception_handling( self, client: AsyncClient, logged_in_headers, basic_case, mock_mcp_settings_enabled, # noqa: ARG002 ): """Test that MCP exceptions during project creation don't prevent project creation.""" with ( patch("langflow.api.v1.projects.get_project_streamable_http_url") as mock_streamable_url, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate, patch("langflow.api.v1.projects.get_storage_service") as mock_storage, ): # Setup mocks mock_streamable_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/streamable" mock_storage.return_value = MagicMock() # Mock validation to raise an exception mock_validate.side_effect = Exception("MCP validation failed") response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) # Project should still be created despite MCP error assert response.status_code == status.HTTP_201_CREATED result = response.json() assert "name" in result assert result["name"] == basic_case["name"] async def test_project_mcp_exception_handling_legacy_sse( self, client: AsyncClient, logged_in_headers, basic_case, mock_mcp_settings_enabled, # noqa: ARG002 ): """Legacy SSE test ensuring MCP exceptions don't block project creation.""" with ( patch("langflow.api.v1.projects.get_project_sse_url") as mock_sse_url, patch("langflow.api.v1.projects.get_project_streamable_http_url") as mock_streamable_url, patch("langflow.api.v1.projects.validate_mcp_server_for_project") as mock_validate, patch("langflow.api.v1.projects.get_storage_service") as mock_storage, ): # Setup mocks mock_sse_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/sse" mock_streamable_url.return_value = "http://localhost:7860/api/v1/mcp/project/test-id/streamable" mock_storage.return_value = MagicMock() # Mock validation to raise an exception mock_validate.side_effect = Exception("MCP validation failed") response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) # Project should still be created despite MCP error assert response.status_code == status.HTTP_201_CREATED result = response.json() assert "name" in result assert result["name"] == basic_case["name"] # Tests for the read_project bug fix class TestReadProjectBugFix: """Test the read_project endpoint fix for ASGI response bug.""" async def test_read_project_without_pagination_params(self, client: AsyncClient, logged_in_headers, basic_case): """Test read_project returns correct response when no pagination params are provided.""" # Create a project first create_response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) assert create_response.status_code == status.HTTP_201_CREATED project_id = create_response.json()["id"] # Read project without pagination params response = await client.get(f"api/v1/projects/{project_id}", headers=logged_in_headers) assert response.status_code == status.HTTP_200_OK result = response.json() # Should return FolderReadWithFlows (direct project response) assert isinstance(result, dict) assert "name" in result assert "description" in result assert "id" in result assert "flows" in result assert result["name"] == basic_case["name"] async def test_read_project_with_pagination_params(self, client: AsyncClient, logged_in_headers, basic_case): """Test read_project returns paginated response when pagination params are provided.""" # Create a project first create_response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) assert create_response.status_code == status.HTTP_201_CREATED project_id = create_response.json()["id"] # Read project with pagination params response = await client.get(f"api/v1/projects/{project_id}?page=1&size=10", headers=logged_in_headers) assert response.status_code == status.HTTP_200_OK result = response.json() # Should return FolderWithPaginatedFlows (paginated response) assert isinstance(result, dict) assert "folder" in result assert "flows" in result # Check folder structure folder = result["folder"] assert "name" in folder assert "description" in folder assert "id" in folder assert folder["name"] == basic_case["name"] # Check flows pagination structure flows = result["flows"] assert "items" in flows assert "total" in flows assert "page" in flows assert "size" in flows async def test_read_project_with_partial_pagination_params( self, client: AsyncClient, logged_in_headers, basic_case ): """Test read_project behavior when only some pagination params are provided.""" # Create a project first create_response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) assert create_response.status_code == status.HTTP_201_CREATED project_id = create_response.json()["id"] # Test with only page param (no size) response = await client.get(f"api/v1/projects/{project_id}?page=1", headers=logged_in_headers) assert response.status_code == status.HTTP_200_OK result = response.json() # Should return non-paginated response (FolderReadWithFlows) assert isinstance(result, dict) assert "name" in result # Direct project response assert "flows" in result assert result["name"] == basic_case["name"] # Test with only size param (no page) response = await client.get(f"api/v1/projects/{project_id}?size=10", headers=logged_in_headers) assert response.status_code == status.HTTP_200_OK result = response.json() # Should return non-paginated response (FolderReadWithFlows) assert isinstance(result, dict) assert "name" in result # Direct project response assert "flows" in result assert result["name"] == basic_case["name"] async def test_read_project_with_filtering_params(self, client: AsyncClient, logged_in_headers, basic_case): """Test read_project with filtering parameters (is_component, is_flow, search).""" # Create a project first create_response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) assert create_response.status_code == status.HTTP_201_CREATED project_id = create_response.json()["id"] # Create a flow and component in the project for filtering tests flow_payload = { "name": "Test Flow", "description": "A test flow", "folder_id": project_id, "data": {"nodes": [], "edges": []}, "is_component": False, } component_payload = { "name": "Test Component", "description": "A test component", "folder_id": project_id, "data": {"nodes": [], "edges": []}, "is_component": True, } flow_response = await client.post("api/v1/flows/", json=flow_payload, headers=logged_in_headers) comp_response = await client.post("api/v1/flows/", json=component_payload, headers=logged_in_headers) assert flow_response.status_code == status.HTTP_201_CREATED assert comp_response.status_code == status.HTTP_201_CREATED # Test with filtering params but no pagination (should use non-paginated path) response = await client.get(f"api/v1/projects/{project_id}?is_flow=true", headers=logged_in_headers) assert response.status_code == status.HTTP_200_OK result = response.json() # Should return non-paginated response assert isinstance(result, dict) assert "name" in result assert "flows" in result # Test with filtering params AND pagination (should use paginated path) response = await client.get( f"api/v1/projects/{project_id}?is_flow=true&page=1&size=10", headers=logged_in_headers ) assert response.status_code == status.HTTP_200_OK result = response.json() # Should return paginated response assert isinstance(result, dict) assert "folder" in result assert "flows" in result assert "items" in result["flows"] async def test_read_project_consistent_response_structure(self, client: AsyncClient, logged_in_headers, basic_case): """Test that read_project returns consistent response structure in all cases.""" # Create a project first create_response = await client.post("api/v1/projects/", json=basic_case, headers=logged_in_headers) assert create_response.status_code == status.HTTP_201_CREATED project_id = create_response.json()["id"] # Test multiple request scenarios to ensure consistency test_cases = [ # No params - should return FolderReadWithFlows {"params": "", "expect_paginated": False}, # Only search - should return FolderReadWithFlows {"params": "?search=test", "expect_paginated": False}, # Only is_component - should return FolderReadWithFlows {"params": "?is_component=true", "expect_paginated": False}, # Only is_flow - should return FolderReadWithFlows {"params": "?is_flow=true", "expect_paginated": False}, # Only page - should return FolderReadWithFlows {"params": "?page=1", "expect_paginated": False}, # Only size - should return FolderReadWithFlows {"params": "?size=10", "expect_paginated": False}, # Both page and size - should return FolderWithPaginatedFlows {"params": "?page=1&size=10", "expect_paginated": True}, # Page, size and filters - should return FolderWithPaginatedFlows {"params": "?page=1&size=10&is_flow=true", "expect_paginated": True}, ] for test_case in test_cases: response = await client.get(f"api/v1/projects/{project_id}{test_case['params']}", headers=logged_in_headers) assert response.status_code == status.HTTP_200_OK, f"Failed for params: {test_case['params']}" result = response.json() assert isinstance(result, dict), f"Result should be dict for params: {test_case['params']}" if test_case["expect_paginated"]: # Paginated response structure assert "folder" in result, f"Paginated response missing 'folder' for params: {test_case['params']}" assert "flows" in result, f"Paginated response missing 'flows' for params: {test_case['params']}" assert "items" in result["flows"], f"Paginated flows missing 'items' for params: {test_case['params']}" assert "total" in result["flows"], f"Paginated flows missing 'total' for params: {test_case['params']}" else: # Non-paginated response structure assert "name" in result, f"Non-paginated response missing 'name' for params: {test_case['params']}" assert "flows" in result, f"Non-paginated response missing 'flows' for params: {test_case['params']}" # Should NOT have pagination structure assert "folder" not in result, ( f"Non-paginated response should not have 'folder' for params: {test_case['params']}" ) async def test_read_project_error_handling_consistency(self, client: AsyncClient, logged_in_headers): """Test that error handling is consistent across both response paths.""" import uuid non_existent_id = str(uuid.uuid4()) # Test both pagination and non-pagination paths with non-existent project test_cases = [ "", # Non-paginated path "?page=1&size=10", # Paginated path ] for params in test_cases: response = await client.get(f"api/v1/projects/{non_existent_id}{params}", headers=logged_in_headers) assert response.status_code == status.HTTP_404_NOT_FOUND, f"Should return 404 for params: {params}" result = response.json() assert "detail" in result, f"Error response should have 'detail' for params: {params}" assert "not found" in result["detail"].lower(), ( f"Error message should mention 'not found' for params: {params}" ) async def test_download_file_starter_project(client: AsyncClient, logged_in_headers, active_user, json_flow): """Test downloading a project with multiple flows. This test specifically validates: 1. The download endpoint returns a valid ZIP file with multiple flows 2. The remove_api_keys function handles flows with various template structures, including components that don't have 'name' keys in their template values (e.g., Note components with only backgroundColor) 3. API keys are removed from downloaded flows 4. Non-sensitive data is preserved in the download """ # Create a project for the user (since download_file requires user ownership) project_payload = { "name": STARTER_FOLDER_NAME, "description": "Starter projects to help you get started in Langflow.", "flows_list": [], "components_list": [], } create_response = await client.post("api/v1/projects/", json=project_payload, headers=logged_in_headers) assert create_response.status_code == status.HTTP_201_CREATED starter_project = create_response.json() starter_project_id = starter_project["id"] # Create multiple flows in the project flow_data = json.loads(json_flow) # Create a flow with a Note component to test the bug fix # Note components have template values without 'name' keys flow_with_note = { "nodes": [ { "id": "note-1", "type": "genericNode", "data": { "node": { "template": { "backgroundColor": {"value": "#ffffff"}, # No 'name' key "text": {"value": "Test note"}, # No 'name' key } } }, }, # Add a node with API keys to test removal { "id": "api-node-1", "type": "genericNode", "data": { "node": { "template": { "api_key": { "name": "api_key", "value": "secret-key-123", "password": True, }, "regular_field": {"name": "regular_field", "value": "keep-this"}, } } }, }, ], "edges": [], } flows_created = [] async with session_scope() as session: # Create 3 flows: 2 from basic example + 1 with Note component for i in range(2): flow_create = FlowCreate( name=f"Starter Flow {i + 1}", description=f"Test starter flow {i + 1}", data=flow_data.get("data", {}), folder_id=starter_project_id, user_id=active_user.id, ) flow = Flow.model_validate(flow_create, from_attributes=True) session.add(flow) flows_created.append(flow) # Add flow with Note component flow_create_note = FlowCreate( name="Flow with Note", description="Flow with Note component and API keys", data=flow_with_note, folder_id=starter_project_id, user_id=active_user.id, ) flow_note = Flow.model_validate(flow_create_note, from_attributes=True) session.add(flow_note) flows_created.append(flow_note) await session.flush() # Refresh to get IDs for flow in flows_created: await session.refresh(flow) await session.commit() # Download the starter project response = await client.get( f"api/v1/projects/download/{starter_project_id}", headers=logged_in_headers, ) # Verify response assert response.status_code == status.HTTP_200_OK, response.text assert response.headers["Content-Type"] == "application/x-zip-compressed" assert "attachment" in response.headers["Content-Disposition"] assert "filename" in response.headers["Content-Disposition"] # The filename is URL-encoded in the header, so check for the project name content_disposition = response.headers["Content-Disposition"] assert ( STARTER_FOLDER_NAME.replace(" ", "%20") in content_disposition or STARTER_FOLDER_NAME.replace(" ", "_") in content_disposition ) # Verify zip file contents zip_content = response.content with zipfile.ZipFile(io.BytesIO(zip_content), "r") as zip_file: file_names = zip_file.namelist() # Should have 3 flow files assert len(file_names) == 3, f"Expected 3 files in zip, got {len(file_names)}: {file_names}" # Verify each basic flow file exists and contains valid JSON for i in range(2): expected_filename = f"Starter Flow {i + 1}.json" assert expected_filename in file_names, f"Expected {expected_filename} in zip file" # Read and verify flow content flow_content = zip_file.read(expected_filename) flow_json = json.loads(flow_content) assert flow_json["name"] == f"Starter Flow {i + 1}" assert flow_json["description"] == f"Test starter flow {i + 1}" # Verify the flow with Note component note_flow_filename = "Flow with Note.json" assert note_flow_filename in file_names, f"Expected {note_flow_filename} in zip file" # Read and verify the Note flow - this tests the bug fix note_flow_content = zip_file.read(note_flow_filename) note_flow_json = json.loads(note_flow_content) assert note_flow_json["name"] == "Flow with Note" assert note_flow_json["description"] == "Flow with Note component and API keys" # Verify the flow has the expected structure assert "data" in note_flow_json assert "nodes" in note_flow_json["data"] assert len(note_flow_json["data"]["nodes"]) == 2 # Find the API node and verify API key was removed api_node = None note_node = None for node in note_flow_json["data"]["nodes"]: if node["id"] == "api-node-1": api_node = node elif node["id"] == "note-1": note_node = node # Verify Note node exists and didn't cause errors (the bug fix) assert note_node is not None, "Note node should exist in downloaded flow" note_template = note_node["data"]["node"]["template"] assert "backgroundColor" in note_template, "Note backgroundColor should be preserved" assert "text" in note_template, "Note text should be preserved" # Verify API key was removed but regular field was kept assert api_node is not None, "API node should exist in downloaded flow" api_template = api_node["data"]["node"]["template"] assert "api_key" in api_template, "API key field should exist" assert api_template["api_key"]["value"] is None, "API key value should be removed/null" assert "regular_field" in api_template, "Regular field should be preserved" assert api_template["regular_field"]["value"] == "keep-this", "Regular field value should be kept" # Clean up: delete the project (which will cascade delete flows) delete_response = await client.delete(f"api/v1/projects/{starter_project_id}", headers=logged_in_headers) assert delete_response.status_code == status.HTTP_204_NO_CONTENT
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/api/v1/test_projects.py", "license": "MIT License", "lines": 1453, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
langflow-ai/langflow:src/backend/base/langflow/services/flow/flow_runner.py
import json import os from pathlib import Path from uuid import UUID, uuid4 from aiofile import async_open from lfx.graph import Graph from lfx.graph.vertex.param_handler import ParameterHandler from lfx.log.logger import configure, logger from lfx.utils.util import update_settings from sqlmodel import delete, select, text from langflow.api.utils import cascade_delete_flow from langflow.load.utils import replace_tweaks_with_env from langflow.processing.process import process_tweaks, run_graph from langflow.services.cache.service import AsyncBaseCacheService from langflow.services.database.models import Flow, User, Variable from langflow.services.database.utils import initialize_database from langflow.services.deps import get_auth_service, get_cache_service, get_storage_service, session_scope class LangflowRunnerExperimental: """LangflowRunnerExperimental orchestrates flow execution without a dedicated server. .. warning:: This class is currently **experimental** and in a **beta phase**. Its API and behavior may change in future releases. Use with caution in production environments. Usage: ------ Instantiate the class and call the `run` method with the desired flow and input. Example: runner = LangflowRunnerExperimental() result = await runner.run(flow="path/to/flow.json", input_value="Hello", session_id=str(uuid.uuid4())) """ def __init__( self, *, should_initialize_db: bool = True, log_level: str | None = None, log_file: str | None = None, log_rotation: str | None = None, disable_logs: bool = False, ): self.should_initialize_db = should_initialize_db log_file_path = Path(log_file) if log_file else None configure( log_level=log_level, log_file=log_file_path, log_rotation=log_rotation, disable=disable_logs, ) async def run( self, session_id: str, # UUID required currently flow: Path | str | dict, input_value: str, *, input_type: str = "chat", output_type: str = "all", cache: str | None = None, stream: bool = False, user_id: str | None = None, generate_user: bool = False, # If True, generates a new user for the flow cleanup: bool = True, # If True, clears flow state after execution tweaks_values: dict | None = None, ): try: await logger.ainfo(f"Start Handling {session_id=}") await self.init_db_if_needed() # Update settings with cache and components path await update_settings(cache=cache) if generate_user: user = await self.generate_user() user_id = str(user.id) flow_dict = await self.prepare_flow_and_add_to_db( flow=flow, user_id=user_id, session_id=session_id, tweaks_values=tweaks_values, ) return await self.run_flow( input_value=input_value, session_id=session_id, flow_dict=flow_dict, input_type=input_type, output_type=output_type, user_id=user_id, stream=stream, ) finally: if cleanup and user_id: await self.clear_user_state(user_id=user_id) async def run_flow( self, *, input_value: str, session_id: str, flow_dict: dict, input_type: str = "chat", output_type: str = "all", user_id: str | None = None, stream: bool = False, ): graph = await self.create_graph_from_flow(session_id, flow_dict, user_id=user_id) try: result = await self.run_graph(input_value, input_type, output_type, session_id, graph, stream=stream) finally: await self.clear_flow_state(flow_dict) await logger.ainfo(f"Finish Handling {session_id=}") return result async def prepare_flow_and_add_to_db( self, *, flow: Path | str | dict, user_id: str | None = None, custom_flow_id: str | None = None, session_id: str | None = None, tweaks_values: dict | None = None, ) -> dict: flow_dict = await self.get_flow_dict(flow) session_id = session_id or custom_flow_id or str(uuid4()) if custom_flow_id: flow_dict["id"] = custom_flow_id flow_dict = self.process_tweaks(flow_dict, tweaks_values=tweaks_values) await self.clear_flow_state(flow_dict) await self.add_flow_to_db(flow_dict, user_id=user_id) return flow_dict def process_tweaks(self, flow_dict: dict, tweaks_values: dict | None = None) -> dict: tweaks: dict | None = None tweaks_values = tweaks_values or os.environ.copy() for vertex in Graph.from_payload(flow_dict).vertices: param_handler = ParameterHandler(vertex, get_storage_service()) field_params, load_from_db_fields = param_handler.process_field_parameters() for db_field in load_from_db_fields: if field_params[db_field]: tweaks = tweaks or {} tweaks[vertex.id] = tweaks.get(vertex.id, {}) tweaks[vertex.id][db_field] = field_params[db_field] if tweaks is not None: tweaks = replace_tweaks_with_env(tweaks=tweaks, env_vars=tweaks_values) flow_dict = process_tweaks(flow_dict, tweaks) # Recursively update load_from_db fields def update_load_from_db(obj): if isinstance(obj, dict): for key, value in obj.items(): if key == "load_from_db" and value is True: obj[key] = False else: update_load_from_db(value) elif isinstance(obj, list): for item in obj: update_load_from_db(item) update_load_from_db(flow_dict) return flow_dict async def generate_user(self) -> User: async with session_scope() as session: user_id = str(uuid4()) hashed = get_auth_service().get_password_hash(str(uuid4())) user = User(id=user_id, username=user_id, password=hashed, is_active=True) session.add(user) await session.flush() await session.refresh(user) return user @staticmethod async def add_flow_to_db(flow_dict: dict, user_id: str | None): async with session_scope() as session: flow_db = Flow( name=flow_dict.get("name"), id=UUID(flow_dict["id"]), data=flow_dict.get("data", {}), user_id=user_id ) session.add(flow_db) @staticmethod async def run_graph( input_value: str, input_type: str, output_type: str, session_id: str, graph: Graph, *, stream: bool, ): return await run_graph( graph=graph, session_id=session_id, input_value=input_value, fallback_to_env_vars=True, input_type=input_type, output_type=output_type, stream=stream, ) @staticmethod async def create_graph_from_flow(session_id: str, flow_dict: dict, user_id: str | None = None): graph = Graph.from_payload( payload=flow_dict, flow_id=flow_dict["id"], flow_name=flow_dict.get("name"), user_id=user_id ) graph.session_id = session_id graph.set_run_id(session_id) graph.user_id = user_id await graph.initialize_run() return graph @staticmethod async def clear_flow_state(flow_dict: dict): cache_service = get_cache_service() if isinstance(cache_service, AsyncBaseCacheService): await cache_service.clear() else: cache_service.clear() async with session_scope() as session: flow_id = flow_dict["id"] uuid_obj = flow_id if isinstance(flow_id, UUID) else UUID(str(flow_id)) await cascade_delete_flow(session, uuid_obj) @staticmethod async def clear_user_state(user_id: str): async with session_scope() as session: flows = await session.exec(select(Flow.id).where(Flow.user_id == user_id)) flow_ids: list[UUID] = [fid for fid in flows.scalars().all() if fid is not None] for flow_id in flow_ids: await cascade_delete_flow(session, flow_id) await session.exec(delete(Variable).where(Variable.user_id == user_id)) await session.exec(delete(User).where(User.id == user_id)) async def init_db_if_needed(self): if not await self.database_exists_check() and self.should_initialize_db: await logger.ainfo("Initializing database...") await initialize_database(fix_migration=True) self.should_initialize_db = False await logger.ainfo("Database initialized.") @staticmethod async def database_exists_check(): async with session_scope() as session: try: result = await session.exec(text("SELECT version_num FROM public.alembic_version")) return result.first() is not None except Exception as e: # noqa: BLE001 await logger.adebug(f"Database check failed: {e}") return False @staticmethod async def get_flow_dict(flow: Path | str | dict) -> dict: if isinstance(flow, str | Path): async with async_open(Path(flow), encoding="utf-8") as f: content = await f.read() return json.loads(content) # If input is a dictionary, assume it's a JSON object elif isinstance(flow, dict): return flow error_msg = "Input must be a file path (str or Path object) or a JSON object (dict)." raise TypeError(error_msg)
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/base/langflow/services/flow/flow_runner.py", "license": "MIT License", "lines": 240, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
langflow-ai/langflow:src/backend/tests/unit/services/flow/test_flow_runner.py
from uuid import uuid4 import pytest from langflow.services.flow.flow_runner import LangflowRunnerExperimental @pytest.fixture def sample_flow_dict(): return { "id": str(uuid4()), # Add required ID field "name": "test_flow", # Add name field "data": { "nodes": [], "edges": [], }, } @pytest.fixture def flow_runner(): return LangflowRunnerExperimental() @pytest.mark.asyncio async def test_database_exists_check(flow_runner): """Test database exists check functionality.""" result = await flow_runner.database_exists_check() assert isinstance(result, bool) @pytest.mark.asyncio async def test_get_flow_dict_from_dict(flow_runner, sample_flow_dict): """Test loading flow from a dictionary.""" result = await flow_runner.get_flow_dict(sample_flow_dict) assert result == sample_flow_dict @pytest.mark.asyncio async def test_get_flow_dict_invalid_input(flow_runner): """Test loading flow with invalid input type.""" pattern = r"Input must be a file path .* or a JSON object .*" with pytest.raises(TypeError, match=pattern): await flow_runner.get_flow_dict(123) @pytest.mark.asyncio async def test_run_with_dict_input(flow_runner, sample_flow_dict): """Test running flow with dictionary input.""" session_id = str(uuid4()) input_value = "test input" result = await flow_runner.run( session_id=session_id, flow=sample_flow_dict, input_value=input_value, ) assert result is not None @pytest.mark.asyncio async def test_run_with_different_input_types(flow_runner, sample_flow_dict): """Test running flow with different input and output types.""" session_id = str(uuid4()) test_cases = [ ("text input", "text", "text"), ("chat input", "chat", "chat"), ("test input", "chat", "all"), # Updated to use "all" as default output_type ] for input_value, input_type, output_type in test_cases: result = await flow_runner.run( session_id=session_id, flow=sample_flow_dict, input_value=input_value, input_type=input_type, output_type=output_type, ) assert result is not None @pytest.mark.asyncio async def test_initialize_database(flow_runner): """Test database initialization.""" flow_runner.should_initialize_db = True await flow_runner.init_db_if_needed() assert not flow_runner.should_initialize_db
{ "repo_id": "langflow-ai/langflow", "file_path": "src/backend/tests/unit/services/flow/test_flow_runner.py", "license": "MIT License", "lines": 67, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
letta-ai/letta:letta/services/memory_repo/path_mapping.py
"""Helpers for mapping memory-repo markdown paths to block labels. Special handling for skills: - sync `skills/{skill_name}/SKILL.md` as block label `skills/{skill_name}` - ignore all other markdown files under `skills/` """ from __future__ import annotations def memory_block_label_from_markdown_path(path: str) -> str | None: """Return block label for a syncable markdown path, else None. Rules: - Non-`.md` files are ignored. - `skills/{skill_name}/SKILL.md` -> `skills/{skill_name}` - Other `skills/**` markdown files are ignored. - All other markdown files map to `path[:-3]`. """ if not path.endswith(".md"): return None if path.startswith("skills/"): parts = path.split("/") if len(parts) == 3 and parts[0] == "skills" and parts[1] and parts[2] == "SKILL.md": return f"skills/{parts[1]}" return None return path[:-3]
{ "repo_id": "letta-ai/letta", "file_path": "letta/services/memory_repo/path_mapping.py", "license": "Apache License 2.0", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
letta-ai/letta:alembic/versions/3e54e2fa2f7e_add_usage_columns_to_steps.py
"""add_usage_columns_to_steps Revision ID: 3e54e2fa2f7e Revises: a1b2c3d4e5f8 Create Date: 2026-02-03 16:35:51.327031 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision: str = "3e54e2fa2f7e" down_revision: Union[str, None] = "a1b2c3d4e5f8" branch_labels: Union[str, Sequence[str], None] = None depends_on: Union[str, Sequence[str], None] = None def upgrade() -> None: op.add_column("steps", sa.Column("model_handle", sa.String(), nullable=True)) op.add_column("steps", sa.Column("cached_input_tokens", sa.Integer(), nullable=True)) op.add_column("steps", sa.Column("cache_write_tokens", sa.Integer(), nullable=True)) op.add_column("steps", sa.Column("reasoning_tokens", sa.Integer(), nullable=True)) def downgrade() -> None: op.drop_column("steps", "reasoning_tokens") op.drop_column("steps", "cache_write_tokens") op.drop_column("steps", "cached_input_tokens") op.drop_column("steps", "model_handle")
{ "repo_id": "letta-ai/letta", "file_path": "alembic/versions/3e54e2fa2f7e_add_usage_columns_to_steps.py", "license": "Apache License 2.0", "lines": 23, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
letta-ai/letta:alembic/versions/b2c3d4e5f6a8_add_llm_config_to_conversations.py
"""Add model and model_settings columns to conversations table for model overrides Revision ID: b2c3d4e5f6a8 Revises: 3e54e2fa2f7e Create Date: 2026-02-23 02:50:00.000000 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision: str = "b2c3d4e5f6a8" down_revision: Union[str, None] = "3e54e2fa2f7e" branch_labels: Union[str, Sequence[str], None] = None depends_on: Union[str, Sequence[str], None] = None def upgrade() -> None: op.add_column("conversations", sa.Column("model", sa.String(), nullable=True)) op.add_column("conversations", sa.Column("model_settings", sa.JSON(), nullable=True)) def downgrade() -> None: op.drop_column("conversations", "model_settings") op.drop_column("conversations", "model")
{ "repo_id": "letta-ai/letta", "file_path": "alembic/versions/b2c3d4e5f6a8_add_llm_config_to_conversations.py", "license": "Apache License 2.0", "lines": 19, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
letta-ai/letta:letta/adapters/sglang_native_adapter.py
""" SGLang Native Adapter for multi-turn RL training. This adapter uses SGLang's native /generate endpoint instead of the OpenAI-compatible endpoint to get token IDs and per-token logprobs, which are essential for proper multi-turn RL training with loss masking. Uses HuggingFace tokenizer's apply_chat_template() for proper tool formatting. """ import json import re import time import uuid from typing import Any, AsyncGenerator, Optional from letta.adapters.simple_llm_request_adapter import SimpleLLMRequestAdapter from letta.helpers.datetime_helpers import get_utc_timestamp_ns from letta.llm_api.sglang_native_client import SGLangNativeClient from letta.log import get_logger from letta.schemas.letta_message import LettaMessage from letta.schemas.letta_message_content import TextContent from letta.schemas.openai.chat_completion_response import ( ChatCompletionResponse, ChatCompletionTokenLogprob, Choice, ChoiceLogprobs, FunctionCall, Message as ChoiceMessage, ToolCall, UsageStatistics, ) logger = get_logger(__name__) # Global tokenizer cache _tokenizer_cache: dict[str, Any] = {} class SGLangNativeAdapter(SimpleLLMRequestAdapter): """ Adapter that uses SGLang's native /generate endpoint for multi-turn RL training. Key differences from SimpleLLMRequestAdapter: - Uses /generate instead of /v1/chat/completions - Returns output_ids (token IDs) in addition to text - Returns output_token_logprobs with [logprob, token_id] pairs - Formats tools into prompt and parses tool calls from response These are essential for building accurate loss masks in multi-turn training. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._sglang_client: Optional[SGLangNativeClient] = None self._tokenizer: Any = None def _get_tokenizer(self) -> Any: """Get or create tokenizer for the model.""" global _tokenizer_cache # Get model name from llm_config model_name = self.llm_config.model if not model_name: logger.warning("No model name in llm_config, cannot load tokenizer") return None # Check cache if model_name in _tokenizer_cache: return _tokenizer_cache[model_name] try: from transformers import AutoTokenizer logger.info(f"Loading tokenizer for model: {model_name}") tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True) _tokenizer_cache[model_name] = tokenizer return tokenizer except ImportError: logger.warning("transformers not installed, falling back to manual formatting") return None except Exception as e: logger.warning(f"Failed to load tokenizer: {e}, falling back to manual formatting") return None def _get_sglang_client(self) -> SGLangNativeClient: """Get or create SGLang native client.""" if self._sglang_client is None: # Get base URL from llm_config, removing /v1 suffix if present base_url = self.llm_config.model_endpoint or "" # SGLang local instances typically don't need API key self._sglang_client = SGLangNativeClient( base_url=base_url, api_key=None, ) return self._sglang_client def _format_tools_for_prompt(self, tools: list) -> str: """ Format tools in Qwen3 chat template format for the system prompt. This matches the exact format produced by Qwen3's tokenizer.apply_chat_template() with tools parameter. """ if not tools: return "" # Format each tool as JSON (matching Qwen3 template exactly) tool_jsons = [] for tool in tools: # Handle both dict and object formats if isinstance(tool, dict): # Already in OpenAI format tool_jsons.append(json.dumps(tool)) else: # Convert object to dict tool_dict = { "type": "function", "function": { "name": getattr(getattr(tool, "function", tool), "name", ""), "description": getattr(getattr(tool, "function", tool), "description", ""), "parameters": getattr(getattr(tool, "function", tool), "parameters", {}), }, } tool_jsons.append(json.dumps(tool_dict)) # Use exact Qwen3 format tools_section = ( "\n\n# Tools\n\n" "You may call one or more functions to assist with the user query.\n\n" "You are provided with function signatures within <tools></tools> XML tags:\n" "<tools>\n" + "\n".join(tool_jsons) + "\n" "</tools>\n\n" "For each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:\n" "<tool_call>\n" '{"name": <function-name>, "arguments": <args-json-object>}\n' "</tool_call>" ) return tools_section def _convert_messages_to_openai_format(self, messages: list) -> list[dict]: """Convert Letta Message objects to OpenAI-style message dicts.""" openai_messages = [] for msg in messages: # Handle both dict and Pydantic Message objects if hasattr(msg, "role"): role = msg.role content = msg.content if hasattr(msg, "content") else "" # Handle content that might be a list of content parts if isinstance(content, list): content = " ".join([c.text if hasattr(c, "text") else str(c) for c in content]) elif content is None: content = "" tool_calls = getattr(msg, "tool_calls", None) tool_call_id = getattr(msg, "tool_call_id", None) name = getattr(msg, "name", None) else: role = msg.get("role", "user") content = msg.get("content", "") tool_calls = msg.get("tool_calls", None) tool_call_id = msg.get("tool_call_id", None) name = msg.get("name", None) openai_msg = {"role": role, "content": content} if tool_calls: # Convert tool calls to OpenAI format openai_tool_calls = [] for tc in tool_calls: if hasattr(tc, "function"): tc_dict = { "id": getattr(tc, "id", f"call_{uuid.uuid4().hex[:8]}"), "type": "function", "function": { "name": tc.function.name, "arguments": tc.function.arguments if isinstance(tc.function.arguments, str) else json.dumps(tc.function.arguments), }, } else: tc_dict = { "id": tc.get("id", f"call_{uuid.uuid4().hex[:8]}"), "type": "function", "function": tc.get("function", {}), } openai_tool_calls.append(tc_dict) openai_msg["tool_calls"] = openai_tool_calls if tool_call_id: openai_msg["tool_call_id"] = tool_call_id if name and role == "tool": openai_msg["name"] = name openai_messages.append(openai_msg) return openai_messages def _convert_tools_to_openai_format(self, tools: list) -> list[dict]: """Convert tools to OpenAI format for tokenizer.""" openai_tools = [] for tool in tools: if isinstance(tool, dict): # Already a dict, ensure it's in the right format if "function" in tool: openai_tools.append(tool) else: # Might be the function directly openai_tools.append({"type": "function", "function": tool}) else: # Convert object to dict func = getattr(tool, "function", tool) tool_dict = { "type": "function", "function": { "name": getattr(func, "name", ""), "description": getattr(func, "description", ""), "parameters": getattr(func, "parameters", {}), }, } openai_tools.append(tool_dict) return openai_tools def _format_messages_to_text(self, messages: list, tools: list) -> str: """ Format messages to text using tokenizer's apply_chat_template if available. Falls back to manual formatting if tokenizer is not available. """ tokenizer = self._get_tokenizer() if tokenizer is not None: # Use tokenizer's apply_chat_template for proper formatting openai_messages = self._convert_messages_to_openai_format(messages) openai_tools = self._convert_tools_to_openai_format(tools) if tools else None try: formatted = tokenizer.apply_chat_template( openai_messages, tokenize=False, add_generation_prompt=True, tools=openai_tools, ) logger.debug(f"Formatted prompt using tokenizer ({len(formatted)} chars)") return formatted except Exception as e: logger.warning(f"apply_chat_template failed: {e}, falling back to manual formatting") # Fallback to manual formatting return self._format_messages_to_text_manual(messages, tools) def _format_messages_to_text_manual(self, messages: list, tools: list) -> str: """Manual fallback formatting for when tokenizer is not available.""" formatted_parts = [] tools_section = self._format_tools_for_prompt(tools) for msg in messages: # Handle both dict and Pydantic Message objects if hasattr(msg, "role"): role = msg.role content = msg.content if hasattr(msg, "content") else "" if isinstance(content, list): content = " ".join([c.text if hasattr(c, "text") else str(c) for c in content]) elif content is None: content = "" tool_calls = getattr(msg, "tool_calls", None) else: role = msg.get("role", "user") content = msg.get("content", "") tool_calls = msg.get("tool_calls", None) if role == "system": system_content = content + tools_section if tools_section else content formatted_parts.append(f"<|im_start|>system\n{system_content}<|im_end|>") tools_section = "" elif role == "user": formatted_parts.append(f"<|im_start|>user\n{content}<|im_end|>") elif role == "assistant": if tool_calls: tc_parts = [] for tc in tool_calls: if hasattr(tc, "function"): tc_name = tc.function.name tc_args = tc.function.arguments else: tc_name = tc.get("function", {}).get("name", "") tc_args = tc.get("function", {}).get("arguments", "{}") if isinstance(tc_args, str): try: tc_args = json.loads(tc_args) except Exception: pass tc_parts.append(f'<tool_call>\n{{"name": "{tc_name}", "arguments": {json.dumps(tc_args)}}}\n</tool_call>') assistant_content = content + "\n" + "\n".join(tc_parts) if content else "\n".join(tc_parts) formatted_parts.append(f"<|im_start|>assistant\n{assistant_content}<|im_end|>") elif content: formatted_parts.append(f"<|im_start|>assistant\n{content}<|im_end|>") elif role == "tool": formatted_parts.append(f"<|im_start|>user\n<tool_response>\n{content}\n</tool_response><|im_end|>") formatted_parts.append("<|im_start|>assistant\n") return "\n".join(formatted_parts) def _parse_tool_calls(self, text: str) -> list[ToolCall]: """ Parse tool calls from response text. Looks for patterns like: <tool_call> {"name": "tool_name", "arguments": {...}} </tool_call> """ tool_calls = [] # Find all tool_call blocks pattern = r"<tool_call>\s*(\{.*?\})\s*</tool_call>" matches = re.findall(pattern, text, re.DOTALL) for match in matches: try: tc_data = json.loads(match) name = tc_data.get("name", "") arguments = tc_data.get("arguments", {}) if isinstance(arguments, dict): arguments = json.dumps(arguments) tool_call = ToolCall( id=f"call_{uuid.uuid4().hex[:8]}", type="function", function=FunctionCall( name=name, arguments=arguments, ), ) tool_calls.append(tool_call) except json.JSONDecodeError as e: logger.warning(f"Failed to parse tool call JSON: {e}") continue return tool_calls def _extract_content_without_tool_calls(self, text: str) -> str: """Extract content from response, removing tool_call blocks.""" # Remove tool_call blocks cleaned = re.sub(r"<tool_call>.*?</tool_call>", "", text, flags=re.DOTALL) # Clean up whitespace cleaned = cleaned.strip() return cleaned async def invoke_llm( self, request_data: dict, messages: list, tools: list, use_assistant_message: bool, requires_approval_tools: list[str] = [], step_id: str | None = None, actor: str | None = None, ) -> AsyncGenerator[LettaMessage | None, None]: """ Execute LLM request using SGLang native endpoint. This method: 1. Formats messages and tools to text using chat template 2. Calls SGLang native /generate endpoint 3. Extracts output_ids and output_token_logprobs 4. Parses tool calls from response 5. Converts response to standard format """ self.request_data = request_data # Get sampling params from request_data sampling_params = { "temperature": request_data.get("temperature", 0.7), "max_new_tokens": request_data.get("max_tokens", 4096), "top_p": request_data.get("top_p", 0.9), } # Format messages to text (includes tools in prompt) text_input = self._format_messages_to_text(messages, tools) # Call SGLang native endpoint client = self._get_sglang_client() try: response = await client.generate( text=text_input, sampling_params=sampling_params, return_logprob=True, ) except Exception as e: logger.error(f"SGLang native endpoint error: {e}") raise self.llm_request_finish_timestamp_ns = get_utc_timestamp_ns() # Store native response data self.response_data = response # Extract SGLang native data self.output_ids = response.get("output_ids") # output_token_logprobs is inside meta_info meta_info = response.get("meta_info", {}) self.output_token_logprobs = meta_info.get("output_token_logprobs") # Extract text response text_response = response.get("text", "") # Remove trailing end token if present if text_response.endswith("<|im_end|>"): text_response = text_response[:-10] # Parse tool calls from response parsed_tool_calls = self._parse_tool_calls(text_response) # Extract content (text without tool_call blocks) content_text = self._extract_content_without_tool_calls(text_response) # Determine finish reason meta_info = response.get("meta_info", {}) finish_reason_info = meta_info.get("finish_reason", {}) if isinstance(finish_reason_info, dict): finish_reason = finish_reason_info.get("type", "stop") else: finish_reason = "stop" # If we have tool calls, set finish_reason to tool_calls if parsed_tool_calls: finish_reason = "tool_calls" # Convert to standard ChatCompletionResponse format for compatibility # Build logprobs in OpenAI format from SGLang format logprobs_content = None if self.output_token_logprobs: logprobs_content = [] for i, lp_data in enumerate(self.output_token_logprobs): # SGLang format: [logprob, token_id, top_logprob] logprob = lp_data[0] if len(lp_data) > 0 else 0.0 token_id = lp_data[1] if len(lp_data) > 1 else 0 logprobs_content.append( ChatCompletionTokenLogprob( token=str(token_id), logprob=logprob, bytes=None, top_logprobs=[], ) ) choice_logprobs = ChoiceLogprobs(content=logprobs_content) if logprobs_content else None # Build chat completion response prompt_tokens = meta_info.get("prompt_tokens", 0) completion_tokens = len(self.output_ids) if self.output_ids else 0 self.chat_completions_response = ChatCompletionResponse( id=meta_info.get("id", "sglang-native"), created=int(time.time()), choices=[ Choice( finish_reason=finish_reason, index=0, message=ChoiceMessage( role="assistant", content=content_text if content_text else None, tool_calls=parsed_tool_calls if parsed_tool_calls else None, ), logprobs=choice_logprobs, ) ], usage=UsageStatistics( prompt_tokens=prompt_tokens, completion_tokens=completion_tokens, total_tokens=prompt_tokens + completion_tokens, ), ) # Extract content if content_text: self.content = [TextContent(text=content_text)] else: self.content = None # No reasoning content from native endpoint self.reasoning_content = None # Set tool calls self.tool_calls = parsed_tool_calls self.tool_call = parsed_tool_calls[0] if parsed_tool_calls else None # Set logprobs self.logprobs = choice_logprobs # Extract usage statistics self.usage.step_count = 1 self.usage.completion_tokens = completion_tokens self.usage.prompt_tokens = prompt_tokens self.usage.total_tokens = prompt_tokens + completion_tokens self.log_provider_trace(step_id=step_id, actor=actor) logger.info( f"SGLang native response: {len(self.output_ids or [])} tokens, " f"{len(self.output_token_logprobs or [])} logprobs, " f"{len(parsed_tool_calls)} tool calls" ) yield None return
{ "repo_id": "letta-ai/letta", "file_path": "letta/adapters/sglang_native_adapter.py", "license": "Apache License 2.0", "lines": 437, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
letta-ai/letta:letta/config_file.py
""" Letta Configuration File Support Loads hierarchical YAML config and maps it to environment variables. Supported top-level keys and their env var prefixes: letta: -> LETTA_* model: -> * (provider-prefixed: OPENAI_*, ANTHROPIC_*, etc.) tool: -> * (prefix-based: E2B_*, MCP_*, TOOL_*, etc.) datadog: -> DD_* Config file format: letta: telemetry: enable_datadog: true pg: host: localhost model: openai: api_key: sk-xxx anthropic: api_key: sk-yyy tool: e2b: api_key: xxx mcp: disable_stdio: true datadog: site: us5.datadoghq.com service: memgpt-server This maps to environment variables: LETTA_TELEMETRY_ENABLE_DATADOG=true LETTA_PG_HOST=localhost OPENAI_API_KEY=sk-xxx ANTHROPIC_API_KEY=sk-yyy E2B_API_KEY=xxx MCP_DISABLE_STDIO=true DD_SITE=us5.datadoghq.com DD_SERVICE=memgpt-server Config file locations (in order of precedence): 1. ~/.letta/conf.yaml 2. ./conf.yaml 3. LETTA_CONFIG_PATH environment variable """ import os from pathlib import Path from typing import Any import yaml # Config file locations DEFAULT_USER_CONFIG = Path.home() / ".letta" / "conf.yaml" DEFAULT_PROJECT_CONFIG = Path.cwd() / "conf.yaml" def load_config_file(config_path: str | Path | None = None) -> dict[str, Any]: """ Load configuration from YAML file. Args: config_path: Optional explicit path to config file Returns: Loaded config dict, or empty dict if no config found """ paths_to_check = [] # Check in order of precedence (lowest to highest) if DEFAULT_USER_CONFIG.exists(): paths_to_check.append(DEFAULT_USER_CONFIG) if DEFAULT_PROJECT_CONFIG.exists(): paths_to_check.append(DEFAULT_PROJECT_CONFIG) # Environment variable override env_path = os.environ.get("LETTA_CONFIG_PATH") if env_path and Path(env_path).exists(): paths_to_check.append(Path(env_path)) # Explicit path has highest precedence if config_path: p = Path(config_path) if p.exists(): paths_to_check.append(p) # Merge configs (later files override earlier) config: dict[str, Any] = {} for path in paths_to_check: try: with open(path, "r") as f: file_config = yaml.safe_load(f) if file_config: config = _deep_merge(config, file_config) except Exception: pass return config def _deep_merge(base: dict, override: dict) -> dict: """Deep merge two dicts, override values take precedence.""" result = base.copy() for key, value in override.items(): if key in result and isinstance(result[key], dict) and isinstance(value, dict): result[key] = _deep_merge(result[key], value) else: result[key] = value return result def _flatten_with_prefix(d: dict, prefix: str, env_vars: dict[str, str]) -> None: """Flatten a dict with a given prefix.""" for key, value in d.items(): env_key = f"{prefix}_{key}".upper() if prefix else key.upper() if isinstance(value, dict): _flatten_with_prefix(value, env_key, env_vars) elif value is not None: if isinstance(value, bool): env_vars[env_key] = str(value).lower() else: env_vars[env_key] = str(value) def _flatten_model_settings(d: dict, env_vars: dict[str, str]) -> None: """ Flatten model settings where nested keys become prefixes. model: openai: api_key: xxx -> OPENAI_API_KEY api_base: yyy -> OPENAI_API_BASE anthropic: api_key: zzz -> ANTHROPIC_API_KEY global_max_context_window_limit: 128000 -> GLOBAL_MAX_CONTEXT_WINDOW_LIMIT """ for key, value in d.items(): if isinstance(value, dict): # Nested provider config: openai.api_key -> OPENAI_API_KEY _flatten_with_prefix(value, key.upper(), env_vars) elif value is not None: # Top-level model setting env_key = key.upper() if isinstance(value, bool): env_vars[env_key] = str(value).lower() else: env_vars[env_key] = str(value) def _flatten_tool_settings(d: dict, env_vars: dict[str, str]) -> None: """ Flatten tool settings where nested keys become prefixes. tool: e2b: api_key: xxx -> E2B_API_KEY sandbox_template_id: y -> E2B_SANDBOX_TEMPLATE_ID mcp: disable_stdio: true -> MCP_DISABLE_STDIO tool_sandbox_timeout: 180 -> TOOL_SANDBOX_TIMEOUT """ for key, value in d.items(): if isinstance(value, dict): # Nested tool config: e2b.api_key -> E2B_API_KEY _flatten_with_prefix(value, key.upper(), env_vars) elif value is not None: # Top-level tool setting env_key = key.upper() if isinstance(value, bool): env_vars[env_key] = str(value).lower() else: env_vars[env_key] = str(value) def config_to_env_vars(config: dict[str, Any]) -> dict[str, str]: """ Convert hierarchical config to flat environment variables. Supports multiple top-level keys with different prefix behaviors: - letta: -> LETTA_* prefix - model: -> provider-prefixed (OPENAI_*, ANTHROPIC_*, etc.) - tool: -> prefix-based (E2B_*, MCP_*, TOOL_*, etc.) - datadog: -> DD_* prefix Args: config: Hierarchical config dict Returns: Dict of environment variable name -> value """ env_vars: dict[str, str] = {} # Handle 'letta' section with LETTA_ prefix if "letta" in config: _flatten_with_prefix(config["letta"], "LETTA", env_vars) # Handle 'model' section (provider-prefixed env vars) if "model" in config: _flatten_model_settings(config["model"], env_vars) # Handle 'tool' section (prefix-based env vars) if "tool" in config: _flatten_tool_settings(config["tool"], env_vars) # Handle 'datadog' section with DD_ prefix if "datadog" in config: _flatten_with_prefix(config["datadog"], "DD", env_vars) return env_vars def apply_config_to_env(config_path: str | Path | None = None) -> None: """ Load config file and apply values to environment variables. Environment variables already set take precedence over config file values. Args: config_path: Optional explicit path to config file """ config = load_config_file(config_path) if not config: return env_vars = config_to_env_vars(config) for key, value in env_vars.items(): # Only set if not already in environment (env vars take precedence) if key not in os.environ: os.environ[key] = value
{ "repo_id": "letta-ai/letta", "file_path": "letta/config_file.py", "license": "Apache License 2.0", "lines": 188, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
letta-ai/letta:letta/llm_api/sglang_native_client.py
""" SGLang Native Client for Letta. This client uses SGLang's native /generate endpoint instead of the OpenAI-compatible /v1/chat/completions endpoint. The native endpoint returns token IDs and per-token logprobs, which are essential for multi-turn RL training. The OpenAI-compatible endpoint only returns token strings, not IDs, making it impossible to accurately reconstruct the token sequence for training. """ from typing import Any, Dict, Optional import httpx from letta.log import get_logger logger = get_logger(__name__) class SGLangNativeClient: """Client for SGLang's native /generate endpoint. Unlike the OpenAI-compatible endpoint, this returns: - output_ids: List of token IDs - output_token_logprobs: List of [logprob, token_id, top_logprob] tuples This is essential for RL training where we need exact token IDs, not re-tokenized text. """ def __init__(self, base_url: str, api_key: Optional[str] = None): """ Initialize the SGLang native client. Args: base_url: Base URL for SGLang server (e.g., http://localhost:30000) api_key: Optional API key for authentication """ # Remove /v1 suffix if present - native endpoint is at root self.base_url = base_url.rstrip("/") if self.base_url.endswith("/v1"): self.base_url = self.base_url[:-3] self.api_key = api_key async def generate( self, text: str, sampling_params: Optional[Dict[str, Any]] = None, return_logprob: bool = True, ) -> Dict[str, Any]: """ Call SGLang's native /generate endpoint. Args: text: The formatted prompt text (with chat template applied) sampling_params: Sampling parameters (temperature, max_new_tokens, etc.) return_logprob: Whether to return logprobs (default True for RL training) Returns: Response dict with: - text: Generated text - output_ids: List of token IDs - output_token_logprobs: List of [logprob, token_id, top_logprob] tuples - meta_info: Metadata including finish_reason, prompt_tokens, etc. Example response: { "text": "Hello! How can I help?", "output_ids": [9707, 0, 2585, 646, 358, 1492, 30], "output_token_logprobs": [ [-0.005, 9707, null], [0.0, 0, null], ... ], "meta_info": { "finish_reason": {"type": "stop", "matched": 151645}, "prompt_tokens": 42, ... } } """ headers = {"Content-Type": "application/json"} if self.api_key: headers["Authorization"] = f"Bearer {self.api_key}" payload = { "text": text, "sampling_params": sampling_params or {}, "return_logprob": return_logprob, } async with httpx.AsyncClient(timeout=300.0) as client: response = await client.post( f"{self.base_url}/generate", json=payload, headers=headers, ) response.raise_for_status() return response.json() async def health_check(self) -> bool: """Check if the SGLang server is healthy.""" try: async with httpx.AsyncClient(timeout=10.0) as client: response = await client.get(f"{self.base_url}/health") return response.status_code == 200 except Exception: return False
{ "repo_id": "letta-ai/letta", "file_path": "letta/llm_api/sglang_native_client.py", "license": "Apache License 2.0", "lines": 89, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
letta-ai/letta:letta/schemas/llm_trace.py
"""Schema for LLM request/response traces stored in ClickHouse for analytics.""" from __future__ import annotations from datetime import datetime from typing import Optional from pydantic import Field from letta.helpers.datetime_helpers import get_utc_time from letta.schemas.letta_base import LettaBase class LLMTrace(LettaBase): """ LLM request/response trace for ClickHouse analytics. Stores LLM request/response payloads with denormalized columns for fast cost analytics queries (token usage by org/agent/model). Attributes: id (str): Unique trace identifier (UUID). organization_id (str): The organization this trace belongs to. project_id (str): The project this trace belongs to. agent_id (str): ID of the agent that made the request. run_id (str): ID of the run this trace is associated with. step_id (str): ID of the step that generated this trace. trace_id (str): OTEL trace ID for correlation. call_type (str): Type of LLM call ('agent_step', 'summarization', 'embedding'). provider (str): LLM provider name ('openai', 'anthropic', etc.). model (str): Model name/identifier used. request_size_bytes (int): Size of request_json in bytes. response_size_bytes (int): Size of response_json in bytes. prompt_tokens (int): Number of prompt tokens used. completion_tokens (int): Number of completion tokens generated. total_tokens (int): Total tokens (prompt + completion). latency_ms (int): Request latency in milliseconds. is_error (bool): Whether the request resulted in an error. error_type (str): Exception class name if error occurred. error_message (str): Error message if error occurred. request_json (str): Full request payload as JSON string. response_json (str): Full response payload as JSON string. created_at (datetime): Timestamp when the trace was created. """ __id_prefix__ = "llm_trace" # Primary identifier (UUID portion of ProviderTrace.id, prefix stripped for ClickHouse) id: str = Field(..., description="Trace UUID (strip 'provider_trace-' prefix to correlate)") # Context identifiers organization_id: str = Field(..., description="Organization this trace belongs to") project_id: Optional[str] = Field(default=None, description="Project this trace belongs to") agent_id: Optional[str] = Field(default=None, description="Agent that made the request") agent_tags: list[str] = Field(default_factory=list, description="Tags associated with the agent") run_id: Optional[str] = Field(default=None, description="Run this trace is associated with") step_id: Optional[str] = Field(default=None, description="Step that generated this trace") trace_id: Optional[str] = Field(default=None, description="OTEL trace ID for correlation") # Request metadata (queryable) call_type: str = Field(..., description="Type of LLM call: 'agent_step', 'summarization', 'embedding'") provider: str = Field(..., description="LLM provider: 'openai', 'anthropic', 'google_ai', etc.") model: str = Field(..., description="Model name/identifier") is_byok: bool = Field(default=False, description="Whether this request used BYOK (Bring Your Own Key)") # Size metrics request_size_bytes: int = Field(default=0, description="Size of request_json in bytes") response_size_bytes: int = Field(default=0, description="Size of response_json in bytes") # Token usage prompt_tokens: int = Field(default=0, description="Number of prompt tokens") completion_tokens: int = Field(default=0, description="Number of completion tokens") total_tokens: int = Field(default=0, description="Total tokens (prompt + completion)") # Cache and reasoning tokens (from LettaUsageStatistics) cached_input_tokens: Optional[int] = Field(default=None, description="Number of input tokens served from cache") cache_write_tokens: Optional[int] = Field(default=None, description="Number of tokens written to cache (Anthropic)") reasoning_tokens: Optional[int] = Field(default=None, description="Number of reasoning/thinking tokens generated") # Latency latency_ms: int = Field(default=0, description="Request latency in milliseconds") # Error tracking is_error: bool = Field(default=False, description="Whether the request resulted in an error") error_type: Optional[str] = Field(default=None, description="Exception class name if error") error_message: Optional[str] = Field(default=None, description="Error message if error") # Raw payloads (JSON strings) request_json: str = Field(..., description="Full request payload as JSON string") response_json: str = Field(..., description="Full response payload as JSON string") llm_config_json: str = Field(default="", description="LLM config as JSON string") # Billing context billing_plan_type: Optional[str] = Field(default=None, description="Subscription tier (e.g., 'basic', 'standard', 'max', 'enterprise')") billing_cost_source: Optional[str] = Field(default=None, description="Cost source: 'quota' or 'credits'") billing_customer_id: Optional[str] = Field(default=None, description="Customer ID for cross-referencing billing records") # Timestamp created_at: datetime = Field(default_factory=get_utc_time, description="When the trace was created") def to_clickhouse_row(self) -> tuple: """Convert to a tuple for ClickHouse insertion.""" return ( self.id, self.organization_id, self.project_id or "", self.agent_id or "", self.agent_tags, self.run_id or "", self.step_id or "", self.trace_id or "", self.call_type, self.provider, self.model, 1 if self.is_byok else 0, self.request_size_bytes, self.response_size_bytes, self.prompt_tokens, self.completion_tokens, self.total_tokens, self.cached_input_tokens, self.cache_write_tokens, self.reasoning_tokens, self.latency_ms, 1 if self.is_error else 0, self.error_type or "", self.error_message or "", self.request_json, self.response_json, self.llm_config_json, self.billing_plan_type or "", self.billing_cost_source or "", self.billing_customer_id or "", self.created_at, ) @classmethod def clickhouse_columns(cls) -> list[str]: """Return column names for ClickHouse insertion.""" return [ "id", "organization_id", "project_id", "agent_id", "agent_tags", "run_id", "step_id", "trace_id", "call_type", "provider", "model", "is_byok", "request_size_bytes", "response_size_bytes", "prompt_tokens", "completion_tokens", "total_tokens", "cached_input_tokens", "cache_write_tokens", "reasoning_tokens", "latency_ms", "is_error", "error_type", "error_message", "request_json", "response_json", "llm_config_json", "billing_plan_type", "billing_cost_source", "billing_customer_id", "created_at", ]
{ "repo_id": "letta-ai/letta", "file_path": "letta/schemas/llm_trace.py", "license": "Apache License 2.0", "lines": 150, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
letta-ai/letta:letta/schemas/memory_repo.py
"""Pydantic schemas for git-based memory repositories. These are used internally by the git-backed block/memory repository services. Note: REST "sync" request/response schemas were removed when we switched to clients interacting with repositories directly via git smart HTTP. """ from __future__ import annotations from datetime import datetime from typing import List, Optional from pydantic import Field from letta.schemas.letta_base import LettaBase class MemoryCommit(LettaBase): """Represents a commit in the memory repository.""" __id_prefix__ = "memcommit" sha: str = Field(..., description="Commit SHA (40-char hex).") parent_sha: Optional[str] = Field(None, description="Parent commit SHA.") message: str = Field(..., description="Commit message.") author_type: str = Field(..., description="Author type: agent, user, system.") author_id: str = Field(..., description="Author ID.") author_name: Optional[str] = Field(None, description="Human-readable author name.") timestamp: datetime = Field(..., description="Commit timestamp.") files_changed: List[str] = Field(default_factory=list, description="List of changed file paths.") additions: int = Field(default=0, description="Number of lines/chars added.") deletions: int = Field(default=0, description="Number of lines/chars deleted.") class FileChange(LettaBase): """Represents a file change for committing.""" path: str = Field(..., description="File path within repository.") content: Optional[str] = Field(None, description="New file content (None for delete).") change_type: str = Field(default="modify", description="Change type: add, modify, delete.")
{ "repo_id": "letta-ai/letta", "file_path": "letta/schemas/memory_repo.py", "license": "Apache License 2.0", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
letta-ai/letta:letta/server/rest_api/routers/v1/git_http.py
"""Git HTTP Smart Protocol endpoints (proxied to memfs service). This module proxies `/v1/git/*` requests to the external memfs service, which handles git smart HTTP protocol (clone, push, pull). Example: git clone http://localhost:8283/v1/git/{agent_id}/state.git Routes (smart HTTP): GET /v1/git/{agent_id}/state.git/info/refs?service=git-upload-pack POST /v1/git/{agent_id}/state.git/git-upload-pack GET /v1/git/{agent_id}/state.git/info/refs?service=git-receive-pack POST /v1/git/{agent_id}/state.git/git-receive-pack Post-push sync to PostgreSQL is triggered from the proxy route after a successful `git-receive-pack`. """ from __future__ import annotations import asyncio from typing import Dict, Iterable, Optional import httpx from fastapi import APIRouter, Depends, Request from fastapi.responses import JSONResponse, StreamingResponse from starlette.background import BackgroundTask from letta.log import get_logger from letta.server.rest_api.dependencies import HeaderParams, get_headers, get_letta_server from letta.services.memory_repo.path_mapping import memory_block_label_from_markdown_path logger = get_logger(__name__) _background_tasks: set[asyncio.Task] = set() def _is_syncable_block_markdown_path(path: str) -> bool: """Return whether a markdown path should be mirrored into block cache. Special-case skills so only skill definitions are mirrored: - sync `skills/{skill_name}/SKILL.md` as label `skills/{skill_name}` - ignore all other markdown under `skills/` """ return memory_block_label_from_markdown_path(path) is not None router = APIRouter(prefix="/git", tags=["git"], include_in_schema=False) # Global storage for the server instance (set during app startup) _server_instance = None def set_server_instance(server) -> None: """Set the Letta server instance for git operations. Called during app startup.""" global _server_instance _server_instance = server async def _sync_after_push(actor_id: str, agent_id: str) -> None: """Sync blocks to PostgreSQL after a successful push. GCS sync is handled by the memfs service. This function syncs the block contents to PostgreSQL for caching/querying. """ if _server_instance is None: logger.warning("Server instance not set; cannot sync after push") return try: actor = await _server_instance.user_manager.get_actor_by_id_async(actor_id) except Exception: logger.exception("Failed to resolve actor for post-push sync (actor_id=%s)", actor_id) return org_id = actor.organization_id # Sync blocks to Postgres (if using GitEnabledBlockManager). # # Keep the same pattern as API-driven edits: read from the source of truth # in object storage after persisting the pushed refs/objects, rather than # relying on a working tree checkout under repo_path/. from letta.services.block_manager_git import GitEnabledBlockManager if not isinstance(_server_instance.block_manager, GitEnabledBlockManager): return # Retry with backoff to handle race condition where GCS upload is still in progress # after git-receive-pack returns. The webhook fires immediately but commit objects # may not be fully uploaded yet. files = {} max_retries = 3 for attempt in range(max_retries): try: files = await _server_instance.memory_repo_manager.git.get_files( agent_id=agent_id, org_id=org_id, ref="HEAD", ) logger.info("get_files returned %d files (attempt %d)", len(files), attempt + 1) break except Exception as e: if attempt < max_retries - 1: wait_time = 2**attempt # 1s, 2s, 4s logger.warning("Failed to read repo files (attempt %d/%d), retrying in %ds: %s", attempt + 1, max_retries, wait_time, e) await asyncio.sleep(wait_time) else: logger.exception("Failed to read repo files after %d retries (agent=%s)", max_retries, agent_id) expected_labels = set() from letta.services.memory_repo.block_markdown import parse_block_markdown md_file_paths = sorted([file_path for file_path in files if _is_syncable_block_markdown_path(file_path)]) nested_md_file_paths = [file_path for file_path in md_file_paths if "/" in file_path[:-3]] logger.info( "Post-push sync file scan: agent=%s total_files=%d md_files=%d nested_md_files=%d sample_md_paths=%s", agent_id, len(files), len(md_file_paths), len(nested_md_file_paths), md_file_paths[:10], ) synced = 0 for file_path, content in files.items(): if not _is_syncable_block_markdown_path(file_path): continue label = memory_block_label_from_markdown_path(file_path) if label is None: continue expected_labels.add(label) # Parse frontmatter to extract metadata alongside value parsed = parse_block_markdown(content) try: await _server_instance.block_manager._sync_block_to_postgres( agent_id=agent_id, label=label, value=parsed["value"], actor=actor, description=parsed.get("description"), limit=parsed.get("limit"), read_only=parsed.get("read_only"), metadata=parsed.get("metadata"), ) synced += 1 logger.info("Synced block %s to PostgreSQL", label) except Exception: logger.exception( "Failed to sync block %s to PostgreSQL (agent=%s) [path=%s nested=%s]", label, agent_id, file_path, "/" in label, ) if synced == 0: logger.warning("No *.md files found in repo HEAD during post-push sync (agent=%s)", agent_id) else: # Detach blocks that were removed in git. # # We treat git as the source of truth for which blocks are attached to # this agent. If a *.md file disappears from HEAD, detach the # corresponding block from the agent in Postgres. try: existing_blocks = await _server_instance.agent_manager.list_agent_blocks_async( agent_id=agent_id, actor=actor, before=None, after=None, limit=1000, ascending=True, ) existing_by_label = {b.label: b for b in existing_blocks} removed_labels = set(existing_by_label.keys()) - expected_labels for label in sorted(removed_labels): block = existing_by_label.get(label) if not block: continue await _server_instance.agent_manager.detach_block_async( agent_id=agent_id, block_id=block.id, actor=actor, ) logger.info("Detached block %s from agent (removed from git)", label) except Exception: logger.exception("Failed detaching removed blocks during post-push sync (agent=%s)", agent_id) def _parse_agent_id_from_repo_path(path: str) -> Optional[str]: """Extract agent_id from a git HTTP path. Expected path form: - {agent_id}/state.git/... """ parts = path.strip("/").split("/") if len(parts) < 2: return None if parts[1] != "state.git": return None return parts[0] def _filter_out_hop_by_hop_headers(headers: Iterable[tuple[str, str]]) -> Dict[str, str]: # RFC 7230 hop-by-hop headers that should not be forwarded hop_by_hop = { "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailers", "transfer-encoding", "upgrade", } out: Dict[str, str] = {} for k, v in headers: lk = k.lower() if lk in hop_by_hop: continue out[k] = v return out def _get_memfs_service_url() -> Optional[str]: """Get the memfs service URL from settings, if configured.""" from letta.settings import settings return settings.memfs_service_url @router.api_route("/{path:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]) # pragma: no cover async def proxy_git_http( path: str, request: Request, server=Depends(get_letta_server), headers: HeaderParams = Depends(get_headers), ): """Proxy `/v1/git/*` requests to the memfs service. Requires LETTA_MEMFS_SERVICE_URL to be configured. """ memfs_url = _get_memfs_service_url() if not memfs_url: return JSONResponse( status_code=501, content={ "detail": "git HTTP requires memfs service (LETTA_MEMFS_SERVICE_URL not configured)", }, ) # Proxy to external memfs service url = f"{memfs_url.rstrip('/')}/git/{path}" logger.info("proxy_git_http: using memfs service at %s", memfs_url) req_headers = _filter_out_hop_by_hop_headers(request.headers.items()) # Avoid sending FastAPI host/length; httpx will compute req_headers.pop("host", None) req_headers.pop("content-length", None) # Resolve org_id from the authenticated actor + agent and forward to memfs. agent_id = _parse_agent_id_from_repo_path(path) if agent_id is not None: actor = await server.user_manager.get_actor_or_default_async(actor_id=headers.actor_id) # Authorization check: ensure the actor can access this agent. await server.agent_manager.get_agent_by_id_async(agent_id=agent_id, actor=actor, include_relationships=[]) # Ensure we set exactly one X-Organization-Id header (avoid duplicate casing). for k in list(req_headers.keys()): if k.lower() == "x-organization-id": req_headers.pop(k, None) # Use the authenticated actor's org; AgentState may not carry an organization field. req_headers["X-Organization-Id"] = actor.organization_id logger.info( "proxy_git_http: method=%s path=%s parsed_agent_id=%s actor_id=%s has_user_id_hdr=%s x_org_hdr=%s", request.method, path, agent_id, headers.actor_id, bool(request.headers.get("user_id")), req_headers.get("X-Organization-Id") or req_headers.get("x-organization-id"), ) async def _body_iter(): async for chunk in request.stream(): yield chunk client = httpx.AsyncClient(timeout=None) req = client.build_request( method=request.method, url=url, params=request.query_params, headers=req_headers, content=_body_iter() if request.method not in {"GET", "HEAD"} else None, ) upstream = await client.send(req, stream=True) resp_headers = _filter_out_hop_by_hop_headers(upstream.headers.items()) # If this was a push, trigger our sync. if request.method == "POST" and path.endswith("git-receive-pack") and upstream.status_code < 400: agent_id = _parse_agent_id_from_repo_path(path) if agent_id is not None: try: actor = await server.user_manager.get_actor_or_default_async(actor_id=headers.actor_id) # Authorization check: ensure the actor can access this agent. await server.agent_manager.get_agent_by_id_async(agent_id=agent_id, actor=actor, include_relationships=[]) task = asyncio.create_task(_sync_after_push(actor.id, agent_id)) _background_tasks.add(task) task.add_done_callback(_background_tasks.discard) except Exception: logger.exception("Failed to trigger post-push sync (agent_id=%s)", agent_id) async def _aclose_upstream_and_client() -> None: try: await upstream.aclose() finally: await client.aclose() return StreamingResponse( upstream.aiter_raw(), status_code=upstream.status_code, headers=resp_headers, media_type=upstream.headers.get("content-type"), background=BackgroundTask(_aclose_upstream_and_client), )
{ "repo_id": "letta-ai/letta", "file_path": "letta/server/rest_api/routers/v1/git_http.py", "license": "Apache License 2.0", "lines": 274, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
letta-ai/letta:letta/services/agent_generate_completion_manager.py
"""Manager for handling direct LLM completions using agent configuration.""" from typing import TYPE_CHECKING, Any, Dict, Optional from letta.errors import LLMError from letta.llm_api.llm_client import LLMClient from letta.log import get_logger from letta.schemas.enums import AgentType, MessageRole from letta.schemas.letta_message_content import TextContent from letta.schemas.message import Message from letta.schemas.usage import LettaUsageStatistics # Tool name used for structured output via tool forcing STRUCTURED_OUTPUT_TOOL_NAME = "structured_output" if TYPE_CHECKING: from letta.orm import User from letta.schemas.llm_config import LLMConfig from letta.server.server import SyncServer logger = get_logger(__name__) def _schema_to_tool_definition(schema: Dict[str, Any]) -> Dict[str, Any]: """ Convert a JSON schema into a tool definition for forced tool calling. Args: schema: JSON schema object with 'properties' and optionally 'required' Returns: Tool definition dict compatible with OpenAI/Anthropic function calling format """ return { "name": STRUCTURED_OUTPUT_TOOL_NAME, "description": "Returns a structured response matching the requested schema.", "parameters": { "type": "object", "properties": schema.get("properties", {}), "required": schema.get("required", list(schema.get("properties", {}).keys())), }, } class GenerateResponse: """Response from direct LLM generation.""" def __init__(self, content: str, model: str, usage: LettaUsageStatistics): self.content = content self.model = model self.usage = usage class AgentGenerateCompletionManager: """Manager for handling direct LLM completions using agent configuration.""" def __init__(self, server: "SyncServer"): """ Initialize the agent generate completion manager. Args: server: The SyncServer instance for accessing managers """ self.server = server self.agent_manager = server.agent_manager self.provider_manager = server.provider_manager async def generate_completion_with_agent_config_async( self, agent_id: str, prompt: str, actor: "User", system_prompt: Optional[str] = None, override_model: Optional[str] = None, response_schema: Optional[Dict[str, Any]] = None, ) -> GenerateResponse: """ Generate a completion directly from the LLM provider using the agent's configuration. This method makes a direct request to the LLM provider without any agent processing: - No memory or context retrieval - No tool calling (unless response_schema is provided) - No message persistence - No agent state modification Args: agent_id: The agent ID whose configuration to use prompt: The prompt/message to send to the LLM actor: The user making the request system_prompt: Optional system prompt to prepend to the conversation override_model: Optional model handle to override the agent's default (e.g., 'openai/gpt-4', 'anthropic/claude-3-5-sonnet') response_schema: Optional JSON schema for structured output. When provided, the LLM will be forced to return a response matching this schema via tool calling. Returns: GenerateResponse with content, model, and usage statistics. When response_schema is provided, content will be the JSON string matching the schema. Raises: NoResultFound: If agent not found HandleNotFoundError: If override_model is invalid LLMError: If LLM provider error occurs """ # 1. Validate agent exists and user has access agent = await self.agent_manager.get_agent_by_id_async( agent_id, actor, include_relationships=[], ) # 2. Get LLM config (with optional override) llm_config: "LLMConfig" = agent.llm_config if override_model: # Get full LLM config for the override model # This ensures we get the right provider, endpoint, credentials, etc. llm_config = await self.server.get_llm_config_from_handle_async( actor=actor, handle=override_model, ) logger.info( f"Generating completion for agent {agent_id}", extra={ "agent_id": str(agent_id), "override_model": override_model, "prompt_length": len(prompt), "has_system_prompt": system_prompt is not None, "has_response_schema": response_schema is not None, "model": llm_config.model, }, ) # 3. Build messages from prompt and optional system_prompt letta_messages = [] # Always add a system message (required by some providers like Anthropic) # Use provided system_prompt or minimal default (empty strings not allowed with cache_control) letta_messages.append( Message( role=MessageRole.system, content=[TextContent(text=system_prompt if system_prompt else "You are a helpful assistant.")], ) ) # Add user prompt letta_messages.append( Message( role=MessageRole.user, content=[TextContent(text=prompt)], ) ) # 4. Create LLM client for the provider llm_client = LLMClient.create( provider_type=llm_config.model_endpoint_type, actor=actor, ) if llm_client is None: raise LLMError(f"Unsupported provider type: {llm_config.model_endpoint_type}") # 5. Build request data # If response_schema is provided, create a tool and force the model to call it tools = None force_tool_call = None if response_schema: tools = [_schema_to_tool_definition(response_schema)] force_tool_call = STRUCTURED_OUTPUT_TOOL_NAME # TODO: create a separate agent type effective_agent_type = AgentType.split_thread_agent if response_schema else agent.agent_type request_data = llm_client.build_request_data( agent_type=effective_agent_type, messages=letta_messages, llm_config=llm_config, tools=tools, force_tool_call=force_tool_call, ) # 6. Make direct LLM request response_data = await llm_client.request_async(request_data, llm_config) # 7. Convert to standard chat completion format chat_completion = await llm_client.convert_response_to_chat_completion( response_data, letta_messages, llm_config, ) # 8. Extract response content content = "" if chat_completion.choices and len(chat_completion.choices) > 0: message = chat_completion.choices[0].message if response_schema: # When using structured output, extract from tool call arguments if message.tool_calls and len(message.tool_calls) > 0: # The tool call arguments contain the structured output as JSON string content = message.tool_calls[0].function.arguments else: # Fallback: some providers may return in content even with tool forcing content = message.content or "" logger.warning( "Expected tool call for structured output but got content response", extra={"agent_id": str(agent_id), "content_length": len(content)}, ) else: content = message.content or "" # 9. Extract usage statistics usage = llm_client.extract_usage_statistics(response_data, llm_config) # 10. Build and return response return GenerateResponse( content=content, model=llm_config.model, usage=usage, )
{ "repo_id": "letta-ai/letta", "file_path": "letta/services/agent_generate_completion_manager.py", "license": "Apache License 2.0", "lines": 185, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
letta-ai/letta:letta/services/block_manager_git.py
"""Git-enabled block manager that uses object storage as source of truth. When an agent has the GIT_MEMORY_ENABLED_TAG tag, block operations: 1. Write to git (GCS) first - source of truth 2. Update PostgreSQL as cache This provides full version history while maintaining fast reads from PostgreSQL. """ import time from typing import List, Optional from letta.constants import CORE_MEMORY_BLOCK_CHAR_LIMIT from letta.log import get_logger from letta.orm.block import Block as BlockModel from letta.otel.tracing import trace_method from letta.schemas.block import Block as PydanticBlock, BlockUpdate, CreateBlock from letta.schemas.user import User as PydanticUser from letta.server.db import db_registry from letta.services.block_manager import BlockManager from letta.services.memory_repo import MemfsClient from letta.utils import enforce_types logger = get_logger(__name__) # Tag that enables git-based memory for an agent GIT_MEMORY_ENABLED_TAG = "git-memory-enabled" class GitEnabledBlockManager(BlockManager): """Block manager that uses git as source of truth when enabled for an agent. For agents with the GIT_MEMORY_ENABLED_TAG: - All writes go to git first, then sync to PostgreSQL - Reads come from PostgreSQL (cache) for performance - Full version history is maintained in git For agents without the tag: - Behaves exactly like the standard BlockManager """ def __init__(self, memory_repo_manager: Optional[MemfsClient] = None): """Initialize the git-enabled block manager. Args: memory_repo_manager: The memory repo manager for git operations. If None, git features are disabled. """ super().__init__() self.memory_repo_manager = memory_repo_manager async def _is_git_enabled_for_agent(self, agent_id: str, actor: PydanticUser) -> bool: """Check if an agent has git-based memory enabled.""" if self.memory_repo_manager is None: return False # Check if agent has the git-memory-enabled tag async with db_registry.async_session() as session: from sqlalchemy import select from letta.orm.agents_tags import AgentsTags result = await session.execute( select(AgentsTags).where( AgentsTags.agent_id == agent_id, AgentsTags.tag == GIT_MEMORY_ENABLED_TAG, ) ) return result.scalar_one_or_none() is not None async def _get_agent_id_for_block(self, block_id: str, actor: PydanticUser) -> Optional[str]: """Get the agent ID that owns a block.""" async with db_registry.async_session() as session: from sqlalchemy import select from letta.orm.blocks_agents import BlocksAgents result = await session.execute(select(BlocksAgents.agent_id).where(BlocksAgents.block_id == block_id)) row = result.first() return row[0] if row else None async def _sync_block_to_postgres( self, agent_id: str, label: str, value: str, actor: PydanticUser, description: Optional[str] = None, limit: Optional[int] = None, read_only: Optional[bool] = None, metadata: Optional[dict] = None, ) -> PydanticBlock: """Sync a block from git to PostgreSQL cache.""" async with db_registry.async_session() as session: from sqlalchemy import select from letta.orm.blocks_agents import BlocksAgents # Find existing block for this agent+label result = await session.execute( select(BlockModel) .join(BlocksAgents, BlocksAgents.block_id == BlockModel.id) .where( BlocksAgents.agent_id == agent_id, BlockModel.label == label, BlockModel.organization_id == actor.organization_id, ) ) block = result.scalar_one_or_none() if block: # Update existing block block.value = value if description is not None: block.description = description if limit is not None: block.limit = limit if read_only is not None: block.read_only = read_only if metadata is not None: block.metadata_ = metadata await block.update_async(db_session=session, actor=actor) else: # Create new block and link to agent in a single transaction from letta.schemas.block import BaseBlock block = BlockModel( id=BaseBlock.generate_id(), label=label, value=value, description=description or f"{label} block", limit=limit or CORE_MEMORY_BLOCK_CHAR_LIMIT, read_only=read_only or False, metadata_=metadata or {}, organization_id=actor.organization_id, ) await block.create_async(db_session=session, actor=actor, no_commit=True) # Link to agent from letta.orm.blocks_agents import BlocksAgents blocks_agents = BlocksAgents( agent_id=agent_id, block_id=block.id, block_label=label, ) session.add(blocks_agents) await session.commit() return block.to_pydantic() async def _delete_block_from_postgres( self, agent_id: str, label: str, actor: PydanticUser, ) -> None: """Delete a block from PostgreSQL cache.""" async with db_registry.async_session() as session: from sqlalchemy import delete, select from letta.orm.blocks_agents import BlocksAgents # Find block for this agent+label result = await session.execute( select(BlockModel) .join(BlocksAgents, BlocksAgents.block_id == BlockModel.id) .where( BlocksAgents.agent_id == agent_id, BlockModel.label == label, BlockModel.organization_id == actor.organization_id, ) ) block = result.scalar_one_or_none() if block: # Delete from blocks_agents await session.execute(delete(BlocksAgents).where(BlocksAgents.block_id == block.id)) # Delete the block await block.hard_delete_async(db_session=session, actor=actor) # ========================================================================= # Override BlockManager methods to add git integration # ========================================================================= @enforce_types @trace_method async def update_block_async( self, block_id: str, block_update: BlockUpdate, actor: PydanticUser, ) -> PydanticBlock: """Update a block. If git-enabled, commits to git first.""" t_start = time.perf_counter() logger.info(f"[GIT_PERF] update_block_async START block_id={block_id}") # Get agent ID for this block t0 = time.perf_counter() agent_id = await self._get_agent_id_for_block(block_id, actor) logger.info(f"[GIT_PERF] _get_agent_id_for_block took {(time.perf_counter() - t0) * 1000:.2f}ms agent_id={agent_id}") # Check if git is enabled for this agent t0 = time.perf_counter() git_enabled = agent_id and await self._is_git_enabled_for_agent(agent_id, actor) logger.info(f"[GIT_PERF] _is_git_enabled_for_agent took {(time.perf_counter() - t0) * 1000:.2f}ms enabled={git_enabled}") if git_enabled: # Get current block to get label t0 = time.perf_counter() async with db_registry.async_session() as session: block = await BlockModel.read_async(db_session=session, identifier=block_id, actor=actor) label = block.label logger.info(f"[GIT_PERF] BlockModel.read_async took {(time.perf_counter() - t0) * 1000:.2f}ms label={label}") # 1. Commit to git (source of truth) # Resolve each field: use the update value if provided, else fall back # to the current block value from Postgres. resolved_value = block_update.value if block_update.value is not None else block.value resolved_description = block_update.description if block_update.description is not None else block.description resolved_limit = block_update.limit if block_update.limit is not None else block.limit resolved_read_only = block_update.read_only if block_update.read_only is not None else block.read_only resolved_metadata = block_update.metadata if block_update.metadata is not None else (block.metadata_ or {}) t0 = time.perf_counter() commit = await self.memory_repo_manager.update_block_async( agent_id=agent_id, label=label, value=resolved_value, actor=actor, message=f"Update {label} block", description=resolved_description, limit=resolved_limit, read_only=resolved_read_only, metadata=resolved_metadata, ) git_time = (time.perf_counter() - t0) * 1000 logger.info(f"[GIT_PERF] memory_repo_manager.update_block_async took {git_time:.2f}ms commit={commit.sha[:8]}") # 2. Sync to PostgreSQL cache t0 = time.perf_counter() result = await self._sync_block_to_postgres( agent_id=agent_id, label=label, value=block_update.value or block.value, actor=actor, description=block_update.description, limit=block_update.limit, ) logger.info(f"[GIT_PERF] _sync_block_to_postgres took {(time.perf_counter() - t0) * 1000:.2f}ms") # Block tags are not stored in git (today); they remain Postgres-only metadata. # Preserve legacy behavior by updating tags in Postgres even for git-enabled agents. if block_update.tags is not None: async with db_registry.async_session() as session: from letta.orm.blocks_tags import BlocksTags await BlockManager._replace_block_pivot_rows_async( session, BlocksTags.__table__, block_id, [{"block_id": block_id, "tag": tag, "organization_id": actor.organization_id} for tag in block_update.tags], ) result.tags = block_update.tags else: async with db_registry.async_session() as session: from sqlalchemy import select from letta.orm.blocks_tags import BlocksTags tags_result = await session.execute(select(BlocksTags.tag).where(BlocksTags.block_id == block_id)) result.tags = [row[0] for row in tags_result.fetchall()] total_time = (time.perf_counter() - t_start) * 1000 logger.info(f"[GIT_PERF] update_block_async TOTAL {total_time:.2f}ms (git-enabled path)") return result else: # Fall back to standard PostgreSQL-only behavior t0 = time.perf_counter() result = await super().update_block_async(block_id, block_update, actor) logger.info(f"[GIT_PERF] super().update_block_async took {(time.perf_counter() - t0) * 1000:.2f}ms") total_time = (time.perf_counter() - t_start) * 1000 logger.info(f"[GIT_PERF] update_block_async TOTAL {total_time:.2f}ms (postgres-only path)") return result @enforce_types @trace_method async def create_block_async( self, block: CreateBlock, actor: PydanticUser, agent_id: Optional[str] = None, ) -> PydanticBlock: """Create a block. If git-enabled and agent_id provided, commits to git first.""" # Check if git is enabled for this agent if agent_id and await self._is_git_enabled_for_agent(agent_id, actor): # 1. Commit to git (source of truth) commit = await self.memory_repo_manager.create_block_async( agent_id=agent_id, block=PydanticBlock( label=block.label, value=block.value, description=block.description, limit=block.limit or CORE_MEMORY_BLOCK_CHAR_LIMIT, ), actor=actor, message=f"Create {block.label} block", ) logger.info(f"Git commit for block create: {commit.sha[:8]}") # 2. Sync to PostgreSQL cache return await self._sync_block_to_postgres( agent_id=agent_id, label=block.label, value=block.value, actor=actor, description=block.description, limit=block.limit, ) else: # Fall back to standard PostgreSQL-only behavior return await super().create_block_async(block, actor) @enforce_types @trace_method async def delete_block_async(self, block_id: str, actor: PydanticUser) -> None: """Delete a block. If git-enabled, commits deletion to git first.""" # Get agent ID and label for this block agent_id = await self._get_agent_id_for_block(block_id, actor) if agent_id and await self._is_git_enabled_for_agent(agent_id, actor): # Get block label before deleting async with db_registry.async_session() as session: block = await BlockModel.read_async(db_session=session, identifier=block_id, actor=actor) label = block.label # 1. Commit deletion to git (source of truth) commit = await self.memory_repo_manager.delete_block_async( agent_id=agent_id, label=label, actor=actor, message=f"Delete {label} block", ) logger.info(f"Git commit for block delete: {commit.sha[:8]}") # 2. Delete from PostgreSQL cache await self._delete_block_from_postgres(agent_id, label, actor) else: # Fall back to standard PostgreSQL-only behavior await super().delete_block_async(block_id, actor) # ========================================================================= # Git-specific methods # ========================================================================= @enforce_types @trace_method async def enable_git_memory_for_agent( self, agent_id: str, actor: PydanticUser, ) -> None: """Enable git-based memory for an agent. This: 1. Adds the GIT_MEMORY_ENABLED_TAG to the agent 2. Creates a git repo for the agent 3. Commits current blocks as initial state """ if self.memory_repo_manager is None: raise ValueError("Memory repo manager not configured") # If already enabled (tag exists), ensure the repo exists. # # This matters because tags can be added via the agent update endpoint. In that # flow, the tag may be persisted before the git repo is created. We treat the # tag as the source-of-truth "desired state" and backfill the repo if missing. if await self._is_git_enabled_for_agent(agent_id, actor): try: # Fast check: does the repo exist in backing storage? await self.memory_repo_manager.git.get_head_sha(agent_id=agent_id, org_id=actor.organization_id) # Repo exists - check if all blocks are present blocks = await self.get_blocks_by_agent_async(agent_id, actor) repo_files = await self.memory_repo_manager.git.get_files(agent_id=agent_id, org_id=actor.organization_id, ref="HEAD") # Check which blocks are missing from repo missing_blocks = [] for block in blocks: expected_path = f"{block.label}.md" if expected_path not in repo_files: missing_blocks.append(block) if missing_blocks: logger.warning( "Git memory repo exists but missing %d/%d blocks for agent %s; backfilling", len(missing_blocks), len(blocks), agent_id, ) # Commit missing blocks for block in missing_blocks: await self.memory_repo_manager.update_block_async( agent_id=agent_id, label=block.label, value=block.value or "", actor=actor, message=f"Backfill {block.label} block", ) logger.info(f"Backfilled {len(missing_blocks)} missing blocks for agent {agent_id}") else: logger.info(f"Git memory already enabled for agent {agent_id}") return except FileNotFoundError: logger.warning( "Git memory tag present but repo missing for agent %s; creating repo from current blocks", agent_id, ) blocks = await self.get_blocks_by_agent_async(agent_id, actor) # Ensure blocks have path-based labels before creating repo. # All existing blocks were rendered in the system prompt, so they # need the system/ prefix. Check startswith (not "/" presence) # because labels like "letta/letta_town" contain "/" but aren't # yet in the system/ namespace. for block in blocks: if not block.label.startswith("system/"): old_label = block.label new_label = f"system/{block.label}" async with db_registry.async_session() as session: block_orm = await BlockModel.read_async(db_session=session, identifier=block.id, actor=actor) block_orm.label = new_label await session.commit() block.label = new_label logger.info(f"Transformed block label '{old_label}' -> '{new_label}' during backfill for agent {agent_id}") await self.memory_repo_manager.create_repo_async( agent_id=agent_id, actor=actor, initial_blocks=blocks, ) logger.info(f"Backfilled git repo for agent {agent_id} with {len(blocks)} blocks") return # Get current blocks for this agent and transform labels to path-based. # All existing blocks were in the system prompt, so they need the system/ prefix. # Use startswith check (not "/" presence) because labels like "letta/letta_town" # contain "/" but aren't yet in the system/ namespace. blocks = await self.get_blocks_by_agent_async(agent_id, actor) for block in blocks: if not block.label.startswith("system/"): old_label = block.label new_label = f"system/{block.label}" logger.info(f"Transforming block label '{old_label}' -> '{new_label}' for agent {agent_id}") # Rename in PostgreSQL directly async with db_registry.async_session() as session: block_orm = await BlockModel.read_async(db_session=session, identifier=block.id, actor=actor) block_orm.label = new_label await session.commit() block.label = new_label # Create git repo with path-based blocks await self.memory_repo_manager.create_repo_async( agent_id=agent_id, actor=actor, initial_blocks=blocks, ) # Add the tag async with db_registry.async_session() as session: from letta.orm.agents_tags import AgentsTags tag = AgentsTags( agent_id=agent_id, tag=GIT_MEMORY_ENABLED_TAG, ) session.add(tag) await session.commit() logger.info(f"Enabled git memory for agent {agent_id} with {len(blocks)} blocks") @enforce_types @trace_method async def disable_git_memory_for_agent( self, agent_id: str, actor: PydanticUser, ) -> None: """Disable git-based memory for an agent. This removes the tag but keeps the git repo for historical reference. """ async with db_registry.async_session() as session: from sqlalchemy import delete from letta.orm.agents_tags import AgentsTags await session.execute( delete(AgentsTags).where( AgentsTags.agent_id == agent_id, AgentsTags.tag == GIT_MEMORY_ENABLED_TAG, ) ) logger.info(f"Disabled git memory for agent {agent_id}") @enforce_types @trace_method async def get_block_at_commit( self, agent_id: str, label: str, commit_sha: str, actor: PydanticUser, ) -> Optional[PydanticBlock]: """Get a block's value at a specific commit. This is a git-only operation that reads from version history. """ if self.memory_repo_manager is None: raise ValueError("Memory repo manager not configured") return await self.memory_repo_manager.get_block_async( agent_id=agent_id, label=label, actor=actor, ref=commit_sha, ) @enforce_types @trace_method async def get_block_history( self, agent_id: str, actor: PydanticUser, label: Optional[str] = None, limit: int = 50, ): """Get commit history for an agent's memory blocks. Args: agent_id: Agent ID actor: User performing the operation label: Optional block label to filter by limit: Maximum commits to return Returns: List of MemoryCommit objects """ if self.memory_repo_manager is None: raise ValueError("Memory repo manager not configured") path = f"{label}.md" if label else None return await self.memory_repo_manager.get_history_async( agent_id=agent_id, actor=actor, path=path, limit=limit, ) @enforce_types @trace_method async def sync_blocks_from_git( self, agent_id: str, actor: PydanticUser, ) -> List[PydanticBlock]: """Sync all blocks from git to PostgreSQL. Use this to rebuild the PostgreSQL cache from git source of truth. """ if self.memory_repo_manager is None: raise ValueError("Memory repo manager not configured") # Get all blocks from git git_blocks = await self.memory_repo_manager.get_blocks_async( agent_id=agent_id, actor=actor, ) # Sync each to PostgreSQL synced_blocks = [] for block in git_blocks: synced = await self._sync_block_to_postgres( agent_id=agent_id, label=block.label, value=block.value, actor=actor, description=block.description, limit=block.limit, ) synced_blocks.append(synced) logger.info(f"Synced {len(synced_blocks)} blocks from git for agent {agent_id}") return synced_blocks
{ "repo_id": "letta-ai/letta", "file_path": "letta/services/block_manager_git.py", "license": "Apache License 2.0", "lines": 514, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
letta-ai/letta:letta/services/credit_verification_service.py
import logging import os import httpx from letta.errors import InsufficientCreditsError logger = logging.getLogger(__name__) class CreditVerificationService: """Service for verifying organization credit balance before agent execution.""" def __init__(self): self.endpoint = os.getenv("STEP_ORCHESTRATOR_ENDPOINT") self.auth_key = os.getenv("STEP_COMPLETE_KEY") async def verify_credits(self, organization_id: str, agent_id: str) -> bool: """ Check if an organization has enough credits to proceed with a specific agent. Args: organization_id: The organization's core ID agent_id: The agent's ID (used to determine model-specific costs) Returns True if credits are available or if the service is not configured. Raises InsufficientCreditsError if no credits remain. """ if not self.endpoint or not self.auth_key: return True try: headers = {} if self.auth_key: headers["Authorization"] = f"Bearer {self.auth_key}" async with httpx.AsyncClient(timeout=5.0) as client: response = await client.get( f"{self.endpoint}/validate/core-organizations/{organization_id}/agents/{agent_id}", headers=headers, ) response.raise_for_status() data = response.json() if not data.get("hasMoreCredits", True): # We need to test why this is firing in production. logger.error( f"[CREDIT VERIFICATION] Insufficient credits would have fired for organization {organization_id} and agent {agent_id}" ) return True return True except InsufficientCreditsError: logger.error( f"[CREDIT VERIFICATION] Insufficient credits would have fired for organization {organization_id} and agent {agent_id}" ) return True except httpx.TimeoutException: logger.warning(f"[CREDIT VERIFICATION] Timeout verifying credits for organization {organization_id}, agent {agent_id}") return True except httpx.HTTPStatusError as e: logger.warning( f"[CREDIT VERIFICATION] HTTP error verifying credits for organization {organization_id}, agent {agent_id}: {e.response.status_code}" ) return True except Exception as e: logger.error( f"[CREDIT VERIFICATION] Unexpected error verifying credits for organization {organization_id}, agent {agent_id}: {e}" ) return True
{ "repo_id": "letta-ai/letta", "file_path": "letta/services/credit_verification_service.py", "license": "Apache License 2.0", "lines": 57, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
letta-ai/letta:letta/services/llm_trace_reader.py
"""ClickHouse reader for LLM analytics traces. Reads LLM traces from ClickHouse for debugging, analytics, and auditing. """ from __future__ import annotations import asyncio from dataclasses import dataclass from datetime import datetime from typing import Any, List, Optional from urllib.parse import urlparse from letta.helpers.singleton import singleton from letta.log import get_logger from letta.schemas.llm_trace import LLMTrace from letta.settings import settings logger = get_logger(__name__) def _parse_clickhouse_endpoint(endpoint: str) -> tuple[str, int, bool]: """Return (host, port, secure) for clickhouse_connect.get_client. Supports: - http://host:port -> (host, port, False) - https://host:port -> (host, port, True) - host:port -> (host, port, False) # Default to insecure for local dev - host -> (host, 8123, False) # Default HTTP port, insecure """ parsed = urlparse(endpoint) if parsed.scheme in ("http", "https"): host = parsed.hostname or "" port = parsed.port or (8443 if parsed.scheme == "https" else 8123) secure = parsed.scheme == "https" return host, port, secure # Fallback: accept raw hostname (possibly with :port) # Default to insecure (HTTP) for local development if ":" in endpoint: host, port_str = endpoint.rsplit(":", 1) return host, int(port_str), False return endpoint, 8123, False @dataclass(frozen=True) class LLMTraceRow: """Raw row from ClickHouse query.""" id: str organization_id: str project_id: str agent_id: str agent_tags: List[str] run_id: str step_id: str trace_id: str call_type: str provider: str model: str is_byok: bool request_size_bytes: int response_size_bytes: int prompt_tokens: int completion_tokens: int total_tokens: int cached_input_tokens: Optional[int] cache_write_tokens: Optional[int] reasoning_tokens: Optional[int] latency_ms: int is_error: bool error_type: str error_message: str request_json: str response_json: str llm_config_json: str created_at: datetime @singleton class LLMTraceReader: """ ClickHouse reader for raw LLM traces. Provides query methods for debugging, analytics, and auditing. Usage: reader = LLMTraceReader() trace = await reader.get_by_step_id_async(step_id="step-xxx", organization_id="org-xxx") traces = await reader.list_by_agent_async(agent_id="agent-xxx", organization_id="org-xxx") """ def __init__(self): self._client = None def _get_client(self): """Initialize ClickHouse client on first use (lazy loading).""" if self._client is not None: return self._client import clickhouse_connect if not settings.clickhouse_endpoint: raise ValueError("CLICKHOUSE_ENDPOINT is required") host, port, secure = _parse_clickhouse_endpoint(settings.clickhouse_endpoint) if not host: raise ValueError("Invalid CLICKHOUSE_ENDPOINT") database = settings.clickhouse_database or "otel" username = settings.clickhouse_username or "default" password = settings.clickhouse_password if not password: raise ValueError("CLICKHOUSE_PASSWORD is required") self._client = clickhouse_connect.get_client( host=host, port=port, username=username, password=password, database=database, secure=secure, verify=True, ) return self._client def _row_to_trace(self, row: tuple) -> LLMTrace: """Convert a ClickHouse row tuple to LLMTrace.""" return LLMTrace( id=row[0], organization_id=row[1], project_id=row[2] or None, agent_id=row[3] or None, agent_tags=list(row[4]) if row[4] else [], run_id=row[5] or None, step_id=row[6] or None, trace_id=row[7] or None, call_type=row[8], provider=row[9], model=row[10], is_byok=bool(row[11]), request_size_bytes=row[12], response_size_bytes=row[13], prompt_tokens=row[14], completion_tokens=row[15], total_tokens=row[16], cached_input_tokens=row[17], cache_write_tokens=row[18], reasoning_tokens=row[19], latency_ms=row[20], is_error=bool(row[21]), error_type=row[22] or None, error_message=row[23] or None, request_json=row[24], response_json=row[25], llm_config_json=row[26] or "", created_at=row[27], ) def _query_sync(self, query: str, parameters: dict[str, Any]) -> List[tuple]: """Execute a query synchronously.""" client = self._get_client() result = client.query(query, parameters=parameters) return result.result_rows if result else [] # ------------------------------------------------------------------------- # Query Methods # ------------------------------------------------------------------------- async def get_by_step_id_async( self, step_id: str, organization_id: str, ) -> Optional[LLMTrace]: """ Get the most recent trace for a step. Args: step_id: The step ID to look up organization_id: Organization ID for access control Returns: LLMTrace if found, None otherwise """ query = """ SELECT id, organization_id, project_id, agent_id, agent_tags, run_id, step_id, trace_id, call_type, provider, model, is_byok, request_size_bytes, response_size_bytes, prompt_tokens, completion_tokens, total_tokens, cached_input_tokens, cache_write_tokens, reasoning_tokens, latency_ms, is_error, error_type, error_message, request_json, response_json, llm_config_json, created_at FROM llm_traces WHERE step_id = %(step_id)s AND organization_id = %(organization_id)s ORDER BY created_at DESC LIMIT 1 """ rows = await asyncio.to_thread( self._query_sync, query, {"step_id": step_id, "organization_id": organization_id}, ) if not rows: return None return self._row_to_trace(rows[0]) async def get_by_id_async( self, trace_id: str, organization_id: str, ) -> Optional[LLMTrace]: """ Get a trace by its ID. Args: trace_id: The trace ID (UUID) organization_id: Organization ID for access control Returns: LLMTrace if found, None otherwise """ query = """ SELECT id, organization_id, project_id, agent_id, agent_tags, run_id, step_id, trace_id, call_type, provider, model, is_byok, request_size_bytes, response_size_bytes, prompt_tokens, completion_tokens, total_tokens, cached_input_tokens, cache_write_tokens, reasoning_tokens, latency_ms, is_error, error_type, error_message, request_json, response_json, llm_config_json, created_at FROM llm_traces WHERE id = %(trace_id)s AND organization_id = %(organization_id)s LIMIT 1 """ rows = await asyncio.to_thread( self._query_sync, query, {"trace_id": trace_id, "organization_id": organization_id}, ) if not rows: return None return self._row_to_trace(rows[0]) async def list_by_agent_async( self, agent_id: str, organization_id: str, limit: int = 100, offset: int = 0, call_type: Optional[str] = None, is_error: Optional[bool] = None, start_date: Optional[datetime] = None, end_date: Optional[datetime] = None, ) -> List[LLMTrace]: """ List traces for an agent with optional filters. Args: agent_id: Agent ID to filter by organization_id: Organization ID for access control limit: Maximum number of results (default 100) offset: Offset for pagination call_type: Filter by call type ('agent_step', 'summarization') is_error: Filter by error status start_date: Filter by created_at >= start_date end_date: Filter by created_at <= end_date Returns: List of LLMTrace objects """ conditions = [ "agent_id = %(agent_id)s", "organization_id = %(organization_id)s", ] params: dict[str, Any] = { "agent_id": agent_id, "organization_id": organization_id, "limit": limit, "offset": offset, } if call_type: conditions.append("call_type = %(call_type)s") params["call_type"] = call_type if is_error is not None: conditions.append("is_error = %(is_error)s") params["is_error"] = 1 if is_error else 0 if start_date: conditions.append("created_at >= %(start_date)s") params["start_date"] = start_date if end_date: conditions.append("created_at <= %(end_date)s") params["end_date"] = end_date where_clause = " AND ".join(conditions) query = f""" SELECT id, organization_id, project_id, agent_id, agent_tags, run_id, step_id, trace_id, call_type, provider, model, is_byok, request_size_bytes, response_size_bytes, prompt_tokens, completion_tokens, total_tokens, cached_input_tokens, cache_write_tokens, reasoning_tokens, latency_ms, is_error, error_type, error_message, request_json, response_json, llm_config_json, created_at FROM llm_traces WHERE {where_clause} ORDER BY created_at DESC LIMIT %(limit)s OFFSET %(offset)s """ rows = await asyncio.to_thread(self._query_sync, query, params) return [self._row_to_trace(row) for row in rows] async def get_usage_stats_async( self, organization_id: str, start_date: Optional[datetime] = None, end_date: Optional[datetime] = None, group_by: str = "model", # 'model', 'agent_id', 'call_type' ) -> List[dict[str, Any]]: """ Get aggregated usage statistics. Args: organization_id: Organization ID for access control start_date: Filter by created_at >= start_date end_date: Filter by created_at <= end_date group_by: Field to group by ('model', 'agent_id', 'call_type') Returns: List of aggregated stats dicts """ valid_group_by = {"model", "agent_id", "call_type", "provider"} if group_by not in valid_group_by: raise ValueError(f"group_by must be one of {valid_group_by}") conditions = ["organization_id = %(organization_id)s"] params: dict[str, Any] = {"organization_id": organization_id} if start_date: conditions.append("created_at >= %(start_date)s") params["start_date"] = start_date if end_date: conditions.append("created_at <= %(end_date)s") params["end_date"] = end_date where_clause = " AND ".join(conditions) query = f""" SELECT {group_by}, count() as request_count, sum(total_tokens) as total_tokens, sum(prompt_tokens) as prompt_tokens, sum(completion_tokens) as completion_tokens, avg(latency_ms) as avg_latency_ms, sum(request_size_bytes) as total_request_bytes, sum(response_size_bytes) as total_response_bytes, countIf(is_error = 1) as error_count FROM llm_traces WHERE {where_clause} GROUP BY {group_by} ORDER BY total_tokens DESC """ rows = await asyncio.to_thread(self._query_sync, query, params) return [ { group_by: row[0], "request_count": row[1], "total_tokens": row[2], "prompt_tokens": row[3], "completion_tokens": row[4], "avg_latency_ms": row[5], "total_request_bytes": row[6], "total_response_bytes": row[7], "error_count": row[8], } for row in rows ] async def find_large_requests_async( self, organization_id: str, min_size_bytes: int = 1_000_000, # 1MB default limit: int = 100, ) -> List[LLMTrace]: """ Find traces with large request payloads (for debugging). Args: organization_id: Organization ID for access control min_size_bytes: Minimum request size in bytes (default 1MB) limit: Maximum number of results Returns: List of LLMTrace objects with large requests """ query = """ SELECT id, organization_id, project_id, agent_id, agent_tags, run_id, step_id, trace_id, call_type, provider, model, is_byok, request_size_bytes, response_size_bytes, prompt_tokens, completion_tokens, total_tokens, cached_input_tokens, cache_write_tokens, reasoning_tokens, latency_ms, is_error, error_type, error_message, request_json, response_json, llm_config_json, created_at FROM llm_traces WHERE organization_id = %(organization_id)s AND request_size_bytes >= %(min_size_bytes)s ORDER BY request_size_bytes DESC LIMIT %(limit)s """ rows = await asyncio.to_thread( self._query_sync, query, { "organization_id": organization_id, "min_size_bytes": min_size_bytes, "limit": limit, }, ) return [self._row_to_trace(row) for row in rows] # Module-level instance for easy access _reader_instance: Optional[LLMTraceReader] = None def get_llm_trace_reader() -> LLMTraceReader: """Get the singleton LLMTraceReader instance.""" global _reader_instance if _reader_instance is None: _reader_instance = LLMTraceReader() return _reader_instance
{ "repo_id": "letta-ai/letta", "file_path": "letta/services/llm_trace_reader.py", "license": "Apache License 2.0", "lines": 393, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
letta-ai/letta:letta/services/llm_trace_writer.py
"""ClickHouse writer for LLM analytics traces. Writes LLM traces to ClickHouse with denormalized columns for cost analytics. Uses ClickHouse's async_insert feature for server-side batching. """ from __future__ import annotations import asyncio import atexit from typing import TYPE_CHECKING, Optional from urllib.parse import urlparse from letta.helpers.singleton import singleton from letta.log import get_logger from letta.settings import settings if TYPE_CHECKING: from letta.schemas.llm_trace import LLMTrace logger = get_logger(__name__) # Retry configuration MAX_RETRIES = 3 INITIAL_BACKOFF_SECONDS = 1.0 _background_tasks: set[asyncio.Task] = set() def _parse_clickhouse_endpoint(endpoint: str) -> tuple[str, int, bool]: """Return (host, port, secure) for clickhouse_connect.get_client. Supports: - http://host:port -> (host, port, False) - https://host:port -> (host, port, True) - host:port -> (host, port, False) # Default to insecure for local dev - host -> (host, 8123, False) # Default HTTP port, insecure """ parsed = urlparse(endpoint) if parsed.scheme in ("http", "https"): host = parsed.hostname or "" port = parsed.port or (8443 if parsed.scheme == "https" else 8123) secure = parsed.scheme == "https" return host, port, secure # Fallback: accept raw hostname (possibly with :port) # Default to insecure (HTTP) for local development if ":" in endpoint: host, port_str = endpoint.rsplit(":", 1) return host, int(port_str), False return endpoint, 8123, False @singleton class LLMTraceWriter: """ Direct ClickHouse writer for raw LLM traces. Uses ClickHouse's async_insert feature for server-side batching. Each trace is inserted directly and ClickHouse handles batching for optimal write performance. Usage: writer = LLMTraceWriter() await writer.write_async(trace) Configuration (via settings): - store_llm_traces: Enable/disable (default: False) """ def __init__(self): self._client = None self._shutdown = False # Check if ClickHouse is configured - if not, writing is disabled self._enabled = bool(settings.clickhouse_endpoint and settings.clickhouse_password) # Register shutdown handler atexit.register(self._sync_shutdown) def _get_client(self): """Initialize ClickHouse client on first use (lazy loading).""" if self._client is not None: return self._client # Import lazily so OSS users who never enable this don't pay import cost import clickhouse_connect host, port, secure = _parse_clickhouse_endpoint(settings.clickhouse_endpoint) database = settings.clickhouse_database or "otel" username = settings.clickhouse_username or "default" self._client = clickhouse_connect.get_client( host=host, port=port, username=username, password=settings.clickhouse_password, database=database, secure=secure, verify=True, settings={ # Enable server-side batching "async_insert": 1, # Don't wait for server-side flush acknowledgment — fire and forget. # Waiting (value=1) caused each insert to hold an asyncio.Lock for ~1s, # creating unbounded task queues that saturated the event loop under load. "wait_for_async_insert": 0, # Flush after 1 second if batch not full "async_insert_busy_timeout_ms": 1000, }, ) logger.info(f"LLMTraceWriter: Connected to ClickHouse at {host}:{port}/{database} (async_insert enabled)") return self._client async def write_async(self, trace: "LLMTrace") -> None: """ Write a trace to ClickHouse (fire-and-forget with retry). ClickHouse's async_insert handles batching server-side for optimal write performance. This method retries on failure with exponential backoff. Args: trace: The LLMTrace to write """ if not self._enabled or self._shutdown: return try: task = asyncio.create_task(self._write_with_retry(trace)) _background_tasks.add(task) task.add_done_callback(_background_tasks.discard) except RuntimeError: pass async def _write_with_retry(self, trace: "LLMTrace") -> None: """Write a single trace with retry on failure.""" from letta.schemas.llm_trace import LLMTrace for attempt in range(MAX_RETRIES): try: client = self._get_client() row = trace.to_clickhouse_row() columns = LLMTrace.clickhouse_columns() # Run synchronous insert in thread pool. clickhouse-connect supports # multithreaded use via a thread-safe connection pool: # https://clickhouse.com/docs/integrations/language-clients/python/advanced-usage#multithreaded-multiprocess-and-asyncevent-driven-use-cases await asyncio.to_thread( client.insert, "llm_traces", [row], column_names=columns, ) return # Success except Exception as e: if attempt < MAX_RETRIES - 1: backoff = INITIAL_BACKOFF_SECONDS * (2**attempt) logger.warning(f"LLMTraceWriter: Retry {attempt + 1}/{MAX_RETRIES}, backoff {backoff}s: {e}") await asyncio.sleep(backoff) else: logger.error(f"LLMTraceWriter: Dropping trace after {MAX_RETRIES} retries: {e}") async def shutdown_async(self) -> None: """Gracefully shutdown the writer.""" self._shutdown = True # Close client if self._client: try: self._client.close() except Exception as e: logger.warning(f"LLMTraceWriter: Error closing client: {e}") self._client = None logger.info("LLMTraceWriter: Shutdown complete") def _sync_shutdown(self) -> None: """Synchronous shutdown handler for atexit.""" if not self._enabled or self._shutdown: return self._shutdown = True if self._client: try: self._client.close() except Exception: pass # Module-level instance for easy access _writer_instance: Optional[LLMTraceWriter] = None def get_llm_trace_writer() -> LLMTraceWriter: """Get the singleton LLMTraceWriter instance.""" global _writer_instance if _writer_instance is None: _writer_instance = LLMTraceWriter() return _writer_instance
{ "repo_id": "letta-ai/letta", "file_path": "letta/services/llm_trace_writer.py", "license": "Apache License 2.0", "lines": 160, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
letta-ai/letta:letta/services/memory_repo/block_markdown.py
"""Serialize and parse block data as Markdown with YAML frontmatter. File format: --- description: "Who I am and how I approach work" --- My name is Memo. I'm a stateful coding assistant... - Frontmatter fields are only rendered when they differ from defaults. - ``limit`` is intentionally excluded from frontmatter (deprecated for git-base memory). - Files without frontmatter are treated as value-only (backward compat). """ from typing import Any, Dict, Optional import yaml from letta.schemas.block import BaseBlock def _get_field_default(field_name: str) -> Any: """Get the default value for a BaseBlock field.""" field = BaseBlock.model_fields[field_name] return field.default def serialize_block( value: str, *, description: Optional[str] = None, limit: Optional[int] = None, read_only: bool = False, metadata: Optional[dict] = None, ) -> str: """Serialize a block to Markdown with optional YAML frontmatter. This is used for initial file creation. For updates to existing files, prefer `merge_frontmatter_with_body` to preserve user formatting. """ # description is always included in frontmatter. # read_only and metadata are only included when non-default. # limit is intentionally excluded (deprecated for git-base memory). front: Dict[str, Any] = {} front["description"] = description if read_only != _get_field_default("read_only"): front["read_only"] = read_only if metadata and metadata != _get_field_default("metadata"): front["metadata"] = metadata # Use block style for cleaner YAML, default_flow_style=False yaml_str = yaml.dump(front, default_flow_style=False, sort_keys=False, allow_unicode=True).rstrip("\n") return f"---\n{yaml_str}\n---\n{value}" def _extract_frontmatter(content: str) -> tuple[Optional[str], str]: """Return (frontmatter_yaml, body). If no valid opening/closing frontmatter delimiters are found, returns (None, original_content). """ if not content.startswith("---\n"): return None, content end_idx = content.find("\n---\n", 4) if end_idx == -1: return None, content yaml_str = content[4:end_idx] body = content[end_idx + 5 :] return yaml_str, body def merge_frontmatter_with_body( existing_content: str, *, value: str, description: Optional[str], limit: Optional[int], read_only: bool, metadata: Optional[dict], ) -> str: """Update block content while preserving existing frontmatter formatting when possible. Behavior: - If existing content has YAML frontmatter, parse it and update keys in-memory, then splice back using the exact original YAML text when values are unchanged. - If keys changed or missing, emit normalized frontmatter only for changed keys, while preserving body exactly as provided. - If no frontmatter exists, create one. """ yaml_str, _existing_body = _extract_frontmatter(existing_content) if yaml_str is None: return serialize_block( value=value, description=description, limit=limit, read_only=read_only, metadata=metadata, ) try: parsed = yaml.safe_load(yaml_str) or {} except yaml.YAMLError: parsed = {} if not isinstance(parsed, dict): parsed = {} # Desired values desired_description = description desired_read_only = read_only desired_metadata = metadata if metadata is not None else _get_field_default("metadata") # Track whether anything semantically changes in frontmatter. changed = False if "description" not in parsed or parsed.get("description") != desired_description: parsed["description"] = desired_description changed = True # Remove limit from frontmatter if it exists (deprecated for git-base memory) if "limit" in parsed: del parsed["limit"] changed = True if desired_read_only != _get_field_default("read_only"): if parsed.get("read_only") != desired_read_only: parsed["read_only"] = desired_read_only changed = True elif "read_only" in parsed: del parsed["read_only"] changed = True if desired_metadata and desired_metadata != _get_field_default("metadata"): if parsed.get("metadata") != desired_metadata: parsed["metadata"] = desired_metadata changed = True elif "metadata" in parsed: del parsed["metadata"] changed = True # If frontmatter semantics unchanged, preserve original YAML formatting verbatim. if not changed: return f"---\n{yaml_str}\n---\n{value}" normalized_yaml = yaml.dump(parsed, default_flow_style=False, sort_keys=False, allow_unicode=True).rstrip("\n") return f"---\n{normalized_yaml}\n---\n{value}" def parse_block_markdown(content: str) -> Dict[str, Any]: """Parse a Markdown file into block fields. Returns a dict with: - "value": the body content after frontmatter - "description", "limit", "read_only", "metadata": from frontmatter (if present) If no frontmatter is detected, the entire content is treated as the value (backward compat with old repos that stored raw values). """ if not content.startswith("---\n"): return {"value": content} # Find the closing --- delimiter end_idx = content.find("\n---\n", 4) if end_idx == -1: # No closing delimiter — treat entire content as value return {"value": content} yaml_str = content[4:end_idx] body = content[end_idx + 5 :] # skip past \n---\n try: front = yaml.safe_load(yaml_str) except yaml.YAMLError: # Malformed YAML — treat entire content as value return {"value": content} if not isinstance(front, dict): return {"value": content} result: Dict[str, Any] = {"value": body} if "description" in front: result["description"] = front["description"] if "limit" in front: result["limit"] = front["limit"] if "read_only" in front: result["read_only"] = front["read_only"] if "metadata" in front: result["metadata"] = front["metadata"] return result
{ "repo_id": "letta-ai/letta", "file_path": "letta/services/memory_repo/block_markdown.py", "license": "Apache License 2.0", "lines": 152, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
letta-ai/letta:letta/services/memory_repo/git_operations.py
"""Git operations for memory repositories using git CLI. This module provides high-level operations for working with git repos stored in object storage (GCS/S3), using the git command-line tool instead of dulwich for better compatibility and maintenance. """ import asyncio import os import shutil import subprocess import tempfile import time import uuid from datetime import datetime, timezone from typing import Dict, List, Optional from letta.data_sources.redis_client import get_redis_client from letta.log import get_logger from letta.schemas.memory_repo import FileChange, MemoryCommit from letta.services.memory_repo.storage.base import StorageBackend logger = get_logger(__name__) def _run_git(args: List[str], cwd: str, check: bool = True) -> subprocess.CompletedProcess: """Run a git command and return the result. Args: args: Git command arguments (without 'git' prefix) cwd: Working directory check: Whether to raise on non-zero exit Returns: CompletedProcess with stdout/stderr """ result = subprocess.run( ["git", *args], cwd=cwd, capture_output=True, text=True, check=False, ) if check and result.returncode != 0: raise subprocess.CalledProcessError(result.returncode, ["git", *args], result.stdout, result.stderr) return result class GitOperations: """High-level git operations for memory repositories. This class provides git operations that work with repositories stored in object storage. It downloads the repo to a temp directory, performs operations, and uploads the changes back. For efficiency with small repos (100s of files), we use a full checkout model. For larger repos, we could optimize to work with packfiles directly. Requirements: git CLI must be installed and available in PATH """ def __init__(self, storage: StorageBackend): """Initialize git operations. Args: storage: Storage backend for repo persistence """ self.storage = storage self._git_available = None def _check_git(self) -> None: """Check that git is available.""" if self._git_available is None: try: result = subprocess.run( ["git", "--version"], capture_output=True, text=True, check=True, ) self._git_available = True logger.debug(f"Git available: {result.stdout.strip()}") except (subprocess.CalledProcessError, FileNotFoundError): self._git_available = False raise RuntimeError("git CLI is required for git operations but was not found in PATH") elif not self._git_available: raise RuntimeError("git CLI is required for git operations but was not found in PATH") def _repo_path(self, agent_id: str, org_id: str) -> str: """Get the storage path for an agent's repo.""" return f"{org_id}/{agent_id}/repo.git" async def create_repo( self, agent_id: str, org_id: str, initial_files: Optional[Dict[str, str]] = None, author_name: str = "Letta System", author_email: str = "system@letta.ai", ) -> str: """Create a new git repository for an agent. Args: agent_id: Agent ID org_id: Organization ID initial_files: Optional initial files to commit author_name: Author name for initial commit author_email: Author email for initial commit Returns: Initial commit SHA """ self._check_git() def _create(): temp_dir = tempfile.mkdtemp(prefix="letta-memrepo-") try: repo_path = os.path.join(temp_dir, "repo") os.makedirs(repo_path) # Initialize a new repository with main as default branch _run_git(["init", "-b", "main"], cwd=repo_path) # Configure user for this repo _run_git(["config", "user.name", author_name], cwd=repo_path) _run_git(["config", "user.email", author_email], cwd=repo_path) # Add initial files if provided if initial_files: for file_path, content in initial_files.items(): full_path = os.path.join(repo_path, file_path) os.makedirs(os.path.dirname(full_path), exist_ok=True) with open(full_path, "w", encoding="utf-8") as f: f.write(content) _run_git(["add", file_path], cwd=repo_path) else: # Create an empty .letta directory to initialize letta_dir = os.path.join(repo_path, ".letta") os.makedirs(letta_dir, exist_ok=True) config_path = os.path.join(letta_dir, "config.json") with open(config_path, "w") as f: f.write('{"version": 1}') _run_git(["add", ".letta/config.json"], cwd=repo_path) # Create initial commit _run_git(["commit", "-m", "Initial commit"], cwd=repo_path) # Get commit SHA result = _run_git(["rev-parse", "HEAD"], cwd=repo_path) commit_sha = result.stdout.strip() return repo_path, commit_sha except Exception: shutil.rmtree(temp_dir, ignore_errors=True) raise repo_path, commit_sha = await asyncio.to_thread(_create) try: await self._upload_repo(repo_path, agent_id, org_id) return commit_sha finally: shutil.rmtree(os.path.dirname(repo_path), ignore_errors=True) async def _upload_repo(self, local_repo_path: str, agent_id: str, org_id: str) -> None: """Upload a local repo to storage (full upload).""" t_start = time.perf_counter() storage_prefix = self._repo_path(agent_id, org_id) git_dir = os.path.join(local_repo_path, ".git") upload_tasks = [] total_bytes = 0 t0 = time.perf_counter() for root, dirs, files in os.walk(git_dir): for filename in files: local_path = os.path.join(root, filename) rel_path = os.path.relpath(local_path, git_dir) storage_path = f"{storage_prefix}/{rel_path}" with open(local_path, "rb") as f: content = f.read() total_bytes += len(content) upload_tasks.append((storage_path, content)) read_time = (time.perf_counter() - t0) * 1000 logger.info(f"[GIT_PERF] _upload_repo read files took {read_time:.2f}ms files={len(upload_tasks)}") t0 = time.perf_counter() await asyncio.gather(*[self.storage.upload_bytes(path, content) for path, content in upload_tasks]) upload_time = (time.perf_counter() - t0) * 1000 total_time = (time.perf_counter() - t_start) * 1000 logger.info( f"[GIT_PERF] _upload_repo TOTAL {total_time:.2f}ms " f"files={len(upload_tasks)} bytes={total_bytes} " f"upload_time={upload_time:.2f}ms" ) @staticmethod def _snapshot_git_files(git_dir: str) -> Dict[str, float]: """Snapshot mtime of all files under .git/ for delta detection.""" snapshot = {} for root, _dirs, files in os.walk(git_dir): for filename in files: path = os.path.join(root, filename) snapshot[path] = os.path.getmtime(path) return snapshot async def _upload_delta( self, local_repo_path: str, agent_id: str, org_id: str, before_snapshot: Dict[str, float], ) -> None: """Upload only new/modified files since before_snapshot.""" t_start = time.perf_counter() storage_prefix = self._repo_path(agent_id, org_id) git_dir = os.path.join(local_repo_path, ".git") upload_tasks = [] total_bytes = 0 for root, _dirs, files in os.walk(git_dir): for filename in files: local_path = os.path.join(root, filename) old_mtime = before_snapshot.get(local_path) if old_mtime is None or os.path.getmtime(local_path) != old_mtime: rel_path = os.path.relpath(local_path, git_dir) storage_path = f"{storage_prefix}/{rel_path}" with open(local_path, "rb") as f: content = f.read() total_bytes += len(content) upload_tasks.append((storage_path, content)) t0 = time.perf_counter() await asyncio.gather(*[self.storage.upload_bytes(path, content) for path, content in upload_tasks]) upload_time = (time.perf_counter() - t0) * 1000 total_time = (time.perf_counter() - t_start) * 1000 logger.info( f"[GIT_PERF] _upload_delta TOTAL {total_time:.2f}ms " f"files={len(upload_tasks)} bytes={total_bytes} " f"upload_time={upload_time:.2f}ms" ) async def _download_repo(self, agent_id: str, org_id: str) -> str: """Download a repo from storage to a temp directory. Returns: Path to the temporary repo directory """ t_start = time.perf_counter() storage_prefix = self._repo_path(agent_id, org_id) t0 = time.perf_counter() files = await self.storage.list_files(storage_prefix) list_time = (time.perf_counter() - t0) * 1000 logger.info(f"[GIT_PERF] _download_repo storage.list_files took {list_time:.2f}ms files_count={len(files)}") if not files: raise FileNotFoundError(f"No repository found for agent {agent_id}") t0 = time.perf_counter() temp_dir = tempfile.mkdtemp(prefix="letta-memrepo-") repo_path = os.path.join(temp_dir, "repo") git_dir = os.path.join(repo_path, ".git") os.makedirs(git_dir) mkdir_time = (time.perf_counter() - t0) * 1000 logger.info(f"[GIT_PERF] _download_repo tempdir creation took {mkdir_time:.2f}ms path={temp_dir}") file_info = [] for file_path in files: if file_path.startswith(storage_prefix): rel_path = file_path[len(storage_prefix) + 1 :] else: rel_path = file_path.split("/")[-1] if "/" in file_path else file_path local_path = os.path.join(git_dir, rel_path) os.makedirs(os.path.dirname(local_path), exist_ok=True) file_info.append((file_path, local_path)) t0 = time.perf_counter() download_tasks = [self.storage.download_bytes(fp) for fp, _ in file_info] contents = await asyncio.gather(*download_tasks) download_time = (time.perf_counter() - t0) * 1000 total_bytes = sum(len(c) for c in contents) logger.info(f"[GIT_PERF] _download_repo parallel download took {download_time:.2f}ms files={len(files)} bytes={total_bytes}") t0 = time.perf_counter() for (_, local_path), content in zip(file_info, contents): with open(local_path, "wb") as f: f.write(content) write_time = (time.perf_counter() - t0) * 1000 total_time = (time.perf_counter() - t_start) * 1000 logger.info( f"[GIT_PERF] _download_repo TOTAL {total_time:.2f}ms " f"files={len(files)} bytes={total_bytes} " f"download_time={download_time:.2f}ms write_time={write_time:.2f}ms" ) return repo_path async def get_files( self, agent_id: str, org_id: str, ref: str = "HEAD", ) -> Dict[str, str]: """Get all files at a specific ref. Args: agent_id: Agent ID org_id: Organization ID ref: Git ref (commit SHA, branch name, or 'HEAD') Returns: Dict mapping file paths to content """ self._check_git() repo_path = await self._download_repo(agent_id, org_id) try: def _get_files(): # List all files tracked by git at the given ref result = _run_git(["ls-tree", "-r", "--name-only", ref], cwd=repo_path) file_paths = result.stdout.strip().split("\n") if result.stdout.strip() else [] files = {} for file_path in file_paths: if not file_path: continue # Get file content at ref try: content_result = _run_git(["show", f"{ref}:{file_path}"], cwd=repo_path) files[file_path] = content_result.stdout except subprocess.CalledProcessError: pass # Skip files that can't be read return files return await asyncio.to_thread(_get_files) finally: shutil.rmtree(os.path.dirname(repo_path), ignore_errors=True) async def commit( self, agent_id: str, org_id: str, changes: List[FileChange], message: str, author_name: str = "Letta Agent", author_email: str = "agent@letta.ai", branch: str = "main", ) -> MemoryCommit: """Commit changes to the repository. Uses a Redis lock to prevent concurrent modifications. Args: agent_id: Agent ID org_id: Organization ID changes: List of file changes message: Commit message author_name: Author name author_email: Author email branch: Branch to commit to Returns: MemoryCommit with commit details Raises: MemoryRepoBusyError: If another operation is in progress """ t_start = time.perf_counter() logger.info(f"[GIT_PERF] GitOperations.commit START agent={agent_id} changes={len(changes)}") t0 = time.perf_counter() redis_client = await get_redis_client() lock_token = f"commit:{uuid.uuid4().hex}" lock = await redis_client.acquire_memory_repo_lock(agent_id, lock_token) logger.info(f"[GIT_PERF] acquire_memory_repo_lock took {(time.perf_counter() - t0) * 1000:.2f}ms") try: t0 = time.perf_counter() result = await self._commit_with_lock( agent_id=agent_id, org_id=org_id, changes=changes, message=message, author_name=author_name, author_email=author_email, branch=branch, ) logger.info(f"[GIT_PERF] _commit_with_lock took {(time.perf_counter() - t0) * 1000:.2f}ms") total_time = (time.perf_counter() - t_start) * 1000 logger.info(f"[GIT_PERF] GitOperations.commit TOTAL {total_time:.2f}ms") return result finally: t0 = time.perf_counter() if lock: try: await lock.release() except Exception as e: logger.warning(f"Failed to release lock for agent {agent_id}: {e}") await redis_client.release_memory_repo_lock(agent_id) logger.info(f"[GIT_PERF] lock release took {(time.perf_counter() - t0) * 1000:.2f}ms") async def _commit_with_lock( self, agent_id: str, org_id: str, changes: List[FileChange], message: str, author_name: str = "Letta Agent", author_email: str = "agent@letta.ai", branch: str = "main", ) -> MemoryCommit: """Internal commit implementation (called while holding lock).""" t_start = time.perf_counter() self._check_git() t0 = time.perf_counter() repo_path = await self._download_repo(agent_id, org_id) download_time = (time.perf_counter() - t0) * 1000 logger.info(f"[GIT_PERF] _commit_with_lock download phase took {download_time:.2f}ms") try: git_dir = os.path.join(repo_path, ".git") before_snapshot = self._snapshot_git_files(git_dir) def _commit(): t_git_start = time.perf_counter() # Configure user for this repo _run_git(["config", "user.name", author_name], cwd=repo_path) _run_git(["config", "user.email", author_email], cwd=repo_path) # Reset to clean state t0_reset = time.perf_counter() _run_git(["reset", "--hard"], cwd=repo_path) reset_time = (time.perf_counter() - t0_reset) * 1000 # Get parent SHA before making changes try: parent_result = _run_git(["rev-parse", "HEAD"], cwd=repo_path, check=False) parent_sha = parent_result.stdout.strip() if parent_result.returncode == 0 else None except Exception: parent_sha = None # Apply changes files_changed = [] additions = 0 deletions = 0 apply_time = 0 for change in changes: t0_apply = time.perf_counter() file_path = change.path.lstrip("/") full_path = os.path.join(repo_path, file_path) if change.change_type == "delete" or change.content is None: if os.path.exists(full_path): with open(full_path, "r") as f: deletions += len(f.read()) os.remove(full_path) _run_git(["rm", "-f", file_path], cwd=repo_path, check=False) else: os.makedirs(os.path.dirname(full_path), exist_ok=True) if os.path.exists(full_path): with open(full_path, "r") as f: old_content = f.read() deletions += len(old_content) additions += len(change.content) with open(full_path, "w", encoding="utf-8") as f: f.write(change.content) _run_git(["add", file_path], cwd=repo_path) files_changed.append(file_path) apply_time += (time.perf_counter() - t0_apply) * 1000 # Create commit t0_commit = time.perf_counter() _run_git(["commit", "-m", message], cwd=repo_path) commit_time = (time.perf_counter() - t0_commit) * 1000 # Get new commit SHA result = _run_git(["rev-parse", "HEAD"], cwd=repo_path) sha_str = result.stdout.strip() git_total = (time.perf_counter() - t_git_start) * 1000 logger.info( f"[GIT_PERF] _commit git operations: reset={reset_time:.2f}ms " f"apply_changes={apply_time:.2f}ms commit={commit_time:.2f}ms total={git_total:.2f}ms" ) return MemoryCommit( sha=sha_str, parent_sha=parent_sha, message=message, author_type="agent" if "agent" in author_email.lower() else "user", author_id=agent_id, author_name=author_name, timestamp=datetime.now(timezone.utc), files_changed=files_changed, additions=additions, deletions=deletions, ) t0 = time.perf_counter() commit = await asyncio.to_thread(_commit) git_thread_time = (time.perf_counter() - t0) * 1000 logger.info(f"[GIT_PERF] _commit_with_lock git thread took {git_thread_time:.2f}ms") t0 = time.perf_counter() await self._upload_delta(repo_path, agent_id, org_id, before_snapshot) upload_time = (time.perf_counter() - t0) * 1000 logger.info(f"[GIT_PERF] _commit_with_lock upload phase (delta) took {upload_time:.2f}ms") total_time = (time.perf_counter() - t_start) * 1000 logger.info( f"[GIT_PERF] _commit_with_lock TOTAL {total_time:.2f}ms " f"(download={download_time:.2f}ms git={git_thread_time:.2f}ms upload={upload_time:.2f}ms)" ) return commit finally: t0 = time.perf_counter() shutil.rmtree(os.path.dirname(repo_path), ignore_errors=True) logger.info(f"[GIT_PERF] cleanup temp dir took {(time.perf_counter() - t0) * 1000:.2f}ms") async def get_history( self, agent_id: str, org_id: str, path: Optional[str] = None, limit: int = 50, ) -> List[MemoryCommit]: """Get commit history. Args: agent_id: Agent ID org_id: Organization ID path: Optional file path to filter by limit: Maximum number of commits to return Returns: List of commits, newest first """ self._check_git() repo_path = await self._download_repo(agent_id, org_id) try: def _get_history(): # Use git log with custom format for easy parsing # Format: SHA|parent_sha|author_name|timestamp|message format_str = "%H|%P|%an|%at|%s" args = ["log", f"--format={format_str}", f"-n{limit}"] if path: args.extend(["--", path]) result = _run_git(args, cwd=repo_path) lines = result.stdout.strip().split("\n") if result.stdout.strip() else [] commits = [] for line in lines: if not line: continue parts = line.split("|", 4) if len(parts) < 5: continue sha, parents, author_name, timestamp_str, message = parts parent_sha = parents.split()[0] if parents else None commits.append( MemoryCommit( sha=sha, parent_sha=parent_sha, message=message, author_type="system", author_id="", author_name=author_name, timestamp=datetime.fromtimestamp(int(timestamp_str), tz=timezone.utc), files_changed=[], additions=0, deletions=0, ) ) return commits return await asyncio.to_thread(_get_history) finally: shutil.rmtree(os.path.dirname(repo_path), ignore_errors=True) async def get_head_sha(self, agent_id: str, org_id: str) -> str: """Get the current HEAD commit SHA. Args: agent_id: Agent ID org_id: Organization ID Returns: HEAD commit SHA """ self._check_git() repo_path = await self._download_repo(agent_id, org_id) try: def _get_head(): result = _run_git(["rev-parse", "HEAD"], cwd=repo_path) return result.stdout.strip() return await asyncio.to_thread(_get_head) finally: shutil.rmtree(os.path.dirname(repo_path), ignore_errors=True) async def delete_repo(self, agent_id: str, org_id: str) -> None: """Delete an agent's repository from storage. Args: agent_id: Agent ID org_id: Organization ID """ storage_prefix = self._repo_path(agent_id, org_id) await self.storage.delete_prefix(storage_prefix) logger.info(f"Deleted repository for agent {agent_id}")
{ "repo_id": "letta-ai/letta", "file_path": "letta/services/memory_repo/git_operations.py", "license": "Apache License 2.0", "lines": 529, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
letta-ai/letta:letta/services/memory_repo/memfs_client_base.py
"""Local filesystem-based client for git memory operations. This is the open-source implementation that stores git repositories on the local filesystem (~/.letta/memfs/ by default). This enables git-backed memory for self-hosted deployments without external dependencies. The cloud/enterprise version (memfs_client.py) connects to the memfs HTTP service instead. """ import hashlib import os import uuid from typing import List, Optional from letta.constants import CORE_MEMORY_BLOCK_CHAR_LIMIT from letta.log import get_logger from letta.otel.tracing import trace_method from letta.schemas.block import Block as PydanticBlock from letta.schemas.memory_repo import MemoryCommit from letta.schemas.user import User as PydanticUser from letta.services.memory_repo.block_markdown import parse_block_markdown, serialize_block from letta.services.memory_repo.git_operations import GitOperations from letta.services.memory_repo.path_mapping import memory_block_label_from_markdown_path from letta.services.memory_repo.storage.local import LocalStorageBackend from letta.utils import enforce_types logger = get_logger(__name__) # File paths within the memory repository (blocks stored at repo root as {label}.md) # Default local storage path DEFAULT_LOCAL_PATH = os.path.expanduser("~/.letta/memfs") class MemfsClient: """Local filesystem-based client for git memory operations. Provides the same interface as the cloud MemfsClient but stores repositories on the local filesystem using LocalStorageBackend. This enables git-backed memory for self-hosted OSS deployments. """ def __init__(self, base_url: str | None = None, local_path: str | None = None, timeout: float = 120.0): """Initialize the local memfs client. Args: base_url: Ignored (for interface compatibility with cloud client) local_path: Path for local storage (default: ~/.letta/memfs) timeout: Ignored (for interface compatibility) """ self.local_path = local_path or DEFAULT_LOCAL_PATH self.storage = LocalStorageBackend(base_path=self.local_path) self.git = GitOperations(storage=self.storage, redis_client=None) logger.info(f"MemfsClient initialized with local storage at {self.local_path}") async def close(self): """Close the client (no-op for local storage).""" pass # ========================================================================= # Repository Operations # ========================================================================= @enforce_types @trace_method async def create_repo_async( self, agent_id: str, actor: PydanticUser, initial_blocks: List[PydanticBlock] | None = None, ) -> str: """Create a new repository for an agent with optional initial blocks. Args: agent_id: Agent ID actor: User performing the operation initial_blocks: Optional list of blocks to commit as initial state Returns: The HEAD SHA of the created repository """ initial_blocks = initial_blocks or [] org_id = actor.organization_id # Build initial files from blocks (frontmatter embeds metadata) initial_files = {} for block in initial_blocks: file_path = f"{block.label}.md" initial_files[file_path] = serialize_block( value=block.value or "", description=block.description, limit=block.limit, read_only=block.read_only, metadata=block.metadata, ) return await self.git.create_repo( agent_id=agent_id, org_id=org_id, initial_files=initial_files, author_name=f"User {actor.id}", author_email=f"{actor.id}@letta.ai", ) # ========================================================================= # Block Operations (Read) # ========================================================================= @enforce_types @trace_method async def get_blocks_async( self, agent_id: str, actor: PydanticUser, ref: str = "HEAD", ) -> List[PydanticBlock]: """Get all memory blocks at a specific ref. Args: agent_id: Agent ID actor: User performing the operation ref: Git ref (commit SHA, branch name, or 'HEAD') Returns: List of memory blocks """ org_id = actor.organization_id try: files = await self.git.get_files(agent_id, org_id, ref) except FileNotFoundError: return [] # Convert block files to PydanticBlock (metadata is in frontmatter). # skills/{skill_name}/SKILL.md is mapped to block label skills/{skill_name}; # other files under skills/ are intentionally ignored. blocks = [] for file_path, content in files.items(): label = memory_block_label_from_markdown_path(file_path) if label is None: continue parsed = parse_block_markdown(content) synthetic_uuid = uuid.UUID(hashlib.md5(f"{agent_id}:{label}".encode()).hexdigest()) blocks.append( PydanticBlock( id=f"block-{synthetic_uuid}", label=label, value=parsed["value"], description=parsed.get("description"), limit=parsed.get("limit", CORE_MEMORY_BLOCK_CHAR_LIMIT), read_only=parsed.get("read_only", False), metadata=parsed.get("metadata", {}), ) ) return blocks @enforce_types @trace_method async def get_block_async( self, agent_id: str, label: str, actor: PydanticUser, ref: str = "HEAD", ) -> Optional[PydanticBlock]: """Get a specific memory block. Args: agent_id: Agent ID label: Block label actor: User performing the operation ref: Git ref Returns: Memory block or None """ blocks = await self.get_blocks_async(agent_id, actor, ref) for block in blocks: if block.label == label: return block return None # ========================================================================= # Block Operations (Write) # ========================================================================= async def _ensure_repo_exists(self, agent_id: str, actor: PydanticUser) -> str: """Ensure the repository exists, creating if needed.""" try: return await self.git.get_head_sha(agent_id, actor.organization_id) except FileNotFoundError: return await self.git.create_repo( agent_id=agent_id, org_id=actor.organization_id, initial_files={}, author_name=f"User {actor.id}", author_email=f"{actor.id}@letta.ai", ) @enforce_types @trace_method async def update_block_async( self, agent_id: str, label: str, value: str, actor: PydanticUser, message: Optional[str] = None, *, description: Optional[str] = None, limit: Optional[int] = None, read_only: bool = False, metadata: Optional[dict] = None, ) -> MemoryCommit: """Update a memory block. Args: agent_id: Agent ID label: Block label value: New block value actor: User performing the operation message: Optional commit message description: Block description (for frontmatter) limit: Block character limit (for frontmatter) read_only: Block read-only flag (for frontmatter) metadata: Block metadata dict (for frontmatter) Returns: Commit details """ from letta.schemas.memory_repo import FileChange await self._ensure_repo_exists(agent_id, actor) file_path = f"{label}.md" file_content = serialize_block( value=value, description=description, limit=limit, read_only=read_only, metadata=metadata, ) commit_message = message or f"Update {label}" return await self.git.commit( agent_id=agent_id, org_id=actor.organization_id, changes=[FileChange(path=file_path, content=file_content, change_type="modify")], message=commit_message, author_name=f"User {actor.id}", author_email=f"{actor.id}@letta.ai", ) @enforce_types @trace_method async def create_block_async( self, agent_id: str, block: PydanticBlock, actor: PydanticUser, message: Optional[str] = None, ) -> MemoryCommit: """Create a new memory block. Args: agent_id: Agent ID block: Block to create actor: User performing the operation message: Optional commit message Returns: Commit details """ from letta.schemas.memory_repo import FileChange await self._ensure_repo_exists(agent_id, actor) org_id = actor.organization_id file_content = serialize_block( value=block.value or "", description=block.description, limit=block.limit, read_only=block.read_only, metadata=block.metadata, ) changes = [ FileChange( path=f"{block.label}.md", content=file_content, change_type="add", ), ] commit_message = message or f"Create block {block.label}" return await self.git.commit( agent_id=agent_id, org_id=org_id, changes=changes, message=commit_message, author_name=f"User {actor.id}", author_email=f"{actor.id}@letta.ai", ) @enforce_types @trace_method async def delete_block_async( self, agent_id: str, label: str, actor: PydanticUser, message: Optional[str] = None, ) -> MemoryCommit: """Delete a memory block. Args: agent_id: Agent ID label: Block label to delete actor: User performing the operation message: Optional commit message Returns: Commit details """ from letta.schemas.memory_repo import FileChange await self._ensure_repo_exists(agent_id, actor) org_id = actor.organization_id changes = [ FileChange( path=f"{label}.md", content=None, change_type="delete", ), ] commit_message = message or f"Delete block {label}" return await self.git.commit( agent_id=agent_id, org_id=org_id, changes=changes, message=commit_message, author_name=f"User {actor.id}", author_email=f"{actor.id}@letta.ai", ) # ========================================================================= # History Operations # ========================================================================= @enforce_types @trace_method async def get_history_async( self, agent_id: str, actor: PydanticUser, path: Optional[str] = None, limit: int = 50, ) -> List[MemoryCommit]: """Get commit history. Args: agent_id: Agent ID actor: User performing the operation path: Optional file path to filter by limit: Maximum commits to return Returns: List of commits, newest first """ try: return await self.git.get_history( agent_id=agent_id, org_id=actor.organization_id, path=path, limit=limit, ) except FileNotFoundError: return []
{ "repo_id": "letta-ai/letta", "file_path": "letta/services/memory_repo/memfs_client_base.py", "license": "Apache License 2.0", "lines": 328, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
letta-ai/letta:letta/services/memory_repo/storage/base.py
"""Abstract base class for storage backends.""" from abc import ABC, abstractmethod from typing import List class StorageBackend(ABC): """Abstract storage backend for memory repositories. Provides a unified interface for storing git repository objects in various object storage systems (GCS, S3, local filesystem). """ @property @abstractmethod def bucket_name(self) -> str: """Return the bucket/container name.""" pass @abstractmethod async def upload_bytes(self, path: str, content: bytes) -> None: """Upload bytes to the given path. Args: path: Path within the bucket (e.g., "org-123/agent-456/objects/pack/pack-abc.pack") content: Raw bytes to upload """ pass @abstractmethod async def download_bytes(self, path: str) -> bytes: """Download bytes from the given path. Args: path: Path within the bucket Returns: Raw bytes content Raises: FileNotFoundError: If the path doesn't exist """ pass @abstractmethod async def exists(self, path: str) -> bool: """Check if a path exists. Args: path: Path within the bucket Returns: True if the path exists """ pass @abstractmethod async def delete(self, path: str) -> None: """Delete a file at the given path. Args: path: Path within the bucket Raises: FileNotFoundError: If the path doesn't exist """ pass @abstractmethod async def list_files(self, prefix: str) -> List[str]: """List all files with the given prefix. Args: prefix: Path prefix to filter by Returns: List of full paths matching the prefix """ pass @abstractmethod async def delete_prefix(self, prefix: str) -> int: """Delete all files with the given prefix. Args: prefix: Path prefix to delete Returns: Number of files deleted """ pass async def upload_text(self, path: str, content: str, encoding: str = "utf-8") -> None: """Upload text content to the given path. Args: path: Path within the bucket content: Text content to upload encoding: Text encoding (default: utf-8) """ await self.upload_bytes(path, content.encode(encoding)) async def download_text(self, path: str, encoding: str = "utf-8") -> str: """Download text content from the given path. Args: path: Path within the bucket encoding: Text encoding (default: utf-8) Returns: Text content """ content = await self.download_bytes(path) return content.decode(encoding) async def copy(self, source_path: str, dest_path: str) -> None: """Copy a file from source to destination. Default implementation downloads and re-uploads. Subclasses may override with more efficient implementations. Args: source_path: Source path dest_path: Destination path """ content = await self.download_bytes(source_path) await self.upload_bytes(dest_path, content)
{ "repo_id": "letta-ai/letta", "file_path": "letta/services/memory_repo/storage/base.py", "license": "Apache License 2.0", "lines": 96, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
letta-ai/letta:letta/services/memory_repo/storage/local.py
"""Local filesystem storage backend for memory repositories. This backend stores git repository data on the local filesystem, making git-backed memory available without external dependencies. Ideal for self-hosted OSS deployments. """ import os import shutil from pathlib import Path from typing import List, Optional from letta.log import get_logger from letta.services.memory_repo.storage.base import StorageBackend logger = get_logger(__name__) class LocalStorageBackend(StorageBackend): """Local filesystem storage backend for memory repositories. Stores repository data under a configurable base path, defaulting to ~/.letta/memfs/. This enables git-backed memory for self-hosted deployments without requiring cloud storage. Directory structure: {base_path}/{prefix}/{org_id}/{agent_id}/repo.git/ """ def __init__( self, base_path: Optional[str] = None, prefix: str = "repository", ): """Initialize local storage backend. Args: base_path: Base directory for storage (default: ~/.letta/memfs) prefix: Prefix for all paths in this backend (default: "repository") """ if base_path is None: base_path = os.path.expanduser("~/.letta/memfs") self._base_path = Path(base_path) self._prefix = prefix.rstrip("/") self._bucket_name = "local" # For interface compatibility # Ensure base directory exists self._base_path.mkdir(parents=True, exist_ok=True) logger.debug(f"LocalStorageBackend initialized at {self._base_path}") def _full_path(self, path: str) -> Path: """Get full filesystem path including prefix.""" path = path.lstrip("/") if self._prefix: return self._base_path / self._prefix / path return self._base_path / path @property def bucket_name(self) -> str: """Return the bucket name (for interface compatibility).""" return self._bucket_name async def upload_bytes(self, path: str, content: bytes) -> None: """Write bytes to a local file.""" full_path = self._full_path(path) full_path.parent.mkdir(parents=True, exist_ok=True) with open(full_path, "wb") as f: f.write(content) logger.debug(f"Wrote {len(content)} bytes to {full_path}") async def download_bytes(self, path: str) -> bytes: """Read bytes from a local file.""" full_path = self._full_path(path) if not full_path.exists(): raise FileNotFoundError(f"{full_path} not found") with open(full_path, "rb") as f: return f.read() async def exists(self, path: str) -> bool: """Check if a path exists.""" full_path = self._full_path(path) return full_path.exists() async def delete(self, path: str) -> None: """Delete a file.""" full_path = self._full_path(path) if not full_path.exists(): raise FileNotFoundError(f"{full_path} not found") full_path.unlink() logger.debug(f"Deleted {full_path}") async def list_files(self, prefix: str) -> List[str]: """List all files with the given prefix.""" full_prefix = self._full_path(prefix) if not full_prefix.exists(): return [] result = [] if full_prefix.is_file(): # Prefix is a file, return it rel_path = str(full_prefix.relative_to(self._base_path / self._prefix)) result.append(rel_path) else: # Walk directory for file_path in full_prefix.rglob("*"): if file_path.is_file(): rel_path = str(file_path.relative_to(self._base_path / self._prefix)) result.append(rel_path) return result async def delete_prefix(self, prefix: str) -> int: """Delete all files with the given prefix.""" full_prefix = self._full_path(prefix) if not full_prefix.exists(): return 0 # Count files before deletion count = sum(1 for _ in full_prefix.rglob("*") if _.is_file()) if full_prefix.is_file(): full_prefix.unlink() count = 1 else: shutil.rmtree(full_prefix, ignore_errors=True) logger.debug(f"Deleted {count} files with prefix {prefix}") return count async def copy(self, source_path: str, dest_path: str) -> None: """Copy a file.""" source_full = self._full_path(source_path) dest_full = self._full_path(dest_path) if not source_full.exists(): raise FileNotFoundError(f"{source_full} not found") dest_full.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(source_full, dest_full) logger.debug(f"Copied {source_full} to {dest_full}")
{ "repo_id": "letta-ai/letta", "file_path": "letta/services/memory_repo/storage/local.py", "license": "Apache License 2.0", "lines": 113, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
letta-ai/letta:letta/services/summarizer/compact.py
"""Standalone compaction functions for message summarization.""" from dataclasses import dataclass from typing import List, Optional from letta.helpers.message_helper import convert_message_creates_to_messages from letta.llm_api.llm_client import LLMClient from letta.log import get_logger from letta.otel.tracing import trace_method from letta.schemas.agent import AgentType from letta.schemas.enums import MessageRole from letta.schemas.letta_message_content import TextContent from letta.schemas.llm_config import LLMConfig from letta.schemas.message import Message, MessageCreate from letta.schemas.user import User from letta.services.summarizer.self_summarizer import self_summarize_all, self_summarize_sliding_window from letta.services.summarizer.summarizer_all import summarize_all from letta.services.summarizer.summarizer_config import CompactionSettings, get_default_prompt_for_mode, get_default_summarizer_model from letta.services.summarizer.summarizer_sliding_window import ( count_tokens, count_tokens_with_tools, summarize_via_sliding_window, ) from letta.services.telemetry_manager import TelemetryManager from letta.system import package_summarize_message_no_counts logger = get_logger(__name__) @dataclass class CompactResult: """Result of a compaction operation.""" summary_message: Message compacted_messages: list[Message] summary_text: str context_token_estimate: Optional[int] async def build_summarizer_llm_config( agent_llm_config: LLMConfig, summarizer_config: CompactionSettings, actor: User, ) -> LLMConfig: """Derive an LLMConfig for summarization from a model handle. This mirrors the agent-creation path: start from the agent's LLMConfig, override provider/model/handle from ``compaction_settings.model``, and then apply any explicit ``compaction_settings.model_settings`` via ``_to_legacy_config_params``. Args: agent_llm_config: The agent's LLM configuration to use as base. summarizer_config: Compaction settings with optional model override. actor: The user performing the operation. Returns: LLMConfig configured for summarization. """ from letta.schemas.enums import ProviderType # If no summarizer model specified, use lightweight provider-specific defaults if not summarizer_config.model: provider_name = agent_llm_config.provider_name or agent_llm_config.model_endpoint_type try: provider_type = ProviderType(provider_name) default_model = get_default_summarizer_model(provider_type=provider_type) if default_model: # Use default model summarizer_config = summarizer_config.model_copy(update={"model": default_model}) except (ValueError, TypeError): pass # Unknown provider - will fall back to agent's model below # If still no model after defaults, use agent's model if not summarizer_config.model: return agent_llm_config try: # Load default config for the summarizer model handle, using the agent's context window from letta.services.provider_manager import ProviderManager provider_manager = ProviderManager() try: # automatically sets the context window to the max available for the summarizer model base = await provider_manager.get_llm_config_from_handle( handle=summarizer_config.model, actor=actor, ) except Exception as e: logger.warning( f"Failed to load LLM config for summarizer handle '{summarizer_config.model}': {e}. Falling back to agent's LLM config." ) return agent_llm_config # If explicit model_settings are provided for the summarizer, apply # them just like server.create_agent_async does for agents. if summarizer_config.model_settings is not None: update_params = summarizer_config.model_settings._to_legacy_config_params() # Don't clobber max_tokens with the Pydantic default when the caller # didn't explicitly provide max_output_tokens. if "max_output_tokens" not in summarizer_config.model_settings.model_fields_set: update_params.pop("max_tokens", None) return base.model_copy(update=update_params) return base except Exception: # On any error, do not break the agent – just fall back return agent_llm_config @trace_method async def compact_messages( actor: User, agent_id: str, agent_llm_config: LLMConfig, telemetry_manager: TelemetryManager, llm_client: LLMClient, agent_type: AgentType, messages: List[Message], timezone: str, compaction_settings: Optional[CompactionSettings] = None, agent_tags: Optional[List[str]] = None, tools: Optional[List[dict]] = None, # Tool json schemas trigger_threshold: Optional[int] = None, run_id: Optional[str] = None, step_id: Optional[str] = None, use_summary_role: bool = True, trigger: Optional[str] = None, context_tokens_before: Optional[int] = None, messages_count_before: Optional[int] = None, ) -> CompactResult: """Compact in-context messages using summarization. Args: actor: The user performing the operation. agent_id: The agent's ID. agent_llm_config: The agent's LLM configuration. messages: The in-context messages to compact. timezone: The agent's timezone for message formatting. compaction_settings: Optional compaction settings override. agent_model_handle: The agent's model handle (used if compaction_settings is None). agent_tags: The agent's tags for telemetry. tools: The agent's tools (for token counting). trigger_threshold: If provided, verify context stays below this after compaction. run_id: Optional run ID for telemetry. step_id: Optional step ID for telemetry. use_summary_role: If True, create summary message with role=summary. trigger: What triggered the compaction (for stats). context_tokens_before: Token count before compaction (for stats). messages_count_before: Message count before compaction (for stats). Returns: CompactResult containing the summary message, compacted messages, summary text, and updated context token estimate. """ summarizer_config = compaction_settings if compaction_settings else CompactionSettings() # Build the LLMConfig used for summarization summarizer_llm_config = await build_summarizer_llm_config( agent_llm_config=agent_llm_config, # used to set default compaction model summarizer_config=summarizer_config, actor=actor, ) summarization_mode_used = summarizer_config.mode if summarizer_config.mode == "self_compact_all": try: summary, compacted_messages = await self_summarize_all( actor=actor, agent_id=agent_id, agent_llm_config=agent_llm_config, telemetry_manager=telemetry_manager, llm_client=llm_client, agent_type=agent_type, messages=messages, compaction_settings=summarizer_config, run_id=run_id, step_id=step_id, timezone=timezone, agent_tags=agent_tags, tools=tools, ) except Exception as e: logger.error(f"Self summarization failed with exception: {str(e)}. Falling back to self sliding window mode.") try: fallback_config = summarizer_config.model_copy( update={ "mode": "self_compact_sliding_window", "prompt": get_default_prompt_for_mode("self_compact_sliding_window"), } ) summary, compacted_messages = await self_summarize_sliding_window( actor=actor, agent_id=agent_id, agent_llm_config=agent_llm_config, telemetry_manager=telemetry_manager, llm_client=llm_client, agent_type=agent_type, messages=messages, compaction_settings=fallback_config, run_id=run_id, step_id=step_id, timezone=timezone, agent_tags=agent_tags, tools=tools, ) summarization_mode_used = "self_compact_sliding_window" except Exception as e: logger.error(f"Self sliding window summarization failed with exception: {str(e)}. Falling back to all mode.") fallback_config = summarizer_config.model_copy( update={ "mode": "all", "prompt": get_default_prompt_for_mode("all"), } ) summary, compacted_messages = await summarize_all( actor=actor, llm_config=summarizer_llm_config, summarizer_config=fallback_config, in_context_messages=messages, agent_id=agent_id, agent_tags=agent_tags, run_id=run_id, step_id=step_id, ) summarization_mode_used = "all" elif summarizer_config.mode == "self_compact_sliding_window": try: summary, compacted_messages = await self_summarize_sliding_window( actor=actor, agent_id=agent_id, agent_llm_config=agent_llm_config, telemetry_manager=telemetry_manager, llm_client=llm_client, agent_type=agent_type, messages=messages, compaction_settings=summarizer_config, run_id=run_id, step_id=step_id, timezone=timezone, agent_tags=agent_tags, tools=tools, ) except Exception as e: # Prompts for all and self mode should be similar --> can use original prompt logger.error(f"Self sliding window summarization failed with exception: {str(e)}. Falling back to all mode.") fallback_config = summarizer_config.model_copy( update={ "mode": "all", "prompt": get_default_prompt_for_mode("all"), } ) summary, compacted_messages = await summarize_all( actor=actor, llm_config=summarizer_llm_config, summarizer_config=fallback_config, in_context_messages=messages, agent_id=agent_id, agent_tags=agent_tags, run_id=run_id, step_id=step_id, ) summarization_mode_used = "all" elif summarizer_config.mode == "all": summary, compacted_messages = await summarize_all( actor=actor, llm_config=summarizer_llm_config, summarizer_config=summarizer_config, in_context_messages=messages, agent_id=agent_id, agent_tags=agent_tags, run_id=run_id, step_id=step_id, ) elif summarizer_config.mode == "sliding_window": try: summary, compacted_messages = await summarize_via_sliding_window( actor=actor, llm_config=summarizer_llm_config, agent_llm_config=agent_llm_config, summarizer_config=summarizer_config, in_context_messages=messages, agent_id=agent_id, agent_tags=agent_tags, run_id=run_id, step_id=step_id, ) except Exception as e: logger.error(f"Sliding window summarization failed with exception: {str(e)}. Falling back to all mode.") fallback_config = summarizer_config.model_copy( update={ "mode": "all", "prompt": get_default_prompt_for_mode("all"), } ) summary, compacted_messages = await summarize_all( actor=actor, llm_config=summarizer_llm_config, summarizer_config=fallback_config, in_context_messages=messages, agent_id=agent_id, agent_tags=agent_tags, run_id=run_id, step_id=step_id, ) summarization_mode_used = "all" else: raise ValueError(f"Invalid summarizer mode: {summarizer_config.mode}") # Update the token count (including tools for accurate comparison with LLM's prompt_tokens) context_token_estimate = await count_tokens_with_tools( actor=actor, llm_config=agent_llm_config, messages=compacted_messages, tools=tools or [], ) logger.info(f"Context token estimate after summarization: {context_token_estimate}") # If the trigger_threshold is provided, verify the new token count is below it if trigger_threshold is not None and context_token_estimate is not None and context_token_estimate >= trigger_threshold: logger.error( "Summarization failed to sufficiently reduce context size: " f"post-summarization tokens={context_token_estimate}, " f"threshold={trigger_threshold}. " "Attempting fallback strategies.", ) # If we used the sliding window mode, try to summarize again with the all mode if summarization_mode_used == "sliding_window": summary, compacted_messages = await summarize_all( actor=actor, llm_config=agent_llm_config, summarizer_config=summarizer_config, in_context_messages=compacted_messages, agent_id=agent_id, agent_tags=agent_tags, run_id=run_id, step_id=step_id, ) summarization_mode_used = "all" context_token_estimate = await count_tokens_with_tools( actor=actor, llm_config=agent_llm_config, messages=compacted_messages, tools=tools or [], ) # Final edge case: check if we're still over threshold if context_token_estimate is not None and context_token_estimate >= trigger_threshold: # Check if system prompt is the cause system_prompt_token_estimate = await count_tokens( actor=actor, llm_config=agent_llm_config, messages=[compacted_messages[0]], ) if system_prompt_token_estimate is not None and system_prompt_token_estimate >= agent_llm_config.context_window: from letta.errors import SystemPromptTokenExceededError raise SystemPromptTokenExceededError( system_prompt_token_estimate=system_prompt_token_estimate, context_window=agent_llm_config.context_window, ) # Log error but don't brick the agent logger.error(f"Failed to summarize messages after fallback: {context_token_estimate} > {trigger_threshold}") else: logger.info(f"Summarization fallback succeeded: {context_token_estimate} < {trigger_threshold}") # Build compaction stats if we have the before values compaction_stats = None if trigger and context_tokens_before is not None and messages_count_before is not None: compaction_stats = { "trigger": trigger, "context_tokens_before": context_tokens_before, "context_tokens_after": context_token_estimate, "context_window": agent_llm_config.context_window, "messages_count_before": messages_count_before, "messages_count_after": len(compacted_messages) + 1, } # Create the summary message summary_message_str_packed = package_summarize_message_no_counts( summary=summary, timezone=timezone, compaction_stats=compaction_stats, mode=summarization_mode_used, ) if use_summary_role: # New behavior: Create Message directly with role=summary summary_message_obj = Message( role=MessageRole.summary, content=[TextContent(text=summary_message_str_packed)], agent_id=agent_id, run_id=run_id, step_id=step_id, ) else: # Legacy behavior: Use convert_message_creates_to_messages with role=user summary_messages = await convert_message_creates_to_messages( message_creates=[ MessageCreate( role=MessageRole.user, content=[TextContent(text=summary_message_str_packed)], ) ], agent_id=agent_id, timezone=timezone, wrap_user_message=False, wrap_system_message=False, run_id=run_id, ) if len(summary_messages) != 1: logger.error(f"Expected only one summary message, got {len(summary_messages)}") summary_message_obj = summary_messages[0] # Build final messages: [system] + [summary] + remaining compacted messages final_messages = [compacted_messages[0], summary_message_obj] if len(compacted_messages) > 1: final_messages += compacted_messages[1:] return CompactResult( summary_message=summary_message_obj, compacted_messages=final_messages, summary_text=summary, context_token_estimate=context_token_estimate, )
{ "repo_id": "letta-ai/letta", "file_path": "letta/services/summarizer/compact.py", "license": "Apache License 2.0", "lines": 393, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
letta-ai/letta:letta/test_gemini.py
from letta_client import Letta def create_agent() -> None: client = Letta(base_url="http://localhost:8283") agent_state = client.agents.create( name="test-gemini-3-pro-agent", model="google_ai/gemini-3.1-pro-preview", embedding="openai/text-embedding-3-small", context_window_limit=16000, ) print("Created agent: ", agent_state) def main(): create_agent() if __name__ == "__main__": main()
{ "repo_id": "letta-ai/letta", "file_path": "letta/test_gemini.py", "license": "Apache License 2.0", "lines": 14, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
letta-ai/letta:tests/integration_test_clickhouse_llm_traces.py
""" Integration tests for ClickHouse-backed LLM raw traces. Validates that: 1) Agent message requests are stored in ClickHouse (request_json contains the message) 2) Summarization traces are stored and retrievable by step_id 3) Error traces are stored with is_error, error_type, and error_message 4) llm_config_json is properly stored 5) Cache and usage statistics are stored (cached_input_tokens, cache_write_tokens, reasoning_tokens) """ import asyncio import json import os import time import uuid import pytest from letta.agents.letta_agent_v3 import LettaAgentV3 from letta.config import LettaConfig from letta.schemas.agent import CreateAgent from letta.schemas.embedding_config import EmbeddingConfig from letta.schemas.enums import MessageRole from letta.schemas.letta_message_content import TextContent from letta.schemas.llm_config import LLMConfig from letta.schemas.message import Message, MessageCreate from letta.schemas.run import Run from letta.server.server import SyncServer from letta.services.llm_trace_reader import get_llm_trace_reader from letta.services.provider_trace_backends import get_provider_trace_backends from letta.services.summarizer.summarizer import simple_summary from letta.settings import settings, telemetry_settings def _require_clickhouse_env() -> dict[str, str]: endpoint = os.getenv("CLICKHOUSE_ENDPOINT") password = os.getenv("CLICKHOUSE_PASSWORD") if not endpoint or not password: pytest.skip("ClickHouse env vars not set (CLICKHOUSE_ENDPOINT, CLICKHOUSE_PASSWORD)") return { "endpoint": endpoint, "password": password, "username": os.getenv("CLICKHOUSE_USERNAME", "default"), "database": os.getenv("CLICKHOUSE_DATABASE", "otel"), } def _anthropic_llm_config() -> LLMConfig: return LLMConfig( model="claude-haiku-4-5-20251001", model_endpoint_type="anthropic", model_endpoint="https://api.anthropic.com/v1", context_window=200000, max_tokens=2048, put_inner_thoughts_in_kwargs=False, enable_reasoner=False, ) @pytest.fixture async def server(): config = LettaConfig.load() config.save() server = SyncServer(init_with_default_org_and_user=True) await server.init_async() await server.tool_manager.upsert_base_tools_async(actor=server.default_user) yield server @pytest.fixture async def actor(server: SyncServer): return server.default_user @pytest.fixture def clickhouse_settings(): env = _require_clickhouse_env() original_values = { "endpoint": settings.clickhouse_endpoint, "username": settings.clickhouse_username, "password": settings.clickhouse_password, "database": settings.clickhouse_database, "store_llm_traces": settings.store_llm_traces, "provider_trace_backend": telemetry_settings.provider_trace_backend, } settings.clickhouse_endpoint = env["endpoint"] settings.clickhouse_username = env["username"] settings.clickhouse_password = env["password"] settings.clickhouse_database = env["database"] settings.store_llm_traces = True # Configure telemetry to use clickhouse backend (set the underlying field, not the property) telemetry_settings.provider_trace_backend = "clickhouse" # Clear the cached backends so they get recreated with new settings get_provider_trace_backends.cache_clear() yield settings.clickhouse_endpoint = original_values["endpoint"] settings.clickhouse_username = original_values["username"] settings.clickhouse_password = original_values["password"] settings.clickhouse_database = original_values["database"] settings.store_llm_traces = original_values["store_llm_traces"] telemetry_settings.provider_trace_backend = original_values["provider_trace_backend"] # Clear cache again to restore original backends get_provider_trace_backends.cache_clear() async def _wait_for_raw_trace(step_id: str, organization_id: str, timeout_seconds: int = 30): """Wait for a trace to appear in ClickHouse. With async_insert + wait_for_async_insert=1, traces should appear quickly, but we poll to handle any propagation delay. """ reader = get_llm_trace_reader() deadline = time.time() + timeout_seconds while time.time() < deadline: trace = await reader.get_by_step_id_async(step_id=step_id, organization_id=organization_id) if trace is not None: return trace await asyncio.sleep(0.5) raise AssertionError(f"Timed out waiting for raw trace with step_id={step_id}") @pytest.mark.asyncio async def test_agent_message_stored_in_clickhouse(server: SyncServer, actor, clickhouse_settings): """Test that agent step traces are stored with all fields including llm_config_json.""" message_text = f"ClickHouse trace test {uuid.uuid4()}" llm_config = _anthropic_llm_config() agent_state = await server.agent_manager.create_agent_async( CreateAgent( name=f"clickhouse_agent_{uuid.uuid4().hex[:8]}", llm_config=llm_config, embedding_config=EmbeddingConfig.default_config(model_name="letta"), ), actor=actor, ) agent = LettaAgentV3(agent_state=agent_state, actor=actor) run = await server.run_manager.create_run( Run(agent_id=agent_state.id), actor=actor, ) run_id = run.id response = await agent.step( [MessageCreate(role=MessageRole.user, content=[TextContent(text=message_text)])], run_id=run_id, ) step_id = next(msg.step_id for msg in reversed(response.messages) if msg.step_id) trace = await _wait_for_raw_trace(step_id=step_id, organization_id=actor.organization_id) # Basic trace fields assert trace.step_id == step_id assert message_text in trace.request_json assert trace.is_error is False assert trace.error_type is None assert trace.error_message is None # Verify llm_config_json is stored and contains expected fields assert trace.llm_config_json, "llm_config_json should not be empty" config_data = json.loads(trace.llm_config_json) assert config_data.get("model") == llm_config.model assert "context_window" in config_data assert "max_tokens" in config_data # Token usage should be populated assert trace.prompt_tokens > 0 assert trace.completion_tokens >= 0 assert trace.total_tokens > 0 @pytest.mark.asyncio async def test_summary_stored_with_content_and_usage(server: SyncServer, actor, clickhouse_settings): """Test that summarization traces are stored with content, usage, and cache info.""" step_id = f"step-{uuid.uuid4()}" llm_config = _anthropic_llm_config() summary_source_messages = [ Message(role=MessageRole.system, content=[TextContent(text="System prompt")]), Message(role=MessageRole.user, content=[TextContent(text="User message 1")]), Message(role=MessageRole.assistant, content=[TextContent(text="Assistant response 1")]), Message(role=MessageRole.user, content=[TextContent(text="User message 2")]), ] summary_text = await simple_summary( messages=summary_source_messages, llm_config=llm_config, actor=actor, agent_id=f"agent-{uuid.uuid4()}", agent_tags=["test", "clickhouse"], run_id=f"run-{uuid.uuid4()}", step_id=step_id, compaction_settings={"mode": "partial_evict", "message_buffer_limit": 60}, ) trace = await _wait_for_raw_trace(step_id=step_id, organization_id=actor.organization_id) # Basic assertions assert trace.step_id == step_id assert trace.call_type == "summarization" assert trace.is_error is False # Verify llm_config_json is stored assert trace.llm_config_json, "llm_config_json should not be empty" config_data = json.loads(trace.llm_config_json) assert config_data.get("model") == llm_config.model # Verify summary content in response summary_in_response = False try: response_payload = json.loads(trace.response_json) if isinstance(response_payload, dict): if "choices" in response_payload: content = response_payload.get("choices", [{}])[0].get("message", {}).get("content", "") summary_in_response = summary_text.strip() in (content or "") elif "content" in response_payload: summary_in_response = summary_text.strip() in (response_payload.get("content") or "") except Exception: summary_in_response = False assert summary_in_response or summary_text in trace.response_json # Token usage should be populated assert trace.prompt_tokens > 0 assert trace.total_tokens > 0 # Cache fields may or may not be populated depending on provider response # Just verify they're accessible (not erroring) _ = trace.cached_input_tokens _ = trace.cache_write_tokens _ = trace.reasoning_tokens @pytest.mark.asyncio async def test_error_trace_stored_in_clickhouse(server: SyncServer, actor, clickhouse_settings): """Test that error traces are stored with is_error=True and error details.""" from letta.llm_api.anthropic_client import AnthropicClient step_id = f"step-error-{uuid.uuid4()}" # Create a client with invalid config to trigger an error invalid_llm_config = LLMConfig( model="invalid-model-that-does-not-exist", model_endpoint_type="anthropic", model_endpoint="https://api.anthropic.com/v1", context_window=200000, max_tokens=2048, ) from letta.services.telemetry_manager import TelemetryManager client = AnthropicClient() client.set_telemetry_context( telemetry_manager=TelemetryManager(), agent_id=f"agent-{uuid.uuid4()}", run_id=f"run-{uuid.uuid4()}", step_id=step_id, call_type="agent_step", org_id=actor.organization_id, ) client.actor = actor # Make a request that will fail request_data = { "model": invalid_llm_config.model, "messages": [{"role": "user", "content": "test"}], "max_tokens": 100, } try: await client.request_async_with_telemetry(request_data, invalid_llm_config) except Exception: pass # Expected to fail # Wait for the error trace to be written trace = await _wait_for_raw_trace(step_id=step_id, organization_id=actor.organization_id) # Verify error fields assert trace.step_id == step_id assert trace.is_error is True assert trace.error_type is not None, "error_type should be set for error traces" assert trace.error_message is not None, "error_message should be set for error traces" # Verify llm_config_json is still stored even for errors assert trace.llm_config_json, "llm_config_json should be stored even for error traces" config_data = json.loads(trace.llm_config_json) assert config_data.get("model") == invalid_llm_config.model @pytest.mark.asyncio async def test_cache_tokens_stored_for_anthropic(server: SyncServer, actor, clickhouse_settings): """Test that Anthropic cache tokens (cached_input_tokens, cache_write_tokens) are stored. Note: This test verifies the fields are properly stored when present in the response. Actual cache token values depend on Anthropic's prompt caching behavior. """ message_text = f"Cache test {uuid.uuid4()}" llm_config = _anthropic_llm_config() agent_state = await server.agent_manager.create_agent_async( CreateAgent( name=f"cache_test_agent_{uuid.uuid4().hex[:8]}", llm_config=llm_config, embedding_config=EmbeddingConfig.default_config(model_name="letta"), ), actor=actor, ) agent = LettaAgentV3(agent_state=agent_state, actor=actor) run = await server.run_manager.create_run( Run(agent_id=agent_state.id), actor=actor, ) # Make two requests - second may benefit from caching response1 = await agent.step( [MessageCreate(role=MessageRole.user, content=[TextContent(text=message_text)])], run_id=run.id, ) step_id_1 = next(msg.step_id for msg in reversed(response1.messages) if msg.step_id) response2 = await agent.step( [MessageCreate(role=MessageRole.user, content=[TextContent(text="Follow up question")])], run_id=run.id, ) step_id_2 = next(msg.step_id for msg in reversed(response2.messages) if msg.step_id) # Check traces for both requests trace1 = await _wait_for_raw_trace(step_id=step_id_1, organization_id=actor.organization_id) trace2 = await _wait_for_raw_trace(step_id=step_id_2, organization_id=actor.organization_id) # Verify cache fields are accessible (may be None if no caching occurred) # The important thing is they're stored correctly when present for trace in [trace1, trace2]: assert trace.prompt_tokens > 0 # Cache fields should be stored (may be None or int) assert trace.cached_input_tokens is None or isinstance(trace.cached_input_tokens, int) assert trace.cache_write_tokens is None or isinstance(trace.cache_write_tokens, int) assert trace.reasoning_tokens is None or isinstance(trace.reasoning_tokens, int) # Verify llm_config_json assert trace.llm_config_json config_data = json.loads(trace.llm_config_json) assert config_data.get("model") == llm_config.model
{ "repo_id": "letta-ai/letta", "file_path": "tests/integration_test_clickhouse_llm_traces.py", "license": "Apache License 2.0", "lines": 287, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
letta-ai/letta:tests/integration_test_system_prompt_prefix_caching.py
""" Integration tests for system prompt prefix caching optimization. These tests verify that the system prompt is NOT rebuilt on every step, only after compaction or message reset. This helps preserve prefix caching for LLM providers. """ import pytest from letta_client import Letta @pytest.fixture(scope="module") def client(server_url: str) -> Letta: """Creates and returns a synchronous Letta REST client for testing.""" return Letta(base_url=server_url) @pytest.fixture(scope="function") def agent(client: Letta): """Create a test agent and clean up after test.""" agent_state = client.agents.create( name="test-prefix-cache-agent", include_base_tools=True, model="openai/gpt-4o-mini", embedding="openai/text-embedding-ada-002", ) yield agent_state # Cleanup try: client.agents.delete(agent_state.id) except Exception: pass class TestSystemPromptPrefixCaching: """Test that system prompt stays stable during normal agent execution.""" def test_system_prompt_stable_after_memory_tool_and_messages(self, client: Letta, agent): """ Test workflow: 1. Get initial system prompt and human block value 2. Tell agent to update its memory block using the memory tool 3. Verify block was modified but system prompt hasn't changed 4. Send another message to the agent 5. Verify system prompt still hasn't changed 6. Manually update a block via API 7. Send another message and verify system prompt still hasn't changed (memory block changes are deferred to compaction) """ # Step 1: Get initial context window, system prompt, and human block value initial_context = client.agents.context.retrieve(agent.id) initial_system_prompt = initial_context.system_prompt assert initial_system_prompt, "Initial system prompt should not be empty" # Get initial human block value human_block = None for block in agent.memory.blocks: if block.label == "human": human_block = block break assert human_block, "Agent should have a 'human' memory block" initial_block_value = human_block.value # Step 2: Tell the agent to update its memory using the memory tool response = client.agents.messages.create( agent_id=agent.id, messages=[ { "role": "user", "content": "Please use the core_memory_append tool to add the following to your 'human' block: 'User likes pizza.'", } ], ) assert response.messages, "Agent should respond with messages" # Step 3: Verify block was modified but system prompt hasn't changed # Check that the block was actually modified updated_block = client.blocks.retrieve(human_block.id) assert updated_block.value != initial_block_value, "Memory block should have been modified by the agent" assert "pizza" in updated_block.value.lower(), "Memory block should contain the new content about pizza" # Verify system prompt hasn't changed context_after_memory_update = client.agents.context.retrieve(agent.id) system_prompt_after_memory = context_after_memory_update.system_prompt assert system_prompt_after_memory == initial_system_prompt, ( "System prompt should NOT change after agent uses memory tool (deferred to compaction)" ) # Step 4: Send another message to the agent response2 = client.agents.messages.create( agent_id=agent.id, messages=[ { "role": "user", "content": "What is my favorite food?", } ], ) assert response2.messages, "Agent should respond with messages" # Step 5: Verify system prompt still hasn't changed context_after_second_message = client.agents.context.retrieve(agent.id) system_prompt_after_second = context_after_second_message.system_prompt assert system_prompt_after_second == initial_system_prompt, "System prompt should remain stable after multiple messages" # Step 6: Manually update a block via the API # Find the human block human_block = None for block in agent.memory.blocks: if block.label == "human": human_block = block break assert human_block, "Agent should have a 'human' memory block" # Update the block directly via API client.blocks.modify( block_id=human_block.id, value=human_block.value + "\nUser also likes sushi.", ) # Step 7: Send another message and verify system prompt still hasn't changed response3 = client.agents.messages.create( agent_id=agent.id, messages=[ { "role": "user", "content": "What foods do I like?", } ], ) assert response3.messages, "Agent should respond with messages" # Verify system prompt STILL hasn't changed (deferred to compaction/reset) context_after_manual_update = client.agents.context.retrieve(agent.id) system_prompt_after_manual = context_after_manual_update.system_prompt assert system_prompt_after_manual == initial_system_prompt, ( "System prompt should NOT change after manual block update (deferred to compaction)" ) def test_system_prompt_updates_after_reset(self, client: Letta, agent): """ Test that system prompt IS updated after message reset. 1. Get initial system prompt 2. Manually update a memory block 3. Reset messages 4. Verify system prompt HAS changed to include the new memory """ # Step 1: Get initial system prompt initial_context = client.agents.context.retrieve(agent.id) initial_system_prompt = initial_context.system_prompt # Step 2: Manually update a block via the API human_block = None for block in agent.memory.blocks: if block.label == "human": human_block = block break assert human_block, "Agent should have a 'human' memory block" # Add distinctive text that we can verify in the system prompt new_memory_content = "UNIQUE_TEST_MARKER_12345: User loves ice cream." client.blocks.modify( block_id=human_block.id, value=human_block.value + f"\n{new_memory_content}", ) # Step 3: Reset messages (this should trigger system prompt rebuild) client.agents.messages.reset(agent.id) # Step 4: Verify system prompt HAS changed and includes the new memory context_after_reset = client.agents.context.retrieve(agent.id) system_prompt_after_reset = context_after_reset.system_prompt assert system_prompt_after_reset != initial_system_prompt, "System prompt SHOULD change after message reset" assert "UNIQUE_TEST_MARKER_12345" in system_prompt_after_reset, ( "System prompt should include the updated memory block content after reset" )
{ "repo_id": "letta-ai/letta", "file_path": "tests/integration_test_system_prompt_prefix_caching.py", "license": "Apache License 2.0", "lines": 153, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
letta-ai/letta:tests/test_context_window_calculator.py
from unittest.mock import AsyncMock, MagicMock import pytest from letta.services.context_window_calculator.context_window_calculator import ContextWindowCalculator class TestExtractTagContent: """Tests for the _extract_tag_content helper method""" def test_extracts_simple_tag(self): text = "prefix <tag>content</tag> suffix" result = ContextWindowCalculator._extract_tag_content(text, "tag") assert result == "<tag>content</tag>" def test_returns_none_for_missing_tag(self): text = "no tags here" result = ContextWindowCalculator._extract_tag_content(text, "tag") assert result is None def test_returns_none_for_missing_opening_tag(self): text = "content</tag>" result = ContextWindowCalculator._extract_tag_content(text, "tag") assert result is None def test_returns_none_for_unclosed_tag(self): text = "<tag>content without closing" result = ContextWindowCalculator._extract_tag_content(text, "tag") assert result is None def test_handles_multiline_content(self): text = "<tag>\nline1\nline2\n</tag>" result = ContextWindowCalculator._extract_tag_content(text, "tag") assert result == "<tag>\nline1\nline2\n</tag>" def test_handles_nested_content(self): text = "<outer><inner>nested</inner></outer>" result = ContextWindowCalculator._extract_tag_content(text, "outer") assert result == "<outer><inner>nested</inner></outer>" def test_handles_empty_content(self): text = "<tag></tag>" result = ContextWindowCalculator._extract_tag_content(text, "tag") assert result == "<tag></tag>" def test_extracts_first_occurrence_with_duplicate_tags(self): """When duplicate tags exist, only the first occurrence is extracted""" text = "<tag>first</tag> some text <tag>second</tag>" result = ContextWindowCalculator._extract_tag_content(text, "tag") assert result == "<tag>first</tag>" class TestExtractSystemComponents: """Tests for the extract_system_components method""" def test_extracts_standard_agent_sections(self): """Standard agent with base_instructions, memory_blocks, and memory_metadata""" system_message = """ <base_instructions> Base prompt here </base_instructions> <memory_blocks> Core memory content </memory_blocks> <memory_metadata> Metadata here </memory_metadata> """ result = ContextWindowCalculator.extract_system_components(system_message) assert result["system_prompt"] is not None assert "<base_instructions>" in result["system_prompt"] assert "Base prompt here" in result["system_prompt"] assert result["core_memory"] is not None assert "Core memory content" in result["core_memory"] assert result["external_memory_summary"] is not None assert "<memory_metadata>" in result["external_memory_summary"] # These should be None for standard agent assert result["memory_filesystem"] is None assert result["tool_usage_rules"] is None assert result["directories"] is None def test_extracts_git_enabled_agent_sections(self): """Git-enabled agent has top-level memory_filesystem OUTSIDE memory_blocks""" system_message = ( "<base_instructions>Base</base_instructions>\n" "<memory_filesystem>\n" "memory/\n" " system/\n" " human.md (100 chars)\n" "</memory_filesystem>\n" "<memory_metadata>Meta</memory_metadata>" ) result = ContextWindowCalculator.extract_system_components(system_message) assert result["core_memory"] is None # git-enabled agents don't use <memory_blocks> assert result["memory_filesystem"] is not None assert "memory/" in result["memory_filesystem"] assert "human.md" in result["memory_filesystem"] def test_extracts_tool_usage_rules(self): """Agent with tool usage rules configured""" system_message = """ <base_instructions>Base</base_instructions> <memory_blocks>Memory</memory_blocks> <tool_usage_rules> You must use tools in a specific order. </tool_usage_rules> <memory_metadata>Meta</memory_metadata> """ result = ContextWindowCalculator.extract_system_components(system_message) assert result["tool_usage_rules"] is not None assert "specific order" in result["tool_usage_rules"] def test_extracts_directories(self): """Agent with attached sources has directories section""" system_message = """ <base_instructions>Base</base_instructions> <memory_blocks>Memory</memory_blocks> <directories> <directory name="project"> <file status="open" name="readme.md"> README content </file> </directory> </directories> <memory_metadata>Meta</memory_metadata> """ result = ContextWindowCalculator.extract_system_components(system_message) assert result["directories"] is not None assert '<directory name="project">' in result["directories"] assert "readme.md" in result["directories"] def test_handles_react_agent_no_memory_blocks(self): """React/workflow agents don't render <memory_blocks>""" system_message = """ <base_instructions>React agent base</base_instructions> <directories> Some directory content </directories> <memory_metadata>Meta</memory_metadata> """ result = ContextWindowCalculator.extract_system_components(system_message) assert result["system_prompt"] is not None assert result["core_memory"] is None # No memory_blocks for react agents assert result["directories"] is not None assert result["external_memory_summary"] is not None def test_handles_all_sections_present(self): """Full agent with all optional sections""" system_message = """ <base_instructions>Base instructions</base_instructions> <memory_blocks>Memory blocks content</memory_blocks> <memory_filesystem>Filesystem tree</memory_filesystem> <tool_usage_rules>Tool rules</tool_usage_rules> <directories>Directories content</directories> <memory_metadata>Metadata</memory_metadata> """ result = ContextWindowCalculator.extract_system_components(system_message) assert result["system_prompt"] is not None assert result["core_memory"] is not None assert result["memory_filesystem"] is not None assert result["tool_usage_rules"] is not None assert result["directories"] is not None assert result["external_memory_summary"] is not None def test_handles_empty_string(self): """Empty input returns all None values""" result = ContextWindowCalculator.extract_system_components("") assert all(v is None for v in result.values()) def test_returns_correct_dict_keys(self): """Verify the returned dict has all expected keys""" result = ContextWindowCalculator.extract_system_components("") expected_keys = { "system_prompt", "core_memory", "memory_filesystem", "tool_usage_rules", "directories", "external_memory_summary", } assert set(result.keys()) == expected_keys def test_no_base_instructions_tag_extracts_preamble(self): """Custom system prompts without <base_instructions> should extract preamble text""" system_message = ( "You are a helpful AI agent.\n" "Use the tools available to you.\n\n" "<memory_blocks>\n" "<persona>My name is Letta.</persona>\n" "</memory_blocks>\n\n" "<memory_metadata>Metadata here</memory_metadata>" ) result = ContextWindowCalculator.extract_system_components(system_message) assert result["system_prompt"] is not None assert "helpful AI agent" in result["system_prompt"] assert "Use the tools" in result["system_prompt"] # Should NOT include memory_blocks content assert "<memory_blocks>" not in result["system_prompt"] assert "<memory_metadata>" not in result["system_prompt"] assert result["core_memory"] is not None assert result["external_memory_summary"] is not None def test_nested_memory_filesystem_not_extracted_as_top_level(self): """memory_filesystem block INSIDE memory_blocks should NOT be extracted as top-level""" system_message = ( "You are a self-improving AI agent.\n\n" "<memory_blocks>\n" "The following memory blocks are currently engaged:\n\n" "<memory_filesystem>\n" "<value>\n" "/memory/\n" "\u251c\u2500\u2500 system/\n" "\u2502 \u251c\u2500\u2500 human.md\n" "\u2502 \u2514\u2500\u2500 persona.md\n" "</value>\n" "</memory_filesystem>\n\n" "<persona>My name is Letta.</persona>\n" "</memory_blocks>\n\n" "<memory_metadata>Metadata</memory_metadata>" ) result = ContextWindowCalculator.extract_system_components(system_message) # memory_filesystem is nested inside memory_blocks - should NOT be extracted assert result["memory_filesystem"] is None # core_memory should include the full memory_blocks content (including the nested filesystem) assert result["core_memory"] is not None assert "<memory_filesystem>" in result["core_memory"] assert "human.md" in result["core_memory"] def test_top_level_memory_filesystem_outside_memory_blocks(self): """Top-level memory_filesystem (git-enabled) rendered BEFORE memory_blocks is extracted""" system_message = ( "<base_instructions>Base</base_instructions>\n" "<memory_filesystem>\n" "\u251c\u2500\u2500 system/\n" "\u2502 \u2514\u2500\u2500 human.md\n" "</memory_filesystem>\n\n" "<system/human.md>\n---\ndescription: About the human\n---\nName: Alice\n</system/human.md>\n\n" "<memory_metadata>Meta</memory_metadata>" ) result = ContextWindowCalculator.extract_system_components(system_message) # This memory_filesystem is top-level (no memory_blocks container) assert result["memory_filesystem"] is not None assert "human.md" in result["memory_filesystem"] # Bare file blocks after </memory_filesystem> are captured as core_memory assert result["core_memory"] is not None assert "<system/human.md>" in result["core_memory"] assert "Name: Alice" in result["core_memory"] def test_letta_code_agent_real_format(self): """Real-world Letta Code agent format: no base_instructions, nested memory_filesystem""" system_message = ( "You are a self-improving AI agent with advanced memory.\n" "You are connected to an interactive CLI tool.\n\n" "# Memory\n" "You have an advanced memory system.\n\n" "<memory_blocks>\n" "The following memory blocks are currently engaged:\n\n" "<memory_filesystem>\n" "<description>Filesystem view</description>\n" "<value>\n" "/memory/\n" "\u251c\u2500\u2500 system/\n" "\u2502 \u251c\u2500\u2500 human.md\n" "\u2502 \u2514\u2500\u2500 persona.md\n" "</value>\n" "</memory_filesystem>\n\n" "<persona>\n" "<value>My name is Letta Code.</value>\n" "</persona>\n\n" "<human>\n" "<value>Name: Jin Peng</value>\n" "</human>\n" "</memory_blocks>\n\n" "<memory_metadata>\n" "- The current system date is: February 10, 2026\n" "- 9663 previous messages in recall memory\n" "</memory_metadata>" ) result = ContextWindowCalculator.extract_system_components(system_message) # System prompt: preamble before <memory_blocks> assert result["system_prompt"] is not None assert "self-improving AI agent" in result["system_prompt"] assert "advanced memory system" in result["system_prompt"] assert "<memory_blocks>" not in result["system_prompt"] # Core memory: the full <memory_blocks> section assert result["core_memory"] is not None assert "Letta Code" in result["core_memory"] assert "Jin Peng" in result["core_memory"] # memory_filesystem is NESTED inside memory_blocks - should NOT be extracted assert result["memory_filesystem"] is None # No tool_usage_rules or directories assert result["tool_usage_rules"] is None assert result["directories"] is None # External memory summary assert result["external_memory_summary"] is not None assert "February 10, 2026" in result["external_memory_summary"] def test_git_enabled_agent_bare_file_blocks_captured_as_core_memory(self): """Git-enabled agents render bare file blocks after </memory_filesystem> — these must be captured as core_memory""" system_message = ( "<base_instructions>Base</base_instructions>\n" "<memory_filesystem>\n" "\u251c\u2500\u2500 system/\n" "\u2502 \u251c\u2500\u2500 human.md\n" "\u2502 \u2514\u2500\u2500 persona.md\n" "</memory_filesystem>\n\n" "<system/human.md>\n---\ndescription: About the human\nlimit: 2000\n---\nName: Alice\n</system/human.md>\n\n" "<system/persona.md>\n---\ndescription: Agent persona\n---\nI am a helpful assistant.\n</system/persona.md>\n\n" "<tool_usage_rules>Always call send_message to respond.</tool_usage_rules>\n" "<memory_metadata>Meta</memory_metadata>" ) result = ContextWindowCalculator.extract_system_components(system_message) # memory_filesystem should preserve tree connectors with deterministic ordering assert result["memory_filesystem"] is not None assert "\u251c\u2500\u2500 system/" in result["memory_filesystem"] # core_memory should capture the bare file blocks assert result["core_memory"] is not None assert "<system/human.md>" in result["core_memory"] assert "Name: Alice" in result["core_memory"] assert "<system/persona.md>" in result["core_memory"] assert "helpful assistant" in result["core_memory"] # tool_usage_rules should NOT be included in core_memory assert "<tool_usage_rules>" not in result["core_memory"] # Other sections assert result["tool_usage_rules"] is not None assert result["external_memory_summary"] is not None def test_git_enabled_agent_no_bare_blocks(self): """Git-enabled agent with no file blocks after memory_filesystem returns None for core_memory""" system_message = ( "<base_instructions>Base</base_instructions>\n" "<memory_filesystem>\n" "\u251c\u2500\u2500 system/\n" "</memory_filesystem>\n" "<memory_metadata>Meta</memory_metadata>" ) result = ContextWindowCalculator.extract_system_components(system_message) assert result["memory_filesystem"] is not None assert result["core_memory"] is None def test_extract_top_level_tag_dual_occurrence_nested_first(self): """When a tag appears nested first and top-level later, the top-level one is extracted""" system_message = ( "<memory_blocks>\n" "<tool_usage_rules>nested rules</tool_usage_rules>\n" "</memory_blocks>\n\n" "<tool_usage_rules>top-level rules</tool_usage_rules>" ) result = ContextWindowCalculator._extract_top_level_tag(system_message, "tool_usage_rules") assert result is not None assert "top-level rules" in result assert "nested rules" not in result def test_extract_system_prompt_pure_text_no_tags(self): """System message with no section tags at all returns the full text as system_prompt""" system_message = "You are a simple agent.\nYou help the user with tasks." result = ContextWindowCalculator._extract_system_prompt(system_message) assert result is not None assert "simple agent" in result assert "help the user" in result def test_git_backed_memory_without_memory_blocks_wrapper(self): """Regression test from main: git-backed agents without <memory_blocks> wrapper""" system_message = """You are some system prompt. <memory_filesystem> Memory Directory: ~/.letta/agents/agent-123/memory /memory/ \u2514\u2500\u2500 system/ \u2514\u2500\u2500 human.md </memory_filesystem> <system/human.md> --- description: test limit: 10 --- hello </system/human.md> <memory_metadata> - foo=bar </memory_metadata> """ result = ContextWindowCalculator.extract_system_components(system_message) assert "You are some system prompt" in result["system_prompt"] # memory_filesystem is a top-level section assert result["memory_filesystem"] is not None assert "<memory_filesystem>" in result["memory_filesystem"] # bare file blocks are captured as core_memory assert result["core_memory"] is not None assert "<system/human.md>" in result["core_memory"] assert result["external_memory_summary"].startswith("<memory_metadata>") def test_legacy_memory_blocks_wrapper(self): """Regression test from main: legacy memory_blocks wrapper is properly parsed""" system_message = """<base_instructions>SYS</base_instructions> <memory_blocks> <persona>p</persona> </memory_blocks> <memory_metadata> - x=y </memory_metadata> """ result = ContextWindowCalculator.extract_system_components(system_message) assert result["system_prompt"].startswith("<base_instructions>") assert result["core_memory"].startswith("<memory_blocks>") assert result["external_memory_summary"].startswith("<memory_metadata>") def _make_system_message(text: str): """Helper to create a real Message object for use as a system message in tests.""" from letta.schemas.enums import MessageRole from letta.schemas.letta_message_content import TextContent from letta.schemas.message import Message return Message(role=MessageRole.system, content=[TextContent(text=text)]) def _make_mock_deps(system_text: str): """Helper to create mocked token_counter, message_manager, and agent_state.""" token_counter = MagicMock() token_counter.count_text_tokens = AsyncMock(side_effect=lambda text: len(text) if text else 0) token_counter.count_message_tokens = AsyncMock(return_value=0) token_counter.count_tool_tokens = AsyncMock(return_value=0) token_counter.convert_messages = MagicMock(return_value=[{"role": "system", "content": system_text}]) message_manager = MagicMock() message_manager.get_messages_by_ids_async = AsyncMock(return_value=[]) agent_state = MagicMock() agent_state.id = "agent-test" agent_state.message_ids = ["msg-sys"] agent_state.system = "fallback system prompt" agent_state.tools = [] agent_state.llm_config.context_window = 128000 actor = MagicMock() return token_counter, message_manager, agent_state, actor class TestCalculateContextWindow: """Integration tests for calculate_context_window with mocked dependencies""" @pytest.mark.asyncio async def test_calculate_context_window_standard_agent(self): """Test full context window calculation with a standard system message""" system_text = ( "<base_instructions>You are a helpful agent.</base_instructions>\n" "<memory_blocks>human: User is Alice</memory_blocks>\n" "<memory_metadata>Archival: 5 passages</memory_metadata>" ) system_msg = _make_system_message(system_text) token_counter, message_manager, agent_state, actor = _make_mock_deps(system_text) calculator = ContextWindowCalculator() result = await calculator.calculate_context_window( agent_state=agent_state, actor=actor, token_counter=token_counter, message_manager=message_manager, system_message_compiled=system_msg, num_archival_memories=5, num_messages=10, message_ids=[], ) assert result.context_window_size_max == 128000 assert result.num_archival_memory == 5 assert result.num_recall_memory == 10 assert result.num_tokens_system > 0 assert "helpful agent" in result.system_prompt assert result.num_tokens_core_memory > 0 assert "User is Alice" in result.core_memory assert result.num_tokens_external_memory_summary > 0 # New sections should be None/0 since not in system message assert result.memory_filesystem is None assert result.num_tokens_memory_filesystem == 0 assert result.tool_usage_rules is None assert result.num_tokens_tool_usage_rules == 0 assert result.directories is None assert result.num_tokens_directories == 0 @pytest.mark.asyncio async def test_calculate_context_window_skips_empty_sections(self): """Verify that token counting is skipped for empty/missing sections""" # Only base_instructions, no other sections system_text = "<base_instructions>Simple agent</base_instructions>" system_msg = _make_system_message(system_text) token_counter, message_manager, agent_state, actor = _make_mock_deps(system_text) calculator = ContextWindowCalculator() await calculator.calculate_context_window( agent_state=agent_state, actor=actor, token_counter=token_counter, message_manager=message_manager, system_message_compiled=system_msg, num_archival_memories=0, num_messages=0, message_ids=[], ) # count_text_tokens should only be called for system_prompt (non-empty) # and NOT for core_memory, memory_filesystem, tool_usage_rules, directories, # external_memory_summary, or summary_memory (all empty/None) calls = token_counter.count_text_tokens.call_args_list assert len(calls) == 1, f"Expected 1 call to count_text_tokens (system_prompt only), got {len(calls)}: {calls}" @pytest.mark.asyncio async def test_calculate_context_window_all_sections(self): """Test with all optional sections present""" system_text = ( "<base_instructions>Agent instructions</base_instructions>\n" "<memory_blocks>Core memory</memory_blocks>\n" "<memory_filesystem>\u251c\u2500\u2500 system/\n\u2502 \u2514\u2500\u2500 human.md</memory_filesystem>\n" "<tool_usage_rules>Always call search first</tool_usage_rules>\n" '<directories><directory name="docs">content</directory></directories>\n' "<memory_metadata>Archival: 10 passages</memory_metadata>" ) system_msg = _make_system_message(system_text) token_counter, message_manager, agent_state, actor = _make_mock_deps(system_text) calculator = ContextWindowCalculator() result = await calculator.calculate_context_window( agent_state=agent_state, actor=actor, token_counter=token_counter, message_manager=message_manager, system_message_compiled=system_msg, num_archival_memories=10, num_messages=5, message_ids=[], ) # All sections should be populated assert result.num_tokens_system > 0 assert result.num_tokens_core_memory > 0 assert result.num_tokens_memory_filesystem > 0 assert result.memory_filesystem is not None assert result.num_tokens_tool_usage_rules > 0 assert result.tool_usage_rules is not None assert result.num_tokens_directories > 0 assert result.directories is not None assert result.num_tokens_external_memory_summary > 0 # Verify total is sum of all parts expected_total = ( result.num_tokens_system + result.num_tokens_core_memory + result.num_tokens_memory_filesystem + result.num_tokens_tool_usage_rules + result.num_tokens_directories + result.num_tokens_external_memory_summary + result.num_tokens_summary_memory + result.num_tokens_messages + result.num_tokens_functions_definitions ) assert result.context_window_size_current == expected_total @pytest.mark.asyncio async def test_calculate_context_window_git_enabled_agent(self): """Test that git-enabled agents capture bare file blocks as core_memory""" system_text = ( "<base_instructions>Git agent</base_instructions>\n" "<memory_filesystem>\n" "\u251c\u2500\u2500 system/\n" "\u2502 \u251c\u2500\u2500 human.md\n" "\u2502 \u2514\u2500\u2500 persona.md\n" "</memory_filesystem>\n\n" "<system/human.md>\n---\ndescription: About the human\n---\nName: Alice\n</system/human.md>\n\n" "<system/persona.md>\n---\ndescription: Agent persona\n---\nI am helpful.\n</system/persona.md>\n\n" "<memory_metadata>Archival: 3 passages</memory_metadata>" ) system_msg = _make_system_message(system_text) token_counter, message_manager, agent_state, actor = _make_mock_deps(system_text) calculator = ContextWindowCalculator() result = await calculator.calculate_context_window( agent_state=agent_state, actor=actor, token_counter=token_counter, message_manager=message_manager, system_message_compiled=system_msg, num_archival_memories=3, num_messages=5, message_ids=[], ) # memory_filesystem should capture the tree view assert result.memory_filesystem is not None assert result.num_tokens_memory_filesystem > 0 # core_memory should capture the bare file blocks assert result.num_tokens_core_memory > 0 assert "Name: Alice" in result.core_memory assert "<system/persona.md>" in result.core_memory # Total should include all sections expected_total = ( result.num_tokens_system + result.num_tokens_core_memory + result.num_tokens_memory_filesystem + result.num_tokens_tool_usage_rules + result.num_tokens_directories + result.num_tokens_external_memory_summary + result.num_tokens_summary_memory + result.num_tokens_messages + result.num_tokens_functions_definitions ) assert result.context_window_size_current == expected_total
{ "repo_id": "letta-ai/letta", "file_path": "tests/test_context_window_calculator.py", "license": "Apache License 2.0", "lines": 551, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
letta-ai/letta:tests/test_google_schema_refs.py
"""Unit tests for GoogleVertexClient._resolve_json_schema_refs and $ref safety net.""" import pytest from letta.llm_api.google_vertex_client import GoogleVertexClient @pytest.fixture def client(): return GoogleVertexClient() class TestResolveJsonSchemaRefs: def test_single_def_with_ref(self, client): schema = { "type": "object", "properties": { "status": {"$ref": "#/$defs/StatusEnum"}, }, "$defs": { "StatusEnum": {"type": "string", "enum": ["active", "inactive"]}, }, } result = client._resolve_json_schema_refs(schema) assert "$defs" not in result assert result["properties"]["status"] == {"type": "string", "enum": ["active", "inactive"]} def test_multiple_defs(self, client): schema = { "type": "object", "properties": { "ticket": {"$ref": "#/$defs/TicketStatus"}, "report": {"$ref": "#/$defs/ReportType"}, }, "$defs": { "TicketStatus": {"type": "string", "enum": ["open", "closed"]}, "ReportType": {"type": "string", "enum": ["summary", "detailed"]}, }, } result = client._resolve_json_schema_refs(schema) assert "$defs" not in result assert result["properties"]["ticket"] == {"type": "string", "enum": ["open", "closed"]} assert result["properties"]["report"] == {"type": "string", "enum": ["summary", "detailed"]} def test_nested_ref_in_def(self, client): schema = { "type": "object", "properties": { "order": {"$ref": "#/$defs/Order"}, }, "$defs": { "Order": { "type": "object", "properties": { "status": {"$ref": "#/$defs/OrderStatus"}, }, }, "OrderStatus": {"type": "string", "enum": ["pending", "shipped"]}, }, } result = client._resolve_json_schema_refs(schema) assert "$defs" not in result assert result["properties"]["order"]["properties"]["status"] == {"type": "string", "enum": ["pending", "shipped"]} def test_ref_inside_anyof(self, client): schema = { "type": "object", "properties": { "value": { "anyOf": [ {"$ref": "#/$defs/StringVal"}, {"type": "null"}, ] }, }, "$defs": { "StringVal": {"type": "string", "maxLength": 100}, }, } result = client._resolve_json_schema_refs(schema) assert "$defs" not in result assert result["properties"]["value"]["anyOf"][0] == {"type": "string", "maxLength": 100} assert result["properties"]["value"]["anyOf"][1] == {"type": "null"} def test_ref_inside_allof(self, client): schema = { "type": "object", "properties": { "item": {"allOf": [{"$ref": "#/$defs/Base"}, {"type": "object", "properties": {"extra": {"type": "string"}}}]}, }, "$defs": { "Base": {"type": "object", "properties": {"name": {"type": "string"}}}, }, } result = client._resolve_json_schema_refs(schema) assert result["properties"]["item"]["allOf"][0] == {"type": "object", "properties": {"name": {"type": "string"}}} def test_no_defs_is_noop(self, client): schema = { "type": "object", "properties": { "name": {"type": "string"}, }, } result = client._resolve_json_schema_refs(schema) assert result == schema def test_definitions_key(self, client): schema = { "type": "object", "properties": { "role": {"$ref": "#/definitions/Role"}, }, "definitions": { "Role": {"type": "string", "enum": ["admin", "user"]}, }, } result = client._resolve_json_schema_refs(schema) assert "definitions" not in result assert result["properties"]["role"] == {"type": "string", "enum": ["admin", "user"]} def test_unresolvable_ref_logged(self, client): schema = { "type": "object", "properties": { "thing": {"$ref": "#/properties/other/nested"}, }, } result = client._resolve_json_schema_refs(schema) assert "$ref" in result["properties"]["thing"] def test_ref_in_array_items(self, client): schema = { "type": "object", "properties": { "tags": { "type": "array", "items": {"$ref": "#/$defs/Tag"}, }, }, "$defs": { "Tag": {"type": "string", "enum": ["urgent", "low"]}, }, } result = client._resolve_json_schema_refs(schema) assert "$defs" not in result assert result["properties"]["tags"]["items"] == {"type": "string", "enum": ["urgent", "low"]} class TestCleanSchemaStripsUnresolvedRefs: def test_ref_stripped_by_cleaner(self, client): schema = { "type": "object", "properties": { "thing": {"$ref": "#/properties/other/nested", "type": "string"}, }, } client._clean_google_ai_schema_properties(schema) assert "$ref" not in schema["properties"]["thing"] assert schema["properties"]["thing"]["type"] == "string" def test_full_pipeline_resolves_then_cleans(self, client): schema = { "type": "object", "properties": { "status": {"$ref": "#/$defs/Status"}, "weird": {"$ref": "#/properties/foo/bar", "type": "string"}, }, "$defs": { "Status": {"type": "string", "enum": ["a", "b"], "default": "a"}, }, } resolved = client._resolve_json_schema_refs(schema) client._clean_google_ai_schema_properties(resolved) assert "$defs" not in resolved assert "$ref" not in resolved["properties"]["weird"] assert resolved["properties"]["status"]["enum"] == ["a", "b"] assert "default" not in resolved["properties"]["status"]
{ "repo_id": "letta-ai/letta", "file_path": "tests/test_google_schema_refs.py", "license": "Apache License 2.0", "lines": 161, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
letta-ai/letta:tests/test_openai_prompt_cache_request_fields.py
from letta.llm_api.openai_client import OpenAIClient from letta.schemas.enums import AgentType, MessageRole from letta.schemas.letta_message_content import TextContent from letta.schemas.llm_config import LLMConfig from letta.schemas.message import Message def _message(text: str = "hello") -> Message: return Message( role=MessageRole.user, content=[TextContent(text=text)], agent_id="agent-abc", ) def _openai_config(model: str, endpoint_type: str = "openai", provider_name: str | None = "openai") -> LLMConfig: return LLMConfig( model=model, model_endpoint_type=endpoint_type, model_endpoint="https://api.openai.com/v1", context_window=256000, provider_name=provider_name, ) def test_responses_request_sets_24h_retention_for_supported_model(): client = OpenAIClient() llm_config = _openai_config(model="gpt-5.1") messages = [_message()] request_data = client.build_request_data( agent_type=AgentType.letta_v1_agent, messages=messages, llm_config=llm_config, tools=[], ) assert "input" in request_data assert "prompt_cache_key" not in request_data assert request_data.get("prompt_cache_retention") == "24h" def test_responses_request_omits_24h_for_unsupported_model(): client = OpenAIClient() llm_config = _openai_config(model="o3-mini") messages = [_message()] request_data = client.build_request_data( agent_type=AgentType.letta_v1_agent, messages=messages, llm_config=llm_config, tools=[], ) assert "prompt_cache_key" not in request_data assert "prompt_cache_retention" not in request_data def test_chat_completions_request_sets_24h_retention_for_supported_model(): client = OpenAIClient() llm_config = _openai_config(model="gpt-4.1") messages = [_message()] request_data = client.build_request_data( agent_type=AgentType.memgpt_v2_agent, messages=messages, llm_config=llm_config, tools=[], ) assert "messages" in request_data assert "prompt_cache_key" not in request_data assert request_data.get("prompt_cache_retention") == "24h" def test_chat_completions_request_omits_24h_for_unsupported_model(): client = OpenAIClient() llm_config = _openai_config(model="gpt-4o-mini") messages = [_message()] request_data = client.build_request_data( agent_type=AgentType.memgpt_v2_agent, messages=messages, llm_config=llm_config, tools=[], ) assert "prompt_cache_key" not in request_data assert "prompt_cache_retention" not in request_data def test_openrouter_request_omits_all_prompt_cache_fields(): client = OpenAIClient() llm_config = LLMConfig( model="gpt-5.1", handle="openrouter/gpt-5.1", model_endpoint_type="openai", model_endpoint="https://openrouter.ai/api/v1", context_window=256000, provider_name="openrouter", ) messages = [_message()] responses_request_data = client.build_request_data( agent_type=AgentType.letta_v1_agent, messages=messages, llm_config=llm_config, tools=[], ) chat_request_data = client.build_request_data( agent_type=AgentType.memgpt_v2_agent, messages=messages, llm_config=llm_config, tools=[], ) assert "prompt_cache_key" not in responses_request_data assert "prompt_cache_retention" not in responses_request_data assert "prompt_cache_key" not in chat_request_data assert "prompt_cache_retention" not in chat_request_data def test_gpt5_family_gets_24h_retention(): """gpt-5, gpt-5-codex, gpt-5.1, gpt-5.2 all get 24h retention.""" client = OpenAIClient() for model in ["gpt-5", "gpt-5-codex", "gpt-5.1", "gpt-5.1-codex", "gpt-5.2"]: llm_config = _openai_config(model=model) request_data = client.build_request_data( agent_type=AgentType.letta_v1_agent, messages=[_message()], llm_config=llm_config, tools=[], ) assert request_data.get("prompt_cache_retention") == "24h", f"{model} should get 24h retention" def test_gpt5_mini_excluded_from_24h_retention(): """gpt-5-mini is not listed in OpenAI docs for extended retention.""" client = OpenAIClient() llm_config = _openai_config(model="gpt-5-mini") request_data = client.build_request_data( agent_type=AgentType.letta_v1_agent, messages=[_message()], llm_config=llm_config, tools=[], ) assert "prompt_cache_retention" not in request_data
{ "repo_id": "letta-ai/letta", "file_path": "tests/test_openai_prompt_cache_request_fields.py", "license": "Apache License 2.0", "lines": 119, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
letta-ai/letta:alembic/versions/297e8217e952_nullable_embedding_for_archives_and_.py
"""nullable embedding for archives and passages Revision ID: 297e8217e952 Revises: 308a180244fc Create Date: 2026-01-20 14:11:21.137232 """ from typing import Sequence, Union import sqlalchemy as sa from sqlalchemy.dialects import postgresql from alembic import op # revision identifiers, used by Alembic. revision: str = "297e8217e952" down_revision: Union[str, None] = "308a180244fc" branch_labels: Union[str, Sequence[str], None] = None depends_on: Union[str, Sequence[str], None] = None def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.alter_column("archival_passages", "embedding_config", existing_type=postgresql.JSON(astext_type=sa.Text()), nullable=True) op.alter_column("archives", "embedding_config", existing_type=postgresql.JSON(astext_type=sa.Text()), nullable=True) op.alter_column("source_passages", "embedding_config", existing_type=postgresql.JSON(astext_type=sa.Text()), nullable=True) # ### end Alembic commands ### def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.alter_column("source_passages", "embedding_config", existing_type=postgresql.JSON(astext_type=sa.Text()), nullable=False) op.alter_column("archives", "embedding_config", existing_type=postgresql.JSON(astext_type=sa.Text()), nullable=False) op.alter_column("archival_passages", "embedding_config", existing_type=postgresql.JSON(astext_type=sa.Text()), nullable=False) # ### end Alembic commands ###
{ "repo_id": "letta-ai/letta", "file_path": "alembic/versions/297e8217e952_nullable_embedding_for_archives_and_.py", "license": "Apache License 2.0", "lines": 26, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
letta-ai/letta:alembic/versions/308a180244fc_last_synced_column_for_providers.py
"""last_synced column for providers Revision ID: 308a180244fc Revises: 82feb220a9b8 Create Date: 2026-01-05 18:54:15.996786 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op # revision identifiers, used by Alembic. revision: str = "308a180244fc" down_revision: Union[str, None] = "82feb220a9b8" branch_labels: Union[str, Sequence[str], None] = None depends_on: Union[str, Sequence[str], None] = None def upgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.add_column("providers", sa.Column("last_synced", sa.DateTime(timezone=True), nullable=True)) # ### end Alembic commands ### def downgrade() -> None: # ### commands auto generated by Alembic - please adjust! ### op.drop_column("providers", "last_synced") # ### end Alembic commands ###
{ "repo_id": "letta-ai/letta", "file_path": "alembic/versions/308a180244fc_last_synced_column_for_providers.py", "license": "Apache License 2.0", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
letta-ai/letta:alembic/versions/9275f62ad282_add_v2_protocol_fields_to_provider_traces.py
"""Add v2 protocol fields to provider_traces Revision ID: 9275f62ad282 Revises: 297e8217e952 Create Date: 2026-01-22 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op revision: str = "9275f62ad282" down_revision: Union[str, None] = "297e8217e952" branch_labels: Union[str, Sequence[str], None] = None depends_on: Union[str, Sequence[str], None] = None def upgrade() -> None: op.add_column("provider_traces", sa.Column("org_id", sa.String(), nullable=True)) op.add_column("provider_traces", sa.Column("user_id", sa.String(), nullable=True)) op.add_column("provider_traces", sa.Column("compaction_settings", sa.JSON(), nullable=True)) op.add_column("provider_traces", sa.Column("llm_config", sa.JSON(), nullable=True)) def downgrade() -> None: op.drop_column("provider_traces", "llm_config") op.drop_column("provider_traces", "compaction_settings") op.drop_column("provider_traces", "user_id") op.drop_column("provider_traces", "org_id")
{ "repo_id": "letta-ai/letta", "file_path": "alembic/versions/9275f62ad282_add_v2_protocol_fields_to_provider_traces.py", "license": "Apache License 2.0", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
letta-ai/letta:alembic/versions/a1b2c3d4e5f8_create_provider_trace_metadata_table.py
"""create provider_trace_metadata table Revision ID: a1b2c3d4e5f8 Revises: 9275f62ad282 Create Date: 2026-01-28 """ from typing import Sequence, Union import sqlalchemy as sa from alembic import op from letta.settings import settings revision: str = "a1b2c3d4e5f8" down_revision: Union[str, None] = "9275f62ad282" branch_labels: Union[str, Sequence[str], None] = None depends_on: Union[str, Sequence[str], None] = None def upgrade() -> None: if not settings.letta_pg_uri_no_default: return op.create_table( "provider_trace_metadata", sa.Column("id", sa.String(), nullable=False), sa.Column("step_id", sa.String(), nullable=True), sa.Column("agent_id", sa.String(), nullable=True), sa.Column("agent_tags", sa.JSON(), nullable=True), sa.Column("call_type", sa.String(), nullable=True), sa.Column("run_id", sa.String(), nullable=True), sa.Column("source", sa.String(), nullable=True), sa.Column("org_id", sa.String(), nullable=True), sa.Column("user_id", sa.String(), nullable=True), sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False), sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=True), sa.Column("is_deleted", sa.Boolean(), server_default=sa.text("FALSE"), nullable=False), sa.Column("_created_by_id", sa.String(), nullable=True), sa.Column("_last_updated_by_id", sa.String(), nullable=True), sa.Column("organization_id", sa.String(), nullable=False), sa.ForeignKeyConstraint( ["organization_id"], ["organizations.id"], ), sa.PrimaryKeyConstraint("created_at", "id"), ) op.create_index("ix_provider_trace_metadata_step_id", "provider_trace_metadata", ["step_id"], unique=False) op.create_index("ix_provider_trace_metadata_id", "provider_trace_metadata", ["id"], unique=True) def downgrade() -> None: if not settings.letta_pg_uri_no_default: return op.drop_index("ix_provider_trace_metadata_id", table_name="provider_trace_metadata") op.drop_index("ix_provider_trace_metadata_step_id", table_name="provider_trace_metadata") op.drop_table("provider_trace_metadata")
{ "repo_id": "letta-ai/letta", "file_path": "alembic/versions/a1b2c3d4e5f8_create_provider_trace_metadata_table.py", "license": "Apache License 2.0", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
letta-ai/letta:letta/llm_api/minimax_client.py
from typing import List, Optional, Union import anthropic from anthropic import AsyncStream from anthropic.types.beta import BetaMessage, BetaRawMessageStreamEvent from letta.helpers.json_helpers import sanitize_unicode_surrogates from letta.llm_api.anthropic_client import AnthropicClient from letta.log import get_logger from letta.otel.tracing import trace_method from letta.schemas.agent import AgentType from letta.schemas.llm_config import LLMConfig from letta.schemas.message import Message as PydanticMessage from letta.settings import model_settings logger = get_logger(__name__) class MiniMaxClient(AnthropicClient): """ MiniMax LLM client using Anthropic-compatible API. Uses the beta messages API to ensure compatibility with Anthropic streaming interfaces. Temperature must be in range (0.0, 1.0]. Some Anthropic params are ignored: top_k, stop_sequences, service_tier, etc. Documentation: https://platform.minimax.io/docs/api-reference/text-anthropic-api Note: We override client creation to always use llm_config.model_endpoint as base_url (required for BYOK where provider_name is user's custom name, not "minimax"). We also override request methods to avoid passing Anthropic-specific beta headers. """ @trace_method def _get_anthropic_client( self, llm_config: LLMConfig, async_client: bool = False ) -> Union[anthropic.AsyncAnthropic, anthropic.Anthropic]: """Create Anthropic client configured for MiniMax API.""" api_key, _, _ = self.get_byok_overrides(llm_config) if not api_key: api_key = model_settings.minimax_api_key # Always use model_endpoint for base_url (works for both base and BYOK providers) base_url = llm_config.model_endpoint if async_client: return anthropic.AsyncAnthropic(api_key=api_key, base_url=base_url, max_retries=model_settings.anthropic_max_retries) return anthropic.Anthropic(api_key=api_key, base_url=base_url, max_retries=model_settings.anthropic_max_retries) @trace_method async def _get_anthropic_client_async( self, llm_config: LLMConfig, async_client: bool = False ) -> Union[anthropic.AsyncAnthropic, anthropic.Anthropic]: """Create Anthropic client configured for MiniMax API (async version).""" api_key, _, _ = await self.get_byok_overrides_async(llm_config) if not api_key: api_key = model_settings.minimax_api_key # Always use model_endpoint for base_url (works for both base and BYOK providers) base_url = llm_config.model_endpoint if async_client: return anthropic.AsyncAnthropic(api_key=api_key, base_url=base_url, max_retries=model_settings.anthropic_max_retries) return anthropic.Anthropic(api_key=api_key, base_url=base_url, max_retries=model_settings.anthropic_max_retries) @trace_method def request(self, request_data: dict, llm_config: LLMConfig) -> dict: """ Synchronous request to MiniMax API. Uses beta messages API for compatibility with Anthropic streaming interfaces. """ client = self._get_anthropic_client(llm_config, async_client=False) response: BetaMessage = client.beta.messages.create(**request_data) return response.model_dump() @trace_method async def request_async(self, request_data: dict, llm_config: LLMConfig) -> dict: """ Asynchronous request to MiniMax API. Uses beta messages API for compatibility with Anthropic streaming interfaces. """ request_data = sanitize_unicode_surrogates(request_data) client = await self._get_anthropic_client_async(llm_config, async_client=True) try: response: BetaMessage = await client.beta.messages.create(**request_data) return response.model_dump() except ValueError as e: # Handle streaming fallback if needed (similar to Anthropic client) if "streaming is required" in str(e).lower(): logger.warning( "[MiniMax] Non-streaming request rejected. Falling back to streaming mode. Error: %s", str(e), ) return await self._request_via_streaming(request_data, llm_config, betas=[]) raise @trace_method async def stream_async(self, request_data: dict, llm_config: LLMConfig) -> AsyncStream[BetaRawMessageStreamEvent]: """ Asynchronous streaming request to MiniMax API. Uses beta messages API for compatibility with Anthropic streaming interfaces. """ request_data = sanitize_unicode_surrogates(request_data) client = await self._get_anthropic_client_async(llm_config, async_client=True) request_data["stream"] = True try: return await client.beta.messages.create(**request_data) except Exception as e: logger.error(f"Error streaming MiniMax request: {e}") raise e @trace_method def build_request_data( self, agent_type: AgentType, messages: List[PydanticMessage], llm_config: LLMConfig, tools: Optional[List[dict]] = None, force_tool_call: Optional[str] = None, requires_subsequent_tool_call: bool = False, tool_return_truncation_chars: Optional[int] = None, ) -> dict: """ Build request data for MiniMax API. Inherits most logic from AnthropicClient, with MiniMax-specific adjustments: - Temperature must be in range (0.0, 1.0] """ data = super().build_request_data( agent_type, messages, llm_config, tools, force_tool_call, requires_subsequent_tool_call, tool_return_truncation_chars, ) # MiniMax temperature range is (0.0, 1.0], recommended value: 1 if data.get("temperature") is not None: temp = data["temperature"] if temp <= 0: data["temperature"] = 0.01 # Minimum valid value (exclusive of 0) logger.warning(f"[MiniMax] Temperature {temp} is invalid. Clamped to 0.01.") elif temp > 1.0: data["temperature"] = 1.0 # Maximum valid value logger.warning(f"[MiniMax] Temperature {temp} is invalid. Clamped to 1.0.") # MiniMax ignores these Anthropic-specific parameters, but we can remove them # to avoid potential issues (they won't cause errors, just ignored) # Note: We don't remove them since MiniMax silently ignores them return data def is_reasoning_model(self, llm_config: LLMConfig) -> bool: """ All MiniMax M2.x models support native interleaved thinking. Unlike Anthropic where only certain models (Claude 3.7+) support extended thinking, all MiniMax models natively support thinking blocks without beta headers. """ return True def requires_auto_tool_choice(self, llm_config: LLMConfig) -> bool: """MiniMax models support all tool choice modes.""" return False def supports_structured_output(self, llm_config: LLMConfig) -> bool: """MiniMax doesn't currently advertise structured output support.""" return False
{ "repo_id": "letta-ai/letta", "file_path": "letta/llm_api/minimax_client.py", "license": "Apache License 2.0", "lines": 144, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
letta-ai/letta:letta/model_specs/litellm_model_specs.py
""" Utility functions for working with litellm model specifications. This module provides access to model specifications from the litellm model_prices_and_context_window.json file. The data is synced from: https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json """ import json import os from typing import Optional import aiofiles from async_lru import alru_cache from letta.log import get_logger logger = get_logger(__name__) # Path to the litellm model specs JSON file MODEL_SPECS_PATH = os.path.join(os.path.dirname(__file__), "model_prices_and_context_window.json") @alru_cache(maxsize=1) async def load_model_specs() -> dict: """Load the litellm model specifications from the JSON file. Returns: dict: The model specifications data Raises: FileNotFoundError: If the model specs file is not found json.JSONDecodeError: If the file is not valid JSON """ if not os.path.exists(MODEL_SPECS_PATH): logger.warning(f"Model specs file not found at {MODEL_SPECS_PATH}") return {} try: async with aiofiles.open(MODEL_SPECS_PATH, "r") as f: content = await f.read() return json.loads(content) except json.JSONDecodeError as e: logger.error(f"Failed to parse model specs JSON: {e}") return {} async def get_model_spec(model_name: str) -> Optional[dict]: """Get the specification for a specific model. Args: model_name: The name of the model (e.g., "gpt-4o", "gpt-4o-mini") Returns: Optional[dict]: The model specification if found, None otherwise """ specs = await load_model_specs() return specs.get(model_name) async def get_max_input_tokens(model_name: str) -> Optional[int]: """Get the max input tokens for a model. Args: model_name: The name of the model Returns: Optional[int]: The max input tokens if found, None otherwise """ spec = await get_model_spec(model_name) if not spec: return None return spec.get("max_input_tokens") async def get_max_output_tokens(model_name: str) -> Optional[int]: """Get the max output tokens for a model. Args: model_name: The name of the model Returns: Optional[int]: The max output tokens if found, None otherwise """ spec = await get_model_spec(model_name) if not spec: return None # Try max_output_tokens first, fall back to max_tokens return spec.get("max_output_tokens") or spec.get("max_tokens") async def get_context_window(model_name: str) -> Optional[int]: """Get the context window size for a model. For most models, this is the max_input_tokens. Args: model_name: The name of the model Returns: Optional[int]: The context window size if found, None otherwise """ return await get_max_input_tokens(model_name) async def get_litellm_provider(model_name: str) -> Optional[str]: """Get the litellm provider for a model. Args: model_name: The name of the model Returns: Optional[str]: The provider name if found, None otherwise """ spec = await get_model_spec(model_name) if not spec: return None return spec.get("litellm_provider")
{ "repo_id": "letta-ai/letta", "file_path": "letta/model_specs/litellm_model_specs.py", "license": "Apache License 2.0", "lines": 85, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
documentation
letta-ai/letta:letta/orm/provider_trace_metadata.py
import uuid from datetime import datetime from typing import TYPE_CHECKING, Optional if TYPE_CHECKING: from letta.orm.organization import Organization from sqlalchemy import JSON, DateTime, Index, String, UniqueConstraint, func from sqlalchemy.orm import Mapped, mapped_column, relationship from letta.orm.mixins import OrganizationMixin from letta.orm.sqlalchemy_base import SqlalchemyBase from letta.schemas.provider_trace import ProviderTraceMetadata as PydanticProviderTraceMetadata class ProviderTraceMetadata(SqlalchemyBase, OrganizationMixin): """Metadata-only provider trace storage (no request/response JSON).""" __tablename__ = "provider_trace_metadata" __pydantic_model__ = PydanticProviderTraceMetadata __table_args__ = ( Index("ix_provider_trace_metadata_step_id", "step_id"), UniqueConstraint("id", name="uq_provider_trace_metadata_id"), ) created_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), primary_key=True, server_default=func.now(), doc="Timestamp when the trace was created" ) id: Mapped[str] = mapped_column( String, primary_key=True, doc="Unique provider trace identifier", default=lambda: f"provider_trace-{uuid.uuid4()}" ) step_id: Mapped[Optional[str]] = mapped_column(String, nullable=True, doc="ID of the step that this trace is associated with") # Telemetry context fields agent_id: Mapped[Optional[str]] = mapped_column(String, nullable=True, doc="ID of the agent that generated this trace") agent_tags: Mapped[Optional[list]] = mapped_column(JSON, nullable=True, doc="Tags associated with the agent for filtering") call_type: Mapped[Optional[str]] = mapped_column(String, nullable=True, doc="Type of call (agent_step, summarization, etc.)") run_id: Mapped[Optional[str]] = mapped_column(String, nullable=True, doc="ID of the run this trace is associated with") source: Mapped[Optional[str]] = mapped_column( String, nullable=True, doc="Source service that generated this trace (memgpt-server, lettuce-py)" ) # v2 protocol fields org_id: Mapped[Optional[str]] = mapped_column(String, nullable=True, doc="ID of the organization") user_id: Mapped[Optional[str]] = mapped_column(String, nullable=True, doc="ID of the user who initiated the request") # Relationships organization: Mapped["Organization"] = relationship("Organization", lazy="selectin")
{ "repo_id": "letta-ai/letta", "file_path": "letta/orm/provider_trace_metadata.py", "license": "Apache License 2.0", "lines": 38, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
letta-ai/letta:letta/schemas/providers/minimax.py
from typing import Literal import anthropic from pydantic import Field from letta.errors import ErrorCode, LLMAuthenticationError, LLMError from letta.log import get_logger from letta.schemas.enums import ProviderCategory, ProviderType from letta.schemas.llm_config import LLMConfig from letta.schemas.providers.base import Provider logger = get_logger(__name__) # MiniMax model specifications from official documentation # https://platform.minimax.io/docs/guides/models-intro MODEL_LIST = [ { "name": "MiniMax-M2.1", "context_window": 200000, "max_output": 128000, "description": "Polyglot code mastery, precision code refactoring (~60 tps)", }, { "name": "MiniMax-M2.1-lightning", "context_window": 200000, "max_output": 128000, "description": "Same performance as M2.1, significantly faster (~100 tps)", }, { "name": "MiniMax-M2", "context_window": 200000, "max_output": 128000, "description": "Agentic capabilities, advanced reasoning", }, { "name": "MiniMax-M2.5", "context_window": 200000, "max_output": 128000, "description": "Peak Performance. Ultimate Value. Master the Complex", }, ] class MiniMaxProvider(Provider): """ MiniMax provider using Anthropic-compatible API. MiniMax models support native interleaved thinking without requiring beta headers. The API uses the standard messages endpoint (not beta). Documentation: https://platform.minimax.io/docs/api-reference/text-anthropic-api """ provider_type: Literal[ProviderType.minimax] = Field(ProviderType.minimax, description="The type of the provider.") provider_category: ProviderCategory = Field(ProviderCategory.base, description="The category of the provider (base or byok)") api_key: str | None = Field(None, description="API key for the MiniMax API.", deprecated=True) base_url: str = Field("https://api.minimax.io/anthropic", description="Base URL for the MiniMax Anthropic-compatible API.") async def check_api_key(self): """Check if the API key is valid by making a test request to the MiniMax API.""" api_key = await self.api_key_enc.get_plaintext_async() if self.api_key_enc else None if not api_key: raise ValueError("No API key provided") try: # Use async Anthropic client pointed at MiniMax's Anthropic-compatible endpoint client = anthropic.AsyncAnthropic(api_key=api_key, base_url=self.base_url) # Use count_tokens as a lightweight check - similar to Anthropic provider await client.messages.count_tokens(model=MODEL_LIST[-1]["name"], messages=[{"role": "user", "content": "a"}]) except anthropic.AuthenticationError as e: raise LLMAuthenticationError(message=f"Failed to authenticate with MiniMax: {e}", code=ErrorCode.UNAUTHENTICATED) except Exception as e: raise LLMError(message=f"{e}", code=ErrorCode.INTERNAL_SERVER_ERROR) def get_default_max_output_tokens(self, model_name: str) -> int: """Get the default max output tokens for MiniMax models.""" # All MiniMax models support 128K output tokens return 128000 def get_model_context_window_size(self, model_name: str) -> int | None: """Get the context window size for a MiniMax model.""" # All current MiniMax models have 200K context window for model in MODEL_LIST: if model["name"] == model_name: return model["context_window"] # Default fallback return 200000 async def list_llm_models_async(self) -> list[LLMConfig]: """ Return available MiniMax models. MiniMax doesn't have a models listing endpoint, so we use a hardcoded list. """ configs = [] for model in MODEL_LIST: configs.append( LLMConfig( model=model["name"], model_endpoint_type="minimax", model_endpoint=self.base_url, context_window=model["context_window"], handle=self.get_handle(model["name"]), max_tokens=model["max_output"], # MiniMax models support native thinking, similar to Claude's extended thinking put_inner_thoughts_in_kwargs=True, # MiniMax models support parallel tool calling via Anthropic-compatible API parallel_tool_calls=True, provider_name=self.name, provider_category=self.provider_category, ) ) return configs
{ "repo_id": "letta-ai/letta", "file_path": "letta/schemas/providers/minimax.py", "license": "Apache License 2.0", "lines": 98, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
letta-ai/letta:letta/schemas/providers/sglang.py
""" SGLang provider for Letta. SGLang is a high-performance inference engine that exposes OpenAI-compatible API endpoints. """ from typing import Literal from pydantic import Field from letta.schemas.embedding_config import EmbeddingConfig from letta.schemas.enums import ProviderCategory, ProviderType from letta.schemas.llm_config import LLMConfig from letta.schemas.providers.base import Provider class SGLangProvider(Provider): provider_type: Literal[ProviderType.sglang] = Field(ProviderType.sglang, description="The type of the provider.") provider_category: ProviderCategory = Field(ProviderCategory.base, description="The category of the provider (base or byok)") base_url: str = Field(..., description="Base URL for the SGLang API (e.g., http://localhost:30000).") api_key: str | None = Field(None, description="API key for the SGLang API (optional for local instances).") default_prompt_formatter: str | None = Field(default=None, description="Default prompt formatter (aka model wrapper).") handle_base: str | None = Field(None, description="Custom handle base name for model handles.") async def list_llm_models_async(self) -> list[LLMConfig]: from letta.llm_api.openai import openai_get_model_list_async # Ensure base_url ends with /v1 (SGLang uses same convention as vLLM) base_url = self.base_url.rstrip("/") if not base_url.endswith("/v1"): base_url = base_url + "/v1" # Decrypt API key before using (may be None for local instances) api_key = await self.api_key_enc.get_plaintext_async() if self.api_key_enc else None response = await openai_get_model_list_async(base_url, api_key=api_key) data = response.get("data", response) configs = [] for model in data: model_name = model["id"] configs.append( LLMConfig( model=model_name, model_endpoint_type="openai", # SGLang is OpenAI-compatible model_endpoint=base_url, model_wrapper=self.default_prompt_formatter, context_window=model.get("max_model_len", 32768), handle=self.get_handle(model_name, base_name=self.handle_base) if self.handle_base else self.get_handle(model_name), max_tokens=self.get_default_max_output_tokens(model_name), provider_name=self.name, provider_category=self.provider_category, ) ) return configs async def list_embedding_models_async(self) -> list[EmbeddingConfig]: # SGLang embedding support not common for training use cases return []
{ "repo_id": "letta-ai/letta", "file_path": "letta/schemas/providers/sglang.py", "license": "Apache License 2.0", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
letta-ai/letta:tests/integration_test_multi_modal_tool_returns.py
""" Integration tests for multi-modal tool returns (images in tool responses). These tests verify that: 1. Models supporting images in tool returns can see and describe image content 2. Models NOT supporting images (e.g., Chat Completions API) receive placeholder text 3. The image data is properly passed through the approval flow The test uses a secret.png image containing hidden text that the model must identify. """ import base64 import os import uuid import pytest from letta_client import Letta from letta_client.types.agents import ApprovalRequestMessage, AssistantMessage # ------------------------------ # Constants # ------------------------------ # The secret text embedded in the test image # This is the actual text visible in secret.png SECRET_TEXT_IN_IMAGE = "FIREBRAWL" # Models that support images in tool returns (Responses API, Anthropic, or Google AI) MODELS_WITH_IMAGE_SUPPORT = [ "anthropic/claude-sonnet-4-5-20250929", "openai/gpt-5", # Uses Responses API "google_ai/gemini-2.5-flash", # Google AI with vision support ] # Models that do NOT support images in tool returns (Chat Completions only) MODELS_WITHOUT_IMAGE_SUPPORT = [ "openai/gpt-4o-mini", # Uses Chat Completions API, not Responses ] def _load_secret_image() -> str: """Loads the secret test image and returns it as base64.""" image_path = os.path.join(os.path.dirname(__file__), "data/secret.png") with open(image_path, "rb") as f: return base64.standard_b64encode(f.read()).decode("utf-8") SECRET_IMAGE_BASE64 = _load_secret_image() def get_image_tool_schema(): """Returns a client-side tool schema that returns an image.""" return { "name": "get_secret_image", "description": "Retrieves a secret image with hidden text. Call this function to get the image.", "parameters": { "type": "object", "properties": {}, "required": [], }, } # ------------------------------ # Fixtures # ------------------------------ @pytest.fixture def client(server_url: str) -> Letta: """Create a Letta client.""" return Letta(base_url=server_url) # ------------------------------ # Test Cases # ------------------------------ class TestMultiModalToolReturns: """Test multi-modal (image) content in tool returns.""" @pytest.mark.parametrize("model", MODELS_WITH_IMAGE_SUPPORT) def test_model_can_see_image_in_tool_return(self, client: Letta, model: str) -> None: """ Test that models supporting images can see and describe image content returned from a tool. Flow: 1. User asks agent to get the secret image and tell them what's in it 2. Agent calls client-side tool, execution pauses 3. Client provides tool return with image content 4. Agent processes the image and describes what it sees 5. Verify the agent mentions the secret text from the image """ # Create agent for this test agent = client.agents.create( name=f"multimodal_test_{uuid.uuid4().hex[:8]}", model=model, embedding="openai/text-embedding-3-small", include_base_tools=False, tool_ids=[], include_base_tool_rules=False, tool_rules=[], ) try: tool_schema = get_image_tool_schema() print(f"\n=== Testing image support with model: {model} ===") # Step 1: User asks for the secret image print("\nStep 1: Asking agent to call get_secret_image tool...") response1 = client.agents.messages.create( agent_id=agent.id, messages=[ { "role": "user", "content": "Call the get_secret_image function now.", } ], client_tools=[tool_schema], ) # Validate Step 1: Should pause with approval request assert response1.stop_reason.stop_reason == "requires_approval", f"Expected requires_approval, got {response1.stop_reason}" # Find the approval request with tool call approval_msg = None for msg in response1.messages: if isinstance(msg, ApprovalRequestMessage): approval_msg = msg break assert approval_msg is not None, f"Expected an ApprovalRequestMessage but got {[type(m).__name__ for m in response1.messages]}" assert approval_msg.tool_call.name == "get_secret_image" print(f"Tool call ID: {approval_msg.tool_call.tool_call_id}") # Step 2: Provide tool return with image content print("\nStep 2: Providing tool return with image...") # Build image content as list of content parts image_content = [ {"type": "text", "text": "Here is the secret image:"}, { "type": "image", "source": { "type": "base64", "data": SECRET_IMAGE_BASE64, "media_type": "image/png", }, }, ] response2 = client.agents.messages.create( agent_id=agent.id, messages=[ { "type": "approval", "approvals": [ { "type": "tool", "tool_call_id": approval_msg.tool_call.tool_call_id, "tool_return": image_content, "status": "success", }, ], }, ], ) # Validate Step 2: Agent should process the image and respond print(f"Stop reason: {response2.stop_reason}") print(f"Messages: {len(response2.messages)}") # Find the assistant message with the response assistant_response = None for msg in response2.messages: if isinstance(msg, AssistantMessage): assistant_response = msg.content print(f"Assistant response: {assistant_response[:200]}...") break assert assistant_response is not None, "Expected an AssistantMessage with the image description" # Verify the model saw the secret text in the image # The model should mention the secret code if it can see the image assert SECRET_TEXT_IN_IMAGE in assistant_response.upper() or SECRET_TEXT_IN_IMAGE.lower() in assistant_response.lower(), ( f"Model should have seen the secret text '{SECRET_TEXT_IN_IMAGE}' in the image, but response was: {assistant_response}" ) print("\nSUCCESS: Model correctly identified secret text in image!") finally: # Cleanup client.agents.delete(agent_id=agent.id) @pytest.mark.parametrize("model", MODELS_WITHOUT_IMAGE_SUPPORT) def test_model_without_image_support_gets_placeholder(self, client: Letta, model: str) -> None: """ Test that models NOT supporting images receive placeholder text and cannot see the actual image content. This verifies that Chat Completions API models (which don't support images in tool results) get a graceful fallback. Flow: 1. User asks agent to get the secret image 2. Agent calls client-side tool, execution pauses 3. Client provides tool return with image content 4. Agent processes but CANNOT see the image (only placeholder text) 5. Verify the agent does NOT mention the secret text """ # Create agent for this test agent = client.agents.create( name=f"no_image_test_{uuid.uuid4().hex[:8]}", model=model, embedding="openai/text-embedding-3-small", include_base_tools=False, tool_ids=[], include_base_tool_rules=False, tool_rules=[], ) try: tool_schema = get_image_tool_schema() print(f"\n=== Testing placeholder for model without image support: {model} ===") # Step 1: User asks for the secret image print("\nStep 1: Asking agent to call get_secret_image tool...") response1 = client.agents.messages.create( agent_id=agent.id, messages=[ { "role": "user", "content": "Call the get_secret_image function now.", } ], client_tools=[tool_schema], ) # Validate Step 1: Should pause with approval request assert response1.stop_reason.stop_reason == "requires_approval", f"Expected requires_approval, got {response1.stop_reason}" # Find the approval request with tool call approval_msg = None for msg in response1.messages: if isinstance(msg, ApprovalRequestMessage): approval_msg = msg break assert approval_msg is not None, f"Expected an ApprovalRequestMessage but got {[type(m).__name__ for m in response1.messages]}" # Step 2: Provide tool return with image content print("\nStep 2: Providing tool return with image...") image_content = [ {"type": "text", "text": "Here is the secret image:"}, { "type": "image", "source": { "type": "base64", "data": SECRET_IMAGE_BASE64, "media_type": "image/png", }, }, ] response2 = client.agents.messages.create( agent_id=agent.id, messages=[ { "type": "approval", "approvals": [ { "type": "tool", "tool_call_id": approval_msg.tool_call.tool_call_id, "tool_return": image_content, "status": "success", }, ], }, ], ) # Find the assistant message assistant_response = None for msg in response2.messages: if isinstance(msg, AssistantMessage): assistant_response = msg.content print(f"Assistant response: {assistant_response[:200]}...") break assert assistant_response is not None, "Expected an AssistantMessage" # Verify the model did NOT see the secret text (it got placeholder instead) assert ( SECRET_TEXT_IN_IMAGE not in assistant_response.upper() and SECRET_TEXT_IN_IMAGE.lower() not in assistant_response.lower() ), ( f"Model should NOT have seen the secret text '{SECRET_TEXT_IN_IMAGE}' (it doesn't support images), " f"but response was: {assistant_response}" ) # The model should mention something about image being omitted/not visible response_lower = assistant_response.lower() mentions_image_issue = any( phrase in response_lower for phrase in ["image", "omitted", "cannot see", "can't see", "unable to", "not able to", "no image"] ) print("\nSUCCESS: Model correctly did not see the secret (image support not available)") if mentions_image_issue: print("Model acknowledged it cannot see the image content") finally: # Cleanup client.agents.delete(agent_id=agent.id) class TestMultiModalToolReturnsSerialization: """Test that multi-modal tool returns serialize/deserialize correctly.""" @pytest.mark.parametrize("model", MODELS_WITH_IMAGE_SUPPORT[:1]) # Just test one model def test_tool_return_with_image_persists_in_db(self, client: Letta, model: str) -> None: """ Test that tool returns with images are correctly persisted and can be retrieved from the database. """ agent = client.agents.create( name=f"persist_test_{uuid.uuid4().hex[:8]}", model=model, embedding="openai/text-embedding-3-small", include_base_tools=False, tool_ids=[], include_base_tool_rules=False, tool_rules=[], ) try: tool_schema = get_image_tool_schema() # Trigger tool call response1 = client.agents.messages.create( agent_id=agent.id, messages=[{"role": "user", "content": "Call the get_secret_image tool."}], client_tools=[tool_schema], ) assert response1.stop_reason.stop_reason == "requires_approval" approval_msg = None for msg in response1.messages: if isinstance(msg, ApprovalRequestMessage): approval_msg = msg break assert approval_msg is not None # Provide image tool return image_content = [ {"type": "text", "text": "Image result"}, { "type": "image", "source": { "type": "base64", "data": SECRET_IMAGE_BASE64, "media_type": "image/png", }, }, ] response2 = client.agents.messages.create( agent_id=agent.id, messages=[ { "type": "approval", "approvals": [ { "type": "tool", "tool_call_id": approval_msg.tool_call.tool_call_id, "tool_return": image_content, "status": "success", }, ], }, ], ) # Verify we got a response assert response2.stop_reason is not None # Retrieve messages from DB and verify they persisted messages_from_db = client.agents.messages.list(agent_id=agent.id) # Look for the tool return message in the persisted messages found_tool_return = False for msg in messages_from_db.items: # Check if this is a tool return message that might contain our image if hasattr(msg, "tool_returns") and msg.tool_returns: found_tool_return = True break # The tool return should have been saved print(f"Found {len(messages_from_db.items)} messages in DB") print(f"Tool return message found: {found_tool_return}") finally: client.agents.delete(agent_id=agent.id)
{ "repo_id": "letta-ai/letta", "file_path": "tests/integration_test_multi_modal_tool_returns.py", "license": "Apache License 2.0", "lines": 337, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
letta-ai/letta:tests/test_embedding_optional.py
""" Tests for embedding-optional archival memory feature. This file tests that agents can be created without an embedding model and that archival memory operations (insert, list, search) work correctly using text-based search when no embeddings are available. """ import os import threading import warnings import pytest from dotenv import load_dotenv from letta_client import Letta as LettaSDKClient from letta_client.types import CreateBlockParam from tests.utils import wait_for_server # Constants SERVER_PORT = 8283 def run_server(): load_dotenv() from letta.server.rest_api.app import start_server print("Starting server...") start_server(debug=True) @pytest.fixture(scope="module") def client() -> LettaSDKClient: """Get or start a Letta server and return a client.""" server_url = os.getenv("LETTA_SERVER_URL", f"http://localhost:{SERVER_PORT}") if not os.getenv("LETTA_SERVER_URL"): print("Starting server thread") thread = threading.Thread(target=run_server, daemon=True) thread.start() wait_for_server(server_url, timeout=60) print("Running embedding-optional tests with server:", server_url) client = LettaSDKClient(base_url=server_url) yield client @pytest.fixture(scope="function") def agent_without_embedding(client: LettaSDKClient): """Create an agent without an embedding model for testing.""" agent_state = client.agents.create( memory_blocks=[ CreateBlockParam( label="human", value="username: test_user", ), ], model="openai/gpt-4o-mini", # NOTE: Intentionally NOT providing embedding parameter # to test embedding-optional functionality ) assert agent_state.embedding_config is None, "Agent should have no embedding config" yield agent_state # Cleanup client.agents.delete(agent_id=agent_state.id) @pytest.fixture(scope="function") def agent_with_embedding(client: LettaSDKClient): """Create an agent WITH an embedding model for comparison testing.""" agent_state = client.agents.create( memory_blocks=[ CreateBlockParam( label="human", value="username: test_user_with_embedding", ), ], model="openai/gpt-4o-mini", embedding="openai/text-embedding-3-small", ) assert agent_state.embedding_config is not None, "Agent should have embedding config" yield agent_state # Cleanup client.agents.delete(agent_id=agent_state.id) class TestAgentCreationWithoutEmbedding: """Tests for agent creation without embedding configuration.""" def test_create_agent_without_embedding(self, client: LettaSDKClient): """Test that an agent can be created without an embedding model.""" agent_state = client.agents.create( memory_blocks=[ CreateBlockParam( label="human", value="test user", ), ], model="openai/gpt-4o-mini", ) try: assert agent_state.id is not None assert agent_state.id.startswith("agent-") assert agent_state.embedding_config is None assert agent_state.llm_config is not None finally: client.agents.delete(agent_id=agent_state.id) def test_agent_with_and_without_embedding_coexist(self, agent_without_embedding, agent_with_embedding): """Test that agents with and without embedding can coexist.""" assert agent_without_embedding.id != agent_with_embedding.id assert agent_without_embedding.embedding_config is None assert agent_with_embedding.embedding_config is not None class TestArchivalMemoryInsertWithoutEmbedding: """Tests for inserting archival memory without embeddings.""" def test_insert_passage_without_embedding(self, client: LettaSDKClient, agent_without_embedding): """Test inserting a passage into an agent without embedding config.""" agent_id = agent_without_embedding.id # Insert a passage - use deprecated API but suppress warning with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) passages = client.agents.passages.create( agent_id=agent_id, text="This is a test passage about Python programming.", ) # Should return a list with one passage assert len(passages) == 1 passage = passages[0] assert passage.id is not None assert passage.text == "This is a test passage about Python programming." # Embedding should be None for agents without embedding config assert passage.embedding is None assert passage.embedding_config is None def test_insert_multiple_passages_without_embedding(self, client: LettaSDKClient, agent_without_embedding): """Test inserting multiple passages into an agent without embedding.""" agent_id = agent_without_embedding.id test_passages = [ "Machine learning is a subset of artificial intelligence.", "Python is widely used for data science applications.", "Neural networks can learn complex patterns from data.", ] with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) for text in test_passages: passages = client.agents.passages.create( agent_id=agent_id, text=text, ) assert len(passages) == 1 assert passages[0].embedding is None # Verify all passages were inserted all_passages = client.agents.passages.list(agent_id=agent_id) assert len(all_passages) >= 3 def test_insert_passage_with_tags_without_embedding(self, client: LettaSDKClient, agent_without_embedding): """Test inserting a passage with tags into an agent without embedding.""" agent_id = agent_without_embedding.id with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) passages = client.agents.passages.create( agent_id=agent_id, text="Important fact: The sky is blue due to Rayleigh scattering.", tags=["science", "physics", "important"], ) assert len(passages) == 1 passage = passages[0] assert passage.embedding is None assert passage.tags is not None assert set(passage.tags) == {"science", "physics", "important"} class TestArchivalMemoryListWithoutEmbedding: """Tests for listing archival memory without embeddings.""" def test_list_passages_without_embedding(self, client: LettaSDKClient, agent_without_embedding): """Test listing passages from an agent without embedding.""" agent_id = agent_without_embedding.id # Insert some passages first with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) client.agents.passages.create( agent_id=agent_id, text="First test passage", ) client.agents.passages.create( agent_id=agent_id, text="Second test passage", ) # List passages passages = client.agents.passages.list(agent_id=agent_id) assert len(passages) >= 2 for passage in passages: # Verify embeddings are None assert passage.embedding is None def test_list_passages_with_search_filter(self, client: LettaSDKClient, agent_without_embedding): """Test listing passages with text search filter.""" agent_id = agent_without_embedding.id # Insert passages with distinctive content with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) client.agents.passages.create( agent_id=agent_id, text="Apple is a fruit that grows on trees.", ) client.agents.passages.create( agent_id=agent_id, text="Python is a programming language.", ) # Search for passages containing "fruit" passages = client.agents.passages.list( agent_id=agent_id, search="fruit", ) # Should find the apple passage assert len(passages) >= 1 assert any("fruit" in p.text.lower() for p in passages) class TestArchivalMemorySearchWithoutEmbedding: """Tests for searching archival memory without embeddings (text-based search).""" def test_search_passages_without_embedding(self, client: LettaSDKClient, agent_without_embedding): """Test searching passages using text search (no embeddings).""" agent_id = agent_without_embedding.id # Insert test passages with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) client.agents.passages.create( agent_id=agent_id, text="The capital of France is Paris.", ) client.agents.passages.create( agent_id=agent_id, text="Tokyo is the capital of Japan.", ) client.agents.passages.create( agent_id=agent_id, text="Python is a popular programming language.", ) # Search for passages about capitals results = client.agents.passages.search( agent_id=agent_id, query="capital", ) # Should find passages about capitals (text search) assert results is not None # Check results structure - might be a response object if hasattr(results, "results"): assert len(results.results) >= 1 elif hasattr(results, "__len__"): assert len(results) >= 0 # Might be empty if text search returns 0 def test_global_passage_search_without_embedding(self, client: LettaSDKClient, agent_without_embedding): """Test global passage search endpoint for agent without embedding.""" agent_id = agent_without_embedding.id # Insert a passage with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) client.agents.passages.create( agent_id=agent_id, text="Unique test content for global search testing xyz123.", ) # Use global passage search results = client.passages.search( query="xyz123", agent_id=agent_id, ) # Should find the passage using text search assert results is not None class TestArchivalMemoryDeleteWithoutEmbedding: """Tests for deleting archival memory without embeddings.""" def test_delete_passage_without_embedding(self, client: LettaSDKClient, agent_without_embedding): """Test deleting a passage from an agent without embedding.""" agent_id = agent_without_embedding.id # Insert a passage with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) passages = client.agents.passages.create( agent_id=agent_id, text="Passage to be deleted", ) passage_id = passages[0].id # Delete the passage with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) client.agents.passages.delete( agent_id=agent_id, memory_id=passage_id, ) # Verify it's deleted - should not appear in list remaining = client.agents.passages.list(agent_id=agent_id) assert all(p.id != passage_id for p in remaining) class TestComparisonWithAndWithoutEmbedding: """Compare behavior between agents with and without embedding config.""" def test_passage_insert_comparison( self, client: LettaSDKClient, agent_without_embedding, agent_with_embedding, ): """Compare passage insertion between agents with/without embedding.""" test_text = "Comparison test: This is identical content for both agents." with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) # Insert into agent without embedding passages_no_embed = client.agents.passages.create( agent_id=agent_without_embedding.id, text=test_text, ) # Insert into agent with embedding passages_with_embed = client.agents.passages.create( agent_id=agent_with_embedding.id, text=test_text, ) # Both should succeed assert len(passages_no_embed) == 1 assert len(passages_with_embed) == 1 # Text should be identical assert passages_no_embed[0].text == passages_with_embed[0].text # Embedding status should differ assert passages_no_embed[0].embedding is None assert passages_with_embed[0].embedding is not None def test_list_passages_comparison( self, client: LettaSDKClient, agent_without_embedding, agent_with_embedding, ): """Compare passage listing between agents with/without embedding.""" with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) # Insert passages into both agents client.agents.passages.create( agent_id=agent_without_embedding.id, text="Test passage for listing comparison", ) client.agents.passages.create( agent_id=agent_with_embedding.id, text="Test passage for listing comparison", ) # List from both agents passages_no_embed = client.agents.passages.list(agent_id=agent_without_embedding.id) passages_with_embed = client.agents.passages.list(agent_id=agent_with_embedding.id) # Both should return passages assert len(passages_no_embed) >= 1 assert len(passages_with_embed) >= 1 class TestEdgeCases: """Edge cases and error handling for embedding-optional feature.""" def test_empty_archival_memory_search(self, client: LettaSDKClient, agent_without_embedding): """Test searching an empty archival memory.""" agent_id = agent_without_embedding.id with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) # Search without any passages - should return empty, not error results = client.agents.passages.search( agent_id=agent_id, query="anything", ) # Should return empty results, not raise an error assert results is not None def test_passage_with_special_characters(self, client: LettaSDKClient, agent_without_embedding): """Test inserting passages with special characters.""" agent_id = agent_without_embedding.id special_text = "Special chars: @#$%^&*() 日本語 émojis 🎉 <script>alert('xss')</script>" with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) passages = client.agents.passages.create( agent_id=agent_id, text=special_text, ) assert len(passages) == 1 assert passages[0].text == special_text assert passages[0].embedding is None def test_very_long_passage(self, client: LettaSDKClient, agent_without_embedding): """Test inserting a very long passage.""" agent_id = agent_without_embedding.id # Create a long text (10KB) long_text = "This is a test. " * 1000 with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) passages = client.agents.passages.create( agent_id=agent_id, text=long_text, ) assert len(passages) >= 1 # Might be chunked # First passage should have no embedding assert passages[0].embedding is None
{ "repo_id": "letta-ai/letta", "file_path": "tests/test_embedding_optional.py", "license": "Apache License 2.0", "lines": 359, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
letta-ai/letta:tests/test_minimax_client.py
"""Unit tests for MiniMax client.""" from unittest.mock import AsyncMock, MagicMock, patch import pytest from letta.llm_api.minimax_client import MiniMaxClient from letta.schemas.enums import AgentType from letta.schemas.llm_config import LLMConfig # MiniMax API base URL MINIMAX_BASE_URL = "https://api.minimax.io/anthropic" class TestMiniMaxClient: """Tests for MiniMaxClient.""" def setup_method(self): """Set up test fixtures.""" self.client = MiniMaxClient(put_inner_thoughts_first=True) self.llm_config = LLMConfig( model="MiniMax-M2.1", model_endpoint_type="minimax", model_endpoint=MINIMAX_BASE_URL, context_window=200000, ) def test_is_reasoning_model_always_true(self): """All MiniMax models support native interleaved thinking.""" assert self.client.is_reasoning_model(self.llm_config) is True # Test with different models for model_name in ["MiniMax-M2.1", "MiniMax-M2.1-lightning", "MiniMax-M2"]: config = LLMConfig( model=model_name, model_endpoint_type="minimax", model_endpoint=MINIMAX_BASE_URL, context_window=200000, ) assert self.client.is_reasoning_model(config) is True def test_requires_auto_tool_choice(self): """MiniMax supports all tool choice modes.""" assert self.client.requires_auto_tool_choice(self.llm_config) is False def test_supports_structured_output(self): """MiniMax doesn't currently advertise structured output support.""" assert self.client.supports_structured_output(self.llm_config) is False @patch("letta.llm_api.minimax_client.model_settings") def test_get_anthropic_client_with_api_key(self, mock_settings): """Test client creation with API key.""" mock_settings.minimax_api_key = "test-api-key" with patch("letta.llm_api.minimax_client.anthropic") as mock_anthropic: mock_anthropic.Anthropic.return_value = MagicMock() # Mock BYOK to return no override self.client.get_byok_overrides = MagicMock(return_value=(None, None, None)) self.client._get_anthropic_client(self.llm_config, async_client=False) mock_anthropic.Anthropic.assert_called_once_with( api_key="test-api-key", base_url=MINIMAX_BASE_URL, ) @patch("letta.llm_api.minimax_client.model_settings") def test_get_anthropic_client_async(self, mock_settings): """Test async client creation.""" mock_settings.minimax_api_key = "test-api-key" with patch("letta.llm_api.minimax_client.anthropic") as mock_anthropic: mock_anthropic.AsyncAnthropic.return_value = MagicMock() # Mock BYOK to return no override self.client.get_byok_overrides = MagicMock(return_value=(None, None, None)) self.client._get_anthropic_client(self.llm_config, async_client=True) mock_anthropic.AsyncAnthropic.assert_called_once_with( api_key="test-api-key", base_url=MINIMAX_BASE_URL, ) class TestMiniMaxClientTemperatureClamping: """Tests for temperature clamping in build_request_data.""" def setup_method(self): """Set up test fixtures.""" self.client = MiniMaxClient(put_inner_thoughts_first=True) self.llm_config = LLMConfig( model="MiniMax-M2.1", model_endpoint_type="minimax", model_endpoint=MINIMAX_BASE_URL, context_window=200000, temperature=0.7, ) @patch.object(MiniMaxClient, "build_request_data") def test_temperature_clamping_is_applied(self, mock_build): """Verify build_request_data is called for temperature clamping.""" # This is a basic test to ensure the method exists and can be called mock_build.return_value = {"temperature": 0.7} self.client.build_request_data( agent_type=AgentType.letta_v1_agent, messages=[], llm_config=self.llm_config, ) mock_build.assert_called_once() def test_temperature_zero_clamped(self): """Test that temperature=0 is clamped to 0.01.""" config = LLMConfig( model="MiniMax-M2.1", model_endpoint_type="minimax", model_endpoint=MINIMAX_BASE_URL, context_window=200000, temperature=0, ) # Mock the parent class method to return a basic dict with patch.object(MiniMaxClient.__bases__[0], "build_request_data") as mock_parent: mock_parent.return_value = {"temperature": 0, "model": "MiniMax-M2.1"} result = self.client.build_request_data( agent_type=AgentType.letta_v1_agent, messages=[], llm_config=config, ) # Temperature should be clamped to 0.01 assert result["temperature"] == 0.01 def test_temperature_negative_clamped(self): """Test that negative temperature is clamped to 0.01.""" config = LLMConfig( model="MiniMax-M2.1", model_endpoint_type="minimax", model_endpoint=MINIMAX_BASE_URL, context_window=200000, temperature=-0.5, ) with patch.object(MiniMaxClient.__bases__[0], "build_request_data") as mock_parent: mock_parent.return_value = {"temperature": -0.5, "model": "MiniMax-M2.1"} result = self.client.build_request_data( agent_type=AgentType.letta_v1_agent, messages=[], llm_config=config, ) assert result["temperature"] == 0.01 def test_temperature_above_one_clamped(self): """Test that temperature > 1.0 is clamped to 1.0.""" config = LLMConfig( model="MiniMax-M2.1", model_endpoint_type="minimax", model_endpoint=MINIMAX_BASE_URL, context_window=200000, temperature=1.5, ) with patch.object(MiniMaxClient.__bases__[0], "build_request_data") as mock_parent: mock_parent.return_value = {"temperature": 1.5, "model": "MiniMax-M2.1"} result = self.client.build_request_data( agent_type=AgentType.letta_v1_agent, messages=[], llm_config=config, ) assert result["temperature"] == 1.0 def test_temperature_valid_not_modified(self): """Test that valid temperature values are not modified.""" config = LLMConfig( model="MiniMax-M2.1", model_endpoint_type="minimax", model_endpoint=MINIMAX_BASE_URL, context_window=200000, temperature=0.7, ) with patch.object(MiniMaxClient.__bases__[0], "build_request_data") as mock_parent: mock_parent.return_value = {"temperature": 0.7, "model": "MiniMax-M2.1"} result = self.client.build_request_data( agent_type=AgentType.letta_v1_agent, messages=[], llm_config=config, ) assert result["temperature"] == 0.7 class TestMiniMaxClientUsesNonBetaAPI: """Tests to verify MiniMax client uses non-beta API.""" def test_request_uses_messages_not_beta(self): """Verify request() uses client.messages.create, not client.beta.messages.create.""" client = MiniMaxClient(put_inner_thoughts_first=True) llm_config = LLMConfig( model="MiniMax-M2.1", model_endpoint_type="minimax", model_endpoint=MINIMAX_BASE_URL, context_window=200000, ) with patch.object(client, "_get_anthropic_client") as mock_get_client: mock_anthropic_client = MagicMock() mock_response = MagicMock() mock_response.model_dump.return_value = {"content": [{"type": "text", "text": "Hello"}]} mock_anthropic_client.messages.create.return_value = mock_response mock_get_client.return_value = mock_anthropic_client client.request({"model": "MiniMax-M2.1"}, llm_config) # Verify messages.create was called (not beta.messages.create) mock_anthropic_client.messages.create.assert_called_once() # Verify beta was NOT accessed assert not hasattr(mock_anthropic_client, "beta") or not mock_anthropic_client.beta.messages.create.called @pytest.mark.asyncio async def test_request_async_uses_messages_not_beta(self): """Verify request_async() uses client.messages.create, not client.beta.messages.create.""" client = MiniMaxClient(put_inner_thoughts_first=True) llm_config = LLMConfig( model="MiniMax-M2.1", model_endpoint_type="minimax", model_endpoint=MINIMAX_BASE_URL, context_window=200000, ) with patch.object(client, "_get_anthropic_client_async") as mock_get_client: mock_anthropic_client = AsyncMock() mock_response = MagicMock() mock_response.model_dump.return_value = {"content": [{"type": "text", "text": "Hello"}]} mock_anthropic_client.messages.create.return_value = mock_response mock_get_client.return_value = mock_anthropic_client await client.request_async({"model": "MiniMax-M2.1"}, llm_config) # Verify messages.create was called (not beta.messages.create) mock_anthropic_client.messages.create.assert_called_once() @pytest.mark.asyncio async def test_stream_async_uses_messages_not_beta(self): """Verify stream_async() uses client.messages.create, not client.beta.messages.create.""" client = MiniMaxClient(put_inner_thoughts_first=True) llm_config = LLMConfig( model="MiniMax-M2.1", model_endpoint_type="minimax", model_endpoint=MINIMAX_BASE_URL, context_window=200000, ) with patch.object(client, "_get_anthropic_client_async") as mock_get_client: mock_anthropic_client = AsyncMock() mock_stream = AsyncMock() mock_anthropic_client.messages.create.return_value = mock_stream mock_get_client.return_value = mock_anthropic_client await client.stream_async({"model": "MiniMax-M2.1"}, llm_config) # Verify messages.create was called (not beta.messages.create) mock_anthropic_client.messages.create.assert_called_once() # Verify stream=True was set call_kwargs = mock_anthropic_client.messages.create.call_args[1] assert call_kwargs.get("stream") is True
{ "repo_id": "letta-ai/letta", "file_path": "tests/test_minimax_client.py", "license": "Apache License 2.0", "lines": 218, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test