diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/__init__.py b/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/__init__.py index 163bc219e..58093930b 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/__init__.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/__init__.py @@ -20,13 +20,13 @@ def instrumentation_dependencies(self) -> Collection[str]: def _instrument(self, **kwargs: Any) -> None: """Enable AgentScope instrumentation.""" if is_agentscope_v1(): - from opentelemetry.instrumentation.agentscope.v1 import ( + from opentelemetry.instrumentation.agentscope.v1 import ( # noqa: PLC0415 AgentScopeV1Instrumentor, ) AgentScopeV1Instrumentor().instrument(**kwargs) else: - from opentelemetry.instrumentation.agentscope.v0 import ( + from opentelemetry.instrumentation.agentscope.v0 import ( # noqa: PLC0415 AgentScopeV0Instrumentor, ) @@ -34,13 +34,13 @@ def _instrument(self, **kwargs: Any) -> None: def _uninstrument(self, **kwargs: Any) -> None: if is_agentscope_v1(): - from opentelemetry.instrumentation.agentscope.v1 import ( + from opentelemetry.instrumentation.agentscope.v1 import ( # noqa: PLC0415 AgentScopeV1Instrumentor, ) AgentScopeV1Instrumentor().uninstrument(**kwargs) else: - from opentelemetry.instrumentation.agentscope.v0 import ( + from opentelemetry.instrumentation.agentscope.v0 import ( # noqa: PLC0415 AgentScopeV0Instrumentor, ) diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/v0/__init__.py b/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/v0/__init__.py index e02101833..e630c56c1 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/v0/__init__.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/v0/__init__.py @@ -52,10 +52,10 @@ def _instrument(self, **kwargs: Any) -> None: ) def _uninstrument(self, **kwargs: Any) -> None: - import agentscope.models.model + import agentscope.models.model # noqa: PLC0415 unwrap(agentscope.models.model.ModelWrapperBase, "__init__") - import agentscope.service.service_toolkit + import agentscope.service.service_toolkit # noqa: PLC0415 unwrap( agentscope.service.service_toolkit.ServiceToolkit, "_execute_func" diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/v0/_extractor.py b/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/v0/_extractor.py index 3c2bc6df7..27a776762 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/v0/_extractor.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/v0/_extractor.py @@ -27,9 +27,10 @@ def extract( f"{agent.model_type}", ) - for key in arguments.keys(): + for item in arguments.items(): + key, entry_value = item if key == "messages": - messages = arguments[key] + messages = entry_value for idx in range(len(messages)): message = messages[idx] if "role" in message: @@ -44,7 +45,7 @@ def extract( ) if key == "tools": - tools = arguments[key] + tools = entry_value for idx in range(len(tools)): tool = tools[idx] yield ( @@ -53,17 +54,17 @@ def extract( ) if key == "texts": - if isinstance(arguments[key], str): - yield GenAIAttributes.GEN_AI_PROMPT, f"{arguments[key]}" - elif isinstance(arguments[key], list): - for idx, text in enumerate(arguments[key]): + if isinstance(entry_value, str): + yield GenAIAttributes.GEN_AI_PROMPT, f"{entry_value}" + elif isinstance(entry_value, list): + for idx, text in enumerate(entry_value): yield ( f"{GenAIAttributes.GEN_AI_PROMPT}.{idx}", f"{text}", ) if key == "prompt": - yield GenAIAttributes.GEN_AI_PROMPT, f"{arguments[key]}" + yield GenAIAttributes.GEN_AI_PROMPT, f"{entry_value}" class ModelResponseExtractor(object): diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/v1/__init__.py b/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/v1/__init__.py index e40ae69f6..fbb0a2855 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/v1/__init__.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/v1/__init__.py @@ -154,7 +154,7 @@ def _instrument(self, **kwargs: Any) -> None: def _uninstrument(self, **kwargs: Any) -> None: """移除插装。""" # 恢复被动态替换的方法 - from ._wrapper import ( + from ._wrapper import ( # noqa: PLC0415 AgentScopeV1AgentWrapper, AgentScopeV1ChatModelWrapper, AgentScopeV1EmbeddingModelWrapper, @@ -166,35 +166,35 @@ def _uninstrument(self, **kwargs: Any) -> None: # 恢复直接包装的方法 try: - import agentscope.model + import agentscope.model # noqa: PLC0415 unwrap(agentscope.model.ChatModelBase, "__init__") except Exception: pass try: - import agentscope.embedding + import agentscope.embedding # noqa: PLC0415 unwrap(agentscope.embedding.EmbeddingModelBase, "__init__") except Exception: pass try: - import agentscope.agent + import agentscope.agent # noqa: PLC0415 unwrap(agentscope.agent.AgentBase, "__init__") except Exception: pass try: - import agentscope.tool + import agentscope.tool # noqa: PLC0415 unwrap(agentscope.tool.Toolkit, "call_tool_function") except Exception: pass try: - import agentscope.formatter + import agentscope.formatter # noqa: PLC0415 unwrap(agentscope.formatter.FormatterBase, "format") except Exception: @@ -202,7 +202,7 @@ def _uninstrument(self, **kwargs: Any) -> None: # 恢复 setup_tracing try: - import agentscope.tracing + import agentscope.tracing # noqa: PLC0415 unwrap(agentscope.tracing, "setup_tracing") except Exception: diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/v1/_response_attributes_extractor.py b/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/v1/_response_attributes_extractor.py index 68fa7bf6f..9cd955f75 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/v1/_response_attributes_extractor.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/src/opentelemetry/instrumentation/agentscope/v1/_response_attributes_extractor.py @@ -17,7 +17,7 @@ def _get_chatmodel_output_messages( list[dict[str, Any]]: 格式化的输出消息列表 """ try: - from agentscope.model import ChatResponse + from agentscope.model import ChatResponse # noqa: PLC0415 if not isinstance(chat_response, ChatResponse): # logger.warning(f"Expected ChatResponse, got {type(chat_response)}") diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/tests/shared/version_utils.py b/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/tests/shared/version_utils.py index 4657e0355..4e0b867a8 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/tests/shared/version_utils.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/tests/shared/version_utils.py @@ -45,7 +45,7 @@ def skip_if_no_agentscope(): """如果没有安装agentscope则跳过测试""" try: # test the import of agentscope, skip the warning - import agentscope # noqa: F401 + import agentscope # noqa: F401, PLC0415 return pytest.mark.skipif(False, reason="") except ImportError: diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/tests/v1/test_agentscope_v1.py b/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/tests/v1/test_agentscope_v1.py index 8900c38c1..bc2f1aae3 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/tests/v1/test_agentscope_v1.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-agentscope/tests/v1/test_agentscope_v1.py @@ -10,6 +10,7 @@ from agentscope.message import Msg from agentscope.model import DashScopeChatModel from agentscope.tool import Toolkit, execute_shell_command +from tests.shared.version_utils import skip_if_not_v1 from opentelemetry import trace as trace_api from opentelemetry.instrumentation.agentscope import AgentScopeInstrumentor @@ -21,7 +22,6 @@ from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( InMemorySpanExporter, ) -from tests.shared.version_utils import skip_if_not_v1 @pytest.fixture(scope="module") @@ -84,7 +84,7 @@ def test_agentscope_v1_basic( msg_task = Msg("user", "compute 1615114134*4343434343 for me", "user") # 使用 asyncio 来运行异步函数 - import asyncio + import asyncio # noqa: PLC0415 async def run_agent(): response = await agent(msg_task) @@ -114,7 +114,9 @@ async def run_agent(): check_tool = True # noqa: F841 # 先检查是否至少有模型调用 span - assert check_model, f"Model call span not found. Available spans: {[span.name for span in spans]}" + assert check_model, ( + f"Model call span not found. Available spans: {[span.name for span in spans]}" + ) @skip_if_not_v1() @@ -142,7 +144,7 @@ def test_agentscope_v1_simple_chat( msg_task = Msg("user", "Hello, how are you?", "user") - import asyncio + import asyncio # noqa: PLC0415 async def run_agent(): response = await agent(msg_task) @@ -162,9 +164,9 @@ async def run_agent(): spans = in_memory_span_exporter.get_finished_spans() print(f"Simple chat spans: {[span.name for span in spans]}") model_spans = [span for span in spans if span.name.startswith("chat ")] - assert ( - len(model_spans) > 0 - ), f"No model call span found. Available spans: {[span.name for span in spans]}" + assert len(model_spans) > 0, ( + f"No model call span found. Available spans: {[span.name for span in spans]}" + ) @skip_if_not_v1() @@ -185,7 +187,7 @@ def test_agentscope_v1_model_direct( # 直接调用模型(使用字典格式避免 Msg 对象问题) messages = [{"role": "user", "content": "Hello, what is 1+1?"}] - import asyncio + import asyncio # noqa: PLC0415 async def call_model(): response = await model(messages) @@ -205,9 +207,9 @@ async def call_model(): spans = in_memory_span_exporter.get_finished_spans() print(f"Direct model spans: {[span.name for span in spans]}") model_spans = [span for span in spans if span.name.startswith("chat ")] - assert ( - len(model_spans) > 0 - ), f"No model call span found. Available spans: {[span.name for span in spans]}" + assert len(model_spans) > 0, ( + f"No model call span found. Available spans: {[span.name for span in spans]}" + ) @skip_if_not_v1() @@ -228,7 +230,7 @@ def test_agentscope_v1_span_attributes( # 直接调用模型(使用字典格式) messages = [{"role": "user", "content": "Simple test message"}] - import asyncio + import asyncio # noqa: PLC0415 async def call_model(): response = await model(messages) @@ -245,9 +247,9 @@ async def call_model(): print(f"Attributes test spans: {[span.name for span in spans]}") model_spans = [span for span in spans if span.name.startswith("chat ")] - assert ( - len(model_spans) > 0 - ), f"No model call span found. Available spans: {[span.name for span in spans]}" + assert len(model_spans) > 0, ( + f"No model call span found. Available spans: {[span.name for span in spans]}" + ) # 验证第一个ModelCall span的基本属性 model_span = model_spans[0] diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-agno/src/opentelemetry/instrumentation/agno/__init__.py b/instrumentation-loongsuite/loongsuite-instrumentation-agno/src/opentelemetry/instrumentation/agno/__init__.py index 1503949ca..fb4e5eac1 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-agno/src/opentelemetry/instrumentation/agno/__init__.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-agno/src/opentelemetry/instrumentation/agno/__init__.py @@ -98,7 +98,7 @@ def _instrument(self, **kwargs: Any) -> None: def _uninstrument(self, **kwargs: Any) -> None: # Unwrap the agent call function - import agno.agent + import agno.agent # noqa: PLC0415 unwrap(agno.agent.Agent, "_run") unwrap(agno.agent.Agent, "_arun") @@ -106,13 +106,13 @@ def _uninstrument(self, **kwargs: Any) -> None: unwrap(agno.agent.Agent, "_arun_stream") # Unwrap the function call - import agno.tools.function + import agno.tools.function # noqa: PLC0415 unwrap(agno.tools.function.FunctionCall, "execute") unwrap(agno.tools.function.FunctionCall, "aexecute") # Unwrap the model - import agno.models.base + import agno.models.base # noqa: PLC0415 unwrap(agno.models.base.Model, "response") unwrap(agno.models.base.Model, "aresponse") diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-agno/src/opentelemetry/instrumentation/agno/_extractor.py b/instrumentation-loongsuite/loongsuite-instrumentation-agno/src/opentelemetry/instrumentation/agno/_extractor.py index ae76d80b1..c859a9d8a 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-agno/src/opentelemetry/instrumentation/agno/_extractor.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-agno/src/opentelemetry/instrumentation/agno/_extractor.py @@ -31,8 +31,8 @@ def extract( if agent.tools: tool_names = [] - from agno.tools.function import Function - from agno.tools.toolkit import Toolkit + from agno.tools.function import Function # noqa: PLC0415 + from agno.tools.toolkit import Toolkit # noqa: PLC0415 for tool in agent.tools: if isinstance(tool, Function): @@ -45,14 +45,15 @@ def extract( tool_names.append(str(tool)) yield GenAIAttributes.GEN_AI_TOOL_NAME, ", ".join(tool_names) - for key in arguments.keys(): + for item in arguments.items(): + key, entry_value = item if key == "run_response": yield ( GenAIAttributes.GEN_AI_RESPONSE_ID, - f"{arguments[key].run_id}", + f"{entry_value.run_id}", ) elif key == "run_messages": - messages = arguments[key].messages + messages = entry_value.messages for idx in range(len(messages)): message = messages[idx] yield ( @@ -62,7 +63,7 @@ def extract( elif key == "response_format": yield ( GenAIAttributes.GEN_AI_OPENAI_REQUEST_RESPONSE_FORMAT, - f"{arguments[key]}", + f"{entry_value}", ) @@ -131,14 +132,15 @@ def extract( f"{json.dumps(request_kwargs, indent=2)}", ) - for key in arguments.keys(): + for item in arguments.items(): + key, entry_value = item if key == "response_format": yield ( GenAIAttributes.GEN_AI_OPENAI_REQUEST_RESPONSE_FORMAT, - f"{arguments[key]}", + f"{entry_value}", ) elif key == "messages": - messages = arguments["messages"] + messages = entry_value for idx in range(len(messages)): message = messages[idx] yield ( @@ -146,7 +148,7 @@ def extract( f"{json.dumps(message.to_dict(), indent=2)}", ) elif key == "tools": - tools = arguments["tools"] + tools = entry_value for idx in range(len(tools)): yield ( f"{GenAIAttributes.GEN_AI_TOOL_DESCRIPTION}.{idx}", diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-agno/tests/test_agno.py b/instrumentation-loongsuite/loongsuite-instrumentation-agno/tests/test_agno.py index ec770e3b3..2e32f6642 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-agno/tests/test_agno.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-agno/tests/test_agno.py @@ -77,6 +77,6 @@ def test_agno(in_memory_span_exporter: InMemorySpanExporter): check_model = True if "ToolCall" in span.name: check_tool = True - assert ( - check_agent and check_model and check_tool - ), "Agent, Model or ToolCall span not found" + assert check_agent and check_model and check_tool, ( + "Agent, Model or ToolCall span not found" + ) diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-dify/src/opentelemetry/instrumentation/dify/strategy/workflow_strategy.py b/instrumentation-loongsuite/loongsuite-instrumentation-dify/src/opentelemetry/instrumentation/dify/strategy/workflow_strategy.py index b5987c228..2a2ace968 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-dify/src/opentelemetry/instrumentation/dify/strategy/workflow_strategy.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-dify/src/opentelemetry/instrumentation/dify/strategy/workflow_strategy.py @@ -87,7 +87,7 @@ def process( event_id = kwargs["id"] span = None with self._lock: - from opentelemetry import context + from opentelemetry import context # noqa: PLC0415 ctx = context.get_current() if len(ctx) == 0: diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-langchain/src/opentelemetry/instrumentation/langchain/__init__.py b/instrumentation-loongsuite/loongsuite-instrumentation-langchain/src/opentelemetry/instrumentation/langchain/__init__.py index 11d8a5d9c..b59a10362 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-langchain/src/opentelemetry/instrumentation/langchain/__init__.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-langchain/src/opentelemetry/instrumentation/langchain/__init__.py @@ -29,7 +29,7 @@ def _instrument(self, **kwargs: Any) -> None: if not (tracer_provider := kwargs.get("tracer_provider")): tracer_provider = trace_api.get_tracer_provider() tracer = trace_api.get_tracer(__name__, "", tracer_provider) - from opentelemetry.instrumentation.langchain.internal._tracer import ( + from opentelemetry.instrumentation.langchain.internal._tracer import ( # noqa: PLC0415 LoongsuiteTracer, ) diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-langchain/src/opentelemetry/instrumentation/langchain/internal/_tracer.py b/instrumentation-loongsuite/loongsuite-instrumentation-langchain/src/opentelemetry/instrumentation/langchain/internal/_tracer.py index f23357fa1..c9dbdd9ab 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-langchain/src/opentelemetry/instrumentation/langchain/internal/_tracer.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-langchain/src/opentelemetry/instrumentation/langchain/internal/_tracer.py @@ -393,9 +393,9 @@ def _input_messages( assert hasattr(inputs, "get"), f"expected Mapping, found {type(inputs)}" # There may be more than one set of messages. We'll use just the first set. if multiple_messages := inputs.get("messages"): - assert isinstance( - multiple_messages, Iterable - ), f"expected Iterable, found {type(multiple_messages)}" + assert isinstance(multiple_messages, Iterable), ( + f"expected Iterable, found {type(multiple_messages)}" + ) # This will only get the first set of messages. if not (first_messages := next(iter(multiple_messages), None)): return @@ -442,14 +442,14 @@ def _input_messages( if parsed_messages: yield LLM_INPUT_MESSAGES, parsed_messages elif multiple_prompts := inputs.get("prompts"): - assert isinstance( - multiple_prompts, Iterable - ), f"expected Iterable, found {type(multiple_prompts)}" + assert isinstance(multiple_prompts, Iterable), ( + f"expected Iterable, found {type(multiple_prompts)}" + ) parsed_prompts = [] for prompt_data in multiple_prompts: - assert isinstance( - prompt_data, str - ), f"expected str, found {type(prompt_data)}" + assert isinstance(prompt_data, str), ( + f"expected str, found {type(prompt_data)}" + ) parsed_prompts.append(dict(_parse_prompt_data(prompt_data))) if parsed_prompts: yield LLM_INPUT_MESSAGES, parsed_prompts @@ -466,20 +466,20 @@ def _output_messages( # There may be more than one set of generations. We'll use just the first set. if not (multiple_generations := outputs.get("generations")): return - assert isinstance( - multiple_generations, Iterable - ), f"expected Iterable, found {type(multiple_generations)}" + assert isinstance(multiple_generations, Iterable), ( + f"expected Iterable, found {type(multiple_generations)}" + ) # This will only get the first set of generations. if not (first_generations := next(iter(multiple_generations), None)): return - assert isinstance( - first_generations, Iterable - ), f"expected Iterable, found {type(first_generations)}" + assert isinstance(first_generations, Iterable), ( + f"expected Iterable, found {type(first_generations)}" + ) parsed_messages = [] for generation in first_generations: - assert hasattr( - generation, "get" - ), f"expected Mapping, found {type(generation)}" + assert hasattr(generation, "get"), ( + f"expected Mapping, found {type(generation)}" + ) if message_data := generation.get("message"): if isinstance(message_data, BaseMessage): parsed_messages.append( @@ -494,15 +494,15 @@ def _output_messages( elif text := generation.get("text"): parsed_messages.append(text) if generation_info := generation.get("generation_info"): - assert hasattr( - generation_info, "get" - ), f"expected Mapping, found {type(generation_info)}" + assert hasattr(generation_info, "get"), ( + f"expected Mapping, found {type(generation_info)}" + ) if finish_reason := generation_info.get("finish_reason"): yield LLM_RESPONSE_FINISH_REASON, finish_reason if token_usage := generation_info.get("token_usage"): - assert hasattr( - token_usage, "get" - ), f"expected Mapping, found {type(token_usage)}" + assert hasattr(token_usage, "get"), ( + f"expected Mapping, found {type(token_usage)}" + ) for attribute_name, key in [ (LLM_USAGE_PROMPT_TOKENS, "input_tokens"), (LLM_USAGE_COMPLETION_TOKENS, "output_tokens"), @@ -514,9 +514,9 @@ def _output_messages( yield LLM_OUTPUT_MESSAGES, parsed_messages if not (llm_output := outputs.get("llm_output")): return - assert hasattr( - llm_output, "get" - ), f"expected Mapping, found {type(llm_output)}" + assert hasattr(llm_output, "get"), ( + f"expected Mapping, found {type(llm_output)}" + ) if model_name := llm_output.get("model_name"): yield LLM_RESPONSE_MODEL_NAME, model_name @@ -527,9 +527,9 @@ def _parse_prompt_data( ) -> Iterator[Tuple[str, Any]]: if not prompt_data: return - assert isinstance( - prompt_data, str - ), f"expected str, found {type(prompt_data)}" + assert isinstance(prompt_data, str), ( + f"expected str, found {type(prompt_data)}" + ) yield CONTENT, process_content(prompt_data) @@ -581,9 +581,9 @@ def _parse_message_data( raise ValueError(f"Cannot parse message of type: {message_class_name}") yield MESSAGE_ROLE, role if kwargs := message_data.get("kwargs"): - assert hasattr( - kwargs, "get" - ), f"expected Mapping, found {type(kwargs)}" + assert hasattr(kwargs, "get"), ( + f"expected Mapping, found {type(kwargs)}" + ) if content := kwargs.get("content"): if isinstance(content, str): yield MESSAGE_CONTENT, process_content(content) @@ -610,27 +610,27 @@ def _parse_message_data( else: logger.warning(f"Expected str for name, found {type(name)}") if additional_kwargs := kwargs.get("additional_kwargs"): - assert hasattr( - additional_kwargs, "get" - ), f"expected Mapping, found {type(additional_kwargs)}" + assert hasattr(additional_kwargs, "get"), ( + f"expected Mapping, found {type(additional_kwargs)}" + ) if function_call := additional_kwargs.get("function_call"): - assert hasattr( - function_call, "get" - ), f"expected Mapping, found {type(function_call)}" + assert hasattr(function_call, "get"), ( + f"expected Mapping, found {type(function_call)}" + ) if name := function_call.get("name"): - assert isinstance( - name, str - ), f"expected str, found {type(name)}" + assert isinstance(name, str), ( + f"expected str, found {type(name)}" + ) yield MESSAGE_FUNCTION_CALL_NAME, name if arguments := function_call.get("arguments"): - assert isinstance( - arguments, str - ), f"expected str, found {type(arguments)}" + assert isinstance(arguments, str), ( + f"expected str, found {type(arguments)}" + ) yield MESSAGE_FUNCTION_CALL_ARGUMENTS_JSON, arguments if tool_calls := additional_kwargs.get("tool_calls"): - assert isinstance( - tool_calls, Iterable - ), f"expected Iterable, found {type(tool_calls)}" + assert isinstance(tool_calls, Iterable), ( + f"expected Iterable, found {type(tool_calls)}" + ) message_tool_calls = [] for tool_call in tool_calls: if message_tool_call := dict(_get_tool_call(tool_call)): @@ -645,20 +645,20 @@ def _get_tool_call( ) -> Iterator[Tuple[str, Any]]: if not tool_call: return - assert hasattr( - tool_call, "get" - ), f"expected Mapping, found {type(tool_call)}" + assert hasattr(tool_call, "get"), ( + f"expected Mapping, found {type(tool_call)}" + ) if function := tool_call.get("function"): - assert hasattr( - function, "get" - ), f"expected Mapping, found {type(function)}" + assert hasattr(function, "get"), ( + f"expected Mapping, found {type(function)}" + ) if name := function.get("name"): assert isinstance(name, str), f"expected str, found {type(name)}" yield TOOL_CALL_FUNCTION_NAME, name if arguments := function.get("arguments"): - assert isinstance( - arguments, str - ), f"expected str, found {type(arguments)}" + assert isinstance(arguments, str), ( + f"expected str, found {type(arguments)}" + ) yield TOOL_CALL_FUNCTION_ARGUMENTS_JSON, arguments @@ -671,9 +671,9 @@ def _prompt_template(run: Run) -> Iterator[Tuple[str, Any]]: serialized: Optional[Mapping[str, Any]] = run.serialized if not serialized: return - assert hasattr( - serialized, "get" - ), f"expected Mapping, found {type(serialized)}" + assert hasattr(serialized, "get"), ( + f"expected Mapping, found {type(serialized)}" + ) if not (kwargs := serialized.get("kwargs")): return assert isinstance(kwargs, dict), f"expected dict, found {type(kwargs)}" @@ -688,16 +688,16 @@ def _prompt_template(run: Run) -> Iterator[Tuple[str, Any]]: if id_[-1].endswith("PromptTemplate"): if not (kwargs := obj.get("kwargs")): continue - assert hasattr( - kwargs, "get" - ), f"expected Mapping, found {type(kwargs)}" + assert hasattr(kwargs, "get"), ( + f"expected Mapping, found {type(kwargs)}" + ) if not (template := kwargs.get("template", "")): continue yield LLM_PROMPT_TEMPLATE, template if input_variables := kwargs.get("input_variables"): - assert isinstance( - input_variables, list - ), f"expected list, found {type(input_variables)}" + assert isinstance(input_variables, list), ( + f"expected list, found {type(input_variables)}" + ) template_variables = {} for variable in input_variables: if (value := run.inputs.get(variable)) is not None: @@ -810,9 +810,9 @@ def _tools(run: Run) -> Iterator[Tuple[str, str]]: return if not (serialized := run.serialized): return - assert hasattr( - serialized, "get" - ), f"expected Mapping, found {type(serialized)}" + assert hasattr(serialized, "get"), ( + f"expected Mapping, found {type(serialized)}" + ) if name := serialized.get("name"): yield TOOL_NAME, name if description := serialized.get("description"): @@ -829,9 +829,9 @@ def _retrieval_documents( return assert hasattr(outputs, "get"), f"expected Mapping, found {type(outputs)}" documents = outputs.get("documents") - assert isinstance( - documents, Iterable - ), f"expected Iterable, found {type(documents)}" + assert isinstance(documents, Iterable), ( + f"expected Iterable, found {type(documents)}" + ) yield ( RETRIEVAL_DOCUMENTS, [dict(_as_document(document)) for document in documents], @@ -869,14 +869,14 @@ def _metadata(run: Run) -> Iterator[Tuple[str, str]]: @stop_on_exception def _as_document(document: Any) -> Iterator[Tuple[str, Any]]: if page_content := getattr(document, "page_content", None): - assert isinstance( - page_content, str - ), f"expected str, found {type(page_content)}" + assert isinstance(page_content, str), ( + f"expected str, found {type(page_content)}" + ) yield DOCUMENT_CONTENT, process_content(page_content) if metadata := getattr(document, "metadata", None): - assert isinstance( - metadata, Mapping - ), f"expected Mapping, found {type(metadata)}" + assert isinstance(metadata, Mapping), ( + f"expected Mapping, found {type(metadata)}" + ) yield DOCUMENT_METADATA, json.dumps(metadata, cls=_SafeJSONEncoder) diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_langchain_instrumentor.py b/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_langchain_instrumentor.py index ab8142825..c3d362106 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_langchain_instrumentor.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_langchain_instrumentor.py @@ -459,7 +459,7 @@ def _generate(self, *args, **kwargs): spans = in_memory_span_exporter.get_finished_spans() for span in spans: if span.name == "RunnableSequence": - from opentelemetry import trace as trace_api + from opentelemetry import trace as trace_api # noqa: PLC0415 assert span.status.status_code == trace_api.StatusCode.ERROR assert span.events[0].name == "exception" diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_message_parsing.py b/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_message_parsing.py index c8dd384b6..e036488f1 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_message_parsing.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_message_parsing.py @@ -197,9 +197,9 @@ def test_parse_message_data(self, test_case): for key, expected_value in test_case["expected"].items(): if key == MessageAttributes.MESSAGE_TOOL_CALLS: tool_calls = result.get(key) - assert ( - tool_calls is not None - ), f"Expected tool_calls for {test_case['name']}" + assert tool_calls is not None, ( + f"Expected tool_calls for {test_case['name']}" + ) # 检查tool_calls列表中是否包含期望的函数名 found = False for tool_call in tool_calls: @@ -211,12 +211,14 @@ def test_parse_message_data(self, test_case): ): found = True break - assert found, f"Expected calculator function in tool_calls for {test_case['name']}" + assert found, ( + f"Expected calculator function in tool_calls for {test_case['name']}" + ) else: actual_value = result.get(key) - assert ( - actual_value == expected_value - ), f"Expected {expected_value}, got {actual_value} for {test_case['name']}" + assert actual_value == expected_value, ( + f"Expected {expected_value}, got {actual_value} for {test_case['name']}" + ) class TestInputMessagesParsing: @@ -264,6 +266,6 @@ class TestInputMessagesParsing: def test_input_messages_parsing(self, test_case): """测试输入消息解析""" result = list(_input_messages(test_case["input"])) - assert ( - len(result) == test_case["expected_count"] - ), f"Expected {test_case['expected_count']} results for {test_case['name']}" + assert len(result) == test_case["expected_count"], ( + f"Expected {test_case['expected_count']} results for {test_case['name']}" + ) diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_metadata.py b/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_metadata.py index 0abcd9577..d8a6ed86c 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_metadata.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_metadata.py @@ -289,16 +289,16 @@ def test_metadata_parsing(self, test_case): result = list(_metadata(mock_run)) # 验证结果数量 - assert ( - len(result) == len(test_case["expected"]) - ), f"Expected {len(test_case['expected'])} results, got {len(result)} for {test_case['name']}" + assert len(result) == len(test_case["expected"]), ( + f"Expected {len(test_case['expected'])} results, got {len(result)} for {test_case['name']}" + ) # 验证每个结果 for i, (actual_key, actual_value) in enumerate(result): expected_key, expected_value = test_case["expected"][i] - assert ( - actual_key == expected_key - ), f"Expected key {expected_key}, got {actual_key} for {test_case['name']}" - assert ( - actual_value == expected_value - ), f"Expected value {expected_value}, got {actual_value} for {test_case['name']}" + assert actual_key == expected_key, ( + f"Expected key {expected_key}, got {actual_key} for {test_case['name']}" + ) + assert actual_value == expected_value, ( + f"Expected value {expected_value}, got {actual_value} for {test_case['name']}" + ) diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_prompts.py b/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_prompts.py index 244f9e537..e7e8d974f 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_prompts.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_prompts.py @@ -176,19 +176,19 @@ def test_prompts_parsing(self, test_case): result = list(_prompts(test_case["inputs"])) # 验证结果数量 - assert ( - len(result) == len(test_case["expected"]) - ), f"Expected {len(test_case['expected'])} results, got {len(result)} for {test_case['name']}" + assert len(result) == len(test_case["expected"]), ( + f"Expected {len(test_case['expected'])} results, got {len(result)} for {test_case['name']}" + ) # 验证每个结果 for i, (actual_key, actual_value) in enumerate(result): expected_key, expected_value = test_case["expected"][i] - assert ( - actual_key == expected_key - ), f"Expected key {expected_key}, got {actual_key} for {test_case['name']}" - assert ( - actual_value == expected_value - ), f"Expected value {expected_value}, got {actual_value} for {test_case['name']}" + assert actual_key == expected_key, ( + f"Expected key {expected_key}, got {actual_key} for {test_case['name']}" + ) + assert actual_value == expected_value, ( + f"Expected value {expected_value}, got {actual_value} for {test_case['name']}" + ) def test_prompts_with_invalid_prompt_types(self): """测试包含无效prompt类型的情况""" diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_singleton_tracer.py b/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_singleton_tracer.py index b464b2b82..f9394554d 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_singleton_tracer.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-langchain/tests/instrumentation/langchain/test_singleton_tracer.py @@ -98,7 +98,7 @@ def test_parent_context_resolution_core_logic( parent_run_id = uuid.uuid4() child_run_id = uuid.uuid4() - from datetime import datetime + from datetime import datetime # noqa: PLC0415 parent_run = Run( id=parent_run_id, @@ -140,9 +140,9 @@ def test_parent_context_resolution_core_logic( first_handler._start_trace(parent_run) # 验证parent run被保存 - assert ( - parent_run_id in first_handler._runs - ), "parent run应该被保存到第一个handler的_runs" + assert parent_run_id in first_handler._runs, ( + "parent run应该被保存到第一个handler的_runs" + ) # 第二次调用:关键测试点 - 验证单例行为 second_manager = BaseCallbackManager(handlers=[]) @@ -159,9 +159,9 @@ def test_parent_context_resolution_core_logic( # 关键验证:第二个handler能否看到parent run parent_in_second_handler = second_handler._runs.get(parent_run_id) - assert ( - parent_in_second_handler is not None - ), "第二个handler应该能看到parent run(链路连续)" + assert parent_in_second_handler is not None, ( + "第二个handler应该能看到parent run(链路连续)" + ) # 模拟第二个handler处理child run with patch.object(second_handler, "_tracer") as mock_tracer: @@ -177,9 +177,9 @@ def test_parent_context_resolution_core_logic( else None ) - assert ( - parent_context_found is not None - ), "child run应该能找到parent context(链路连续)" + assert parent_context_found is not None, ( + "child run应该能找到parent context(链路连续)" + ) # 处理child run second_handler._start_trace(child_run) diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-mcp/src/opentelemetry/instrumentation/mcp/__init__.py b/instrumentation-loongsuite/loongsuite-instrumentation-mcp/src/opentelemetry/instrumentation/mcp/__init__.py index 31c7281da..0f589b6ba 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-mcp/src/opentelemetry/instrumentation/mcp/__init__.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-mcp/src/opentelemetry/instrumentation/mcp/__init__.py @@ -123,7 +123,7 @@ def _instrument(self, **kwargs: Any) -> None: def _uninstrument(self, **kwargs: Any) -> None: try: - from mcp import ClientSession + from mcp import ClientSession # noqa: PLC0415 for method_name, _ in _client_session_methods: unwrap(ClientSession, method_name) @@ -131,14 +131,14 @@ def _uninstrument(self, **kwargs: Any) -> None: logger.warning("Fail to uninstrument ClientSession", exc_info=True) try: - import mcp.client.sse + import mcp.client.sse # noqa: PLC0415 unwrap(mcp.client.sse, "sse_client") except Exception: logger.warning("Fail to uninstrument sse_client", exc_info=True) try: - import mcp.client.streamable_http + import mcp.client.streamable_http # noqa: PLC0415 unwrap(mcp.client.streamable_http, "streamablehttp_client") except Exception: @@ -147,7 +147,7 @@ def _uninstrument(self, **kwargs: Any) -> None: ) try: - import mcp.client.stdio + import mcp.client.stdio # noqa: PLC0415 unwrap(mcp.client.stdio, "stdio_client") except Exception: @@ -155,7 +155,7 @@ def _uninstrument(self, **kwargs: Any) -> None: if _is_ws_installed(): try: - import mcp.client.websocket + import mcp.client.websocket # noqa: PLC0415 unwrap(mcp.client.websocket, "websocket_client") except Exception: @@ -164,7 +164,7 @@ def _uninstrument(self, **kwargs: Any) -> None: ) try: - import mcp.server.lowlevel.server + import mcp.server.lowlevel.server # noqa: PLC0415 unwrap(mcp.server.lowlevel.server, "Server._handle_request") except Exception: diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-mcp/src/opentelemetry/instrumentation/mcp/utils.py b/instrumentation-loongsuite/loongsuite-instrumentation-mcp/src/opentelemetry/instrumentation/mcp/utils.py index 35d364a33..42655cdc3 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-mcp/src/opentelemetry/instrumentation/mcp/utils.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-mcp/src/opentelemetry/instrumentation/mcp/utils.py @@ -49,7 +49,7 @@ def _get_max_attribute_length() -> int: def _is_ws_installed() -> bool: try: # test the import of websockets, skip the warning - import websockets # noqa: F401 + import websockets # noqa: F401, PLC0415 return True except ImportError: diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/fastmcp_server.py b/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/fastmcp_server.py index 21bd88c40..44dcde077 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/fastmcp_server.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/fastmcp_server.py @@ -28,7 +28,9 @@ def create_tracer_provider(): def do_instrument(): - from opentelemetry.instrumentation.mcp import MCPInstrumentor + from opentelemetry.instrumentation.mcp import ( # noqa: PLC0415 + MCPInstrumentor, + ) instrumentor = MCPInstrumentor() instrumentor._instrument(tracer_provider=create_tracer_provider()) diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/mcp_server.py b/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/mcp_server.py index 50cc9adca..5f036580d 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/mcp_server.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/mcp_server.py @@ -14,8 +14,8 @@ def create_mcp_server(): - import mcp.types as types - from mcp.server import Server + import mcp.types as types # noqa: PLC0415 + from mcp.server import Server # noqa: PLC0415 server = Server("example-server") @@ -116,14 +116,16 @@ def create_tracer_provider(): # Run the server as STDIO async def main(): if do_instrument: - from opentelemetry.instrumentation.mcp import MCPInstrumentor + from opentelemetry.instrumentation.mcp import ( # noqa: PLC0415 + MCPInstrumentor, + ) instrumentor = MCPInstrumentor() instrumentor._instrument(tracer_provider=create_tracer_provider()) - from mcp.server import NotificationOptions - from mcp.server.models import InitializationOptions - from mcp.server.stdio import stdio_server + from mcp.server import NotificationOptions # noqa: PLC0415 + from mcp.server.models import InitializationOptions # noqa: PLC0415 + from mcp.server.stdio import stdio_server # noqa: PLC0415 server = create_mcp_server() async with stdio_server() as (read_stream, write_stream): @@ -142,7 +144,7 @@ async def main(): if __name__ == "__main__": - import asyncio + import asyncio # noqa: PLC0415 if len(sys.argv) > 1 and sys.argv[1] == "instrument": do_instrument = True diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_instrument.py b/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_instrument.py index 52fe62c19..0d965066b 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_instrument.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_instrument.py @@ -14,11 +14,11 @@ def test_instrumentation_dependencies(): def test_instrument(tracer_provider): - import mcp.client.sse - import mcp.client.stdio - import mcp.client.streamable_http - import mcp.client.websocket - from mcp.client.session import ClientSession + import mcp.client.sse # noqa: PLC0415 + import mcp.client.stdio # noqa: PLC0415 + import mcp.client.streamable_http # noqa: PLC0415 + import mcp.client.websocket # noqa: PLC0415 + from mcp.client.session import ClientSession # noqa: PLC0415 assert not isinstance(ClientSession.list_prompts, BoundFunctionWrapper) mcp_instrumentor = MCPInstrumentor() diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_propagate.py b/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_propagate.py index 61506418a..4ec27497d 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_propagate.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_propagate.py @@ -26,10 +26,10 @@ def instrumentor( @pytest.mark.asyncio async def test_send_request_propagator(memory_exporter, tracer_provider): - from mcp import ClientSession, StdioServerParameters - from mcp.client.stdio import stdio_client - from mcp.shared.message import SessionMessage - from mcp.types import JSONRPCRequest + from mcp import ClientSession, StdioServerParameters # noqa: PLC0415 + from mcp.client.stdio import stdio_client # noqa: PLC0415 + from mcp.shared.message import SessionMessage # noqa: PLC0415 + from mcp.types import JSONRPCRequest # noqa: PLC0415 server_params = StdioServerParameters( command="python", diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_session_handler.py b/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_session_handler.py index 3fc66da62..af14fd5e8 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_session_handler.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_session_handler.py @@ -26,10 +26,10 @@ async def mock_client(params): @pytest.mark.asyncio async def test_client_invalid(tracer_provider): - import mcp.client.sse - import mcp.client.stdio - import mcp.client.streamable_http - import mcp.client.websocket + import mcp.client.sse # noqa: PLC0415 + import mcp.client.stdio # noqa: PLC0415 + import mcp.client.streamable_http # noqa: PLC0415 + import mcp.client.websocket # noqa: PLC0415 stdio_client_backup = mcp.client.stdio.stdio_client websocket_client_backup = mcp.client.websocket.websocket_client @@ -45,10 +45,12 @@ async def test_client_invalid(tracer_provider): mcp_instrumentor = MCPInstrumentor() mcp_instrumentor._instrument(tracer_provider=tracer_provider) - from mcp.client.sse import sse_client - from mcp.client.stdio import stdio_client - from mcp.client.streamable_http import streamablehttp_client - from mcp.client.websocket import websocket_client + from mcp.client.sse import sse_client # noqa: PLC0415 + from mcp.client.stdio import stdio_client # noqa: PLC0415 + from mcp.client.streamable_http import ( # noqa: PLC0415 + streamablehttp_client, + ) + from mcp.client.websocket import websocket_client # noqa: PLC0415 assert isinstance(stdio_client, FunctionWrapper) assert isinstance(websocket_client, FunctionWrapper) @@ -98,9 +100,12 @@ async def send(self, *args, **kwargs): async def test_send_wrapper(tracer_provider): mcp_instrumentor = MCPInstrumentor() mcp_instrumentor._instrument(tracer_provider=tracer_provider) - from mcp.client.stdio import StdioServerParameters, stdio_client + from mcp.client.stdio import ( # noqa: PLC0415 + StdioServerParameters, + stdio_client, + ) - from opentelemetry.instrumentation.mcp.session_handler import ( + from opentelemetry.instrumentation.mcp.session_handler import ( # noqa: PLC0415 _writer_send_wrapper, ) @@ -160,8 +165,8 @@ async def test_send_wrapper(tracer_provider): async def test_server_handle_request_wrapper(tracer_provider): mcp_instrumentor = MCPInstrumentor() mcp_instrumentor._instrument(tracer_provider=tracer_provider) - from mcp.shared.session import RequestResponder - from mcp.types import ( + from mcp.shared.session import RequestResponder # noqa: PLC0415 + from mcp.types import ( # noqa: PLC0415 CallToolRequest, CallToolRequestParams, ClientRequest, @@ -174,7 +179,9 @@ async def test_server_handle_request_wrapper(tracer_provider): SubscribeRequestParams, ) - from opentelemetry.instrumentation.mcp.semconv import MCPAttributes + from opentelemetry.instrumentation.mcp.semconv import ( # noqa: PLC0415 + MCPAttributes, + ) wrapper = _create_server_wrapper(mcp_instrumentor, tracer_provider) @@ -276,7 +283,7 @@ async def test_server_handle_request_wrapper(tracer_provider): def _create_server_wrapper(mcp_instrumentor, tracer_provider): - from opentelemetry.instrumentation.mcp.session_handler import ( + from opentelemetry.instrumentation.mcp.session_handler import ( # noqa: PLC0415 ServerHandleRequestWrapper, ) @@ -298,8 +305,12 @@ def _create_server_wrapper(mcp_instrumentor, tracer_provider): async def test_server_extract_parent_context(tracer_provider): mcp_instrumentor = MCPInstrumentor() mcp_instrumentor._instrument(tracer_provider=tracer_provider) - from mcp.shared.session import RequestResponder - from mcp.types import ClientRequest, ListToolsRequest, RequestParams + from mcp.shared.session import RequestResponder # noqa: PLC0415 + from mcp.types import ( # noqa: PLC0415 + ClientRequest, + ListToolsRequest, + RequestParams, + ) wrapper = _create_server_wrapper(mcp_instrumentor, tracer_provider) diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_stdio.py b/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_stdio.py index 40bbc3332..7e8703760 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_stdio.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_stdio.py @@ -36,7 +36,7 @@ async def test_call_tool(memory_exporter): command="python", args=[FASTMCP_SERVER_SCRIPT], ) - from mcp.client.stdio import stdio_client + from mcp.client.stdio import stdio_client # noqa: PLC0415 async with stdio_client(server_params) as (stdio, write): async with ClientSession(stdio, write) as session: @@ -67,7 +67,7 @@ async def test_subscribe_resource(memory_exporter): command="python", args=[MCP_SERVER_SCRIPT], ) - from mcp.client.stdio import stdio_client + from mcp.client.stdio import stdio_client # noqa: PLC0415 async with stdio_client(server_params) as (stdio, write): async with ClientSession(stdio, write) as session: diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_websocket.py b/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_websocket.py index 3d5c4cff6..faaf3f854 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_websocket.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-mcp/tests/test_websocket.py @@ -64,7 +64,7 @@ def server_url(server_port: int) -> str: # Test server implementation def create_server(): - from mcp.server import Server + from mcp.server import Server # noqa: PLC0415 server = Server(SERVER_NAME) @@ -115,7 +115,7 @@ async def handle_call_tool(name: str, args: dict) -> list[TextContent]: def make_server_app() -> Starlette: """Create test Starlette app with WebSocket transport""" server = create_server() - from mcp.server.websocket import websocket_server + from mcp.server.websocket import websocket_server # noqa: PLC0415 async def handle_ws(websocket): async with websocket_server( @@ -205,10 +205,10 @@ def server(server_port) -> Generator[None, None, None]: @pytest.mark.asyncio async def test_ws_client_basic_connection(server, server_url: str) -> None: """Test the WebSocket connection establishment""" - from mcp.client.websocket import websocket_client + from mcp.client.websocket import websocket_client # noqa: PLC0415 async with websocket_client(server_url + "/ws") as streams: - from mcp.client.session import ClientSession + from mcp.client.session import ClientSession # noqa: PLC0415 async with ClientSession(*streams) as session: # Test initialization @@ -226,10 +226,10 @@ async def test_ws_client_happy_request_and_response( server: None, server_url: str, memory_exporter, tracer_provider, find_span ) -> None: """Test a successful request and response via WebSocket""" - from mcp.client.websocket import websocket_client + from mcp.client.websocket import websocket_client # noqa: PLC0415 async with websocket_client(server_url + "/ws") as streams: - from mcp.client.session import ClientSession + from mcp.client.session import ClientSession # noqa: PLC0415 async with ClientSession(*streams) as session: result = await session.initialize() diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-mem0/src/opentelemetry/instrumentation/mem0/internal/_util.py b/instrumentation-loongsuite/loongsuite-instrumentation-mem0/src/opentelemetry/instrumentation/mem0/internal/_util.py index 2231d891d..54ce079af 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-mem0/src/opentelemetry/instrumentation/mem0/internal/_util.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-mem0/src/opentelemetry/instrumentation/mem0/internal/_util.py @@ -99,7 +99,7 @@ def _normalize_provider_from_class(instance: Any) -> Optional[str]: Infer provider name from instance class name by removing common suffixes and lowercasing. Example: QdrantVectorStore -> qdrant; PineconeIndex -> pinecone """ - from opentelemetry.instrumentation.mem0.semconv import ( + from opentelemetry.instrumentation.mem0.semconv import ( # noqa: PLC0415 PROVIDER_CLASS_SUFFIXES, ) diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/conftest.py b/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/conftest.py index 74398aeb4..08acdbe6a 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/conftest.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/conftest.py @@ -390,7 +390,7 @@ def vcr_config(request): # Flatten cassette files to tests/cassettes directory without subdirectories def _flatten_path(path: str) -> str: - import os as _os + import os as _os # noqa: PLC0415 base = _os.path.basename(path) if not base.endswith(".yaml"): diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_extractors.py b/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_extractors.py index 62d93d849..1bfbb2503 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_extractors.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_extractors.py @@ -413,7 +413,7 @@ def test_extract_attributes_unified_add(self): def test_input_messages_string(self): """Tests extracting input messages from string - directly returns original value""" - from opentelemetry.instrumentation.mem0.config import ( + from opentelemetry.instrumentation.mem0.config import ( # noqa: PLC0415 should_capture_content, ) @@ -436,7 +436,7 @@ def test_input_messages_string(self): def test_input_messages_dict_with_content(self): """Tests extracting input messages from dict - directly returns original value""" - from opentelemetry.instrumentation.mem0.config import ( + from opentelemetry.instrumentation.mem0.config import ( # noqa: PLC0415 should_capture_content, ) @@ -463,7 +463,7 @@ def test_input_messages_dict_with_content(self): def test_input_messages_list_original(self): """Tests extracting input messages from list - directly returns original value""" - from opentelemetry.instrumentation.mem0.config import ( + from opentelemetry.instrumentation.mem0.config import ( # noqa: PLC0415 should_capture_content, ) @@ -492,7 +492,7 @@ def test_input_messages_list_original(self): def test_output_messages_original(self): """Tests output messages - Return original content directly""" - from opentelemetry.instrumentation.mem0.config import ( + from opentelemetry.instrumentation.mem0.config import ( # noqa: PLC0415 should_capture_content, ) @@ -673,7 +673,7 @@ def test_extract_attributes_unified_delete(self): def test_output_messages_memory_client_add_respects_async_mode(self): """MemoryClient.add: only capture output.messages when async_mode=False""" - from opentelemetry.instrumentation.mem0.config import ( + from opentelemetry.instrumentation.mem0.config import ( # noqa: PLC0415 should_capture_content, ) @@ -757,7 +757,7 @@ def test_extract_common_attributes(self): def test_update_input_messages_with_data(self): """Tests update operation extracting data as input content""" - from opentelemetry.instrumentation.mem0.config import ( + from opentelemetry.instrumentation.mem0.config import ( # noqa: PLC0415 should_capture_content, ) @@ -784,7 +784,7 @@ def test_update_input_messages_with_data(self): def test_update_input_messages_with_text(self): """Tests update operation extracting text as input content (MemoryClient)""" - from opentelemetry.instrumentation.mem0.config import ( + from opentelemetry.instrumentation.mem0.config import ( # noqa: PLC0415 should_capture_content, ) @@ -811,7 +811,7 @@ def test_update_input_messages_with_text(self): def test_batch_update_input_messages(self): """Tests batch_update operation extracting memories list as input content""" - from opentelemetry.instrumentation.mem0.config import ( + from opentelemetry.instrumentation.mem0.config import ( # noqa: PLC0415 should_capture_content, ) diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_instrumentor.py b/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_instrumentor.py index a9309d321..9ca126fbc 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_instrumentor.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_instrumentor.py @@ -268,8 +268,8 @@ def _private_method(self): def test_public_methods_of_module(self): """Tests getting public methods of a class from module (via temporary module).""" - import sys - import types + import sys # noqa: PLC0415 + import types # noqa: PLC0415 test_mod = types.ModuleType("test_module") diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_memory_client_errors_vcr.py b/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_memory_client_errors_vcr.py index 35285d114..a287412fe 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_memory_client_errors_vcr.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_memory_client_errors_vcr.py @@ -33,7 +33,7 @@ def test_client_connection_error_vcr( - Asserts top-level span is marked as ERROR and contains error.type Note: First time requires --record-mode=all in real environment to record exception; afterwards playback mode replays the exception. """ - from opentelemetry.trace import StatusCode + from opentelemetry.trace import StatusCode # noqa: PLC0415 # Unreachable address (port 9 is typically not listened to, triggers connection refused) host = os.environ.get("MEM0_ERROR_HOST", "http://127.0.0.1:9") @@ -55,12 +55,12 @@ def test_client_connection_error_vcr( error_spans = [ s for s in spans if s.status.status_code == StatusCode.ERROR ] - assert ( - error_spans - ), "Should generate at least one top-level span with ERROR status" - assert any( - "error.type" in s.attributes for s in error_spans - ), "Error span should contain error.type" + assert error_spans, ( + "Should generate at least one top-level span with ERROR status" + ) + assert any("error.type" in s.attributes for s in error_spans), ( + "Error span should contain error.type" + ) def _start_test_http_server(status_code: int) -> Tuple[HTTPServer, str]: @@ -112,7 +112,7 @@ def test_client_http_401_vcr( """ Returns 401 via local controllable HTTP service, records and replays exception. """ - from opentelemetry.trace import StatusCode + from opentelemetry.trace import StatusCode # noqa: PLC0415 server, base_url = _start_test_http_server(401) try: @@ -148,7 +148,7 @@ def test_client_http_500_vcr( """ Returns 500 via local controllable HTTP service, records and replays exception. """ - from opentelemetry.trace import StatusCode + from opentelemetry.trace import StatusCode # noqa: PLC0415 server, base_url = _start_test_http_server(500) try: diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_memory_operations_record_vcr.py b/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_memory_operations_record_vcr.py index b7e07b81f..0a62e0460 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_memory_operations_record_vcr.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_memory_operations_record_vcr.py @@ -75,10 +75,10 @@ def test_record_memory_full_flow_vcr( Memory = pytest.importorskip("mem0.memory.main").Memory # Import needed mock modules - import sys + import sys # noqa: PLC0415 sys.path.insert(0, os.path.dirname(__file__)) - from conftest import patch_factories + from conftest import patch_factories # noqa: PLC0415 # Patch factories before creating Memory instance patch_factories(monkeypatch) @@ -88,7 +88,7 @@ def test_record_memory_full_flow_vcr( # patch_factories already provides fake vector storage, no additional mock needed # but need to set FakeLLM and FakeEmbedder (these are not created via factory) - from conftest import FakeEmbedder, FakeLLM + from conftest import FakeEmbedder, FakeLLM # noqa: PLC0415 m.llm = FakeLLM() m.embedding_model = FakeEmbedder() @@ -132,10 +132,10 @@ def test_record_memory_full_flow_vcr( mem_id = results_list[0].get("id") else: # When no memory is generated, insert seed data into FakeVectorStore and get its id - import sys + import sys # noqa: PLC0415 sys.path.insert(0, os.path.dirname(__file__)) - from conftest import get_fake_vector_store # type: ignore + from conftest import get_fake_vector_store # noqa: PLC0415 store = get_fake_vector_store() store.insert(payloads=[{"data": "seed memory for tests"}]) @@ -204,10 +204,14 @@ def test_record_memory_add_vcr( """Memory add operation test: verify add memory attributes""" Memory = pytest.importorskip("mem0.memory.main").Memory - import sys + import sys # noqa: PLC0415 sys.path.insert(0, os.path.dirname(__file__)) - from conftest import FakeEmbedder, FakeLLM, patch_factories + from conftest import ( # noqa: PLC0415 + FakeEmbedder, + FakeLLM, + patch_factories, + ) patch_factories(monkeypatch) config = _build_demo_config_from_env() @@ -278,10 +282,14 @@ def test_record_memory_get_all_vcr( """Memory get_all operation test: verify get all memory attributes""" Memory = pytest.importorskip("mem0.memory.main").Memory - import sys + import sys # noqa: PLC0415 sys.path.insert(0, os.path.dirname(__file__)) - from conftest import FakeEmbedder, FakeLLM, patch_factories + from conftest import ( # noqa: PLC0415 + FakeEmbedder, + FakeLLM, + patch_factories, + ) patch_factories(monkeypatch) config = _build_demo_config_from_env() @@ -348,10 +356,10 @@ def test_record_memory_get_vcr( """Memory get operation test: verify get single memory attributes""" Memory = pytest.importorskip("mem0.memory.main").Memory - import sys + import sys # noqa: PLC0415 sys.path.insert(0, os.path.dirname(__file__)) - from conftest import ( + from conftest import ( # noqa: PLC0415 FakeEmbedder, FakeLLM, get_fake_vector_store, @@ -420,10 +428,14 @@ def test_record_memory_search_vcr( """Memory search operation test: verify search memory attributes""" Memory = pytest.importorskip("mem0.memory.main").Memory - import sys + import sys # noqa: PLC0415 sys.path.insert(0, os.path.dirname(__file__)) - from conftest import FakeEmbedder, FakeLLM, patch_factories + from conftest import ( # noqa: PLC0415 + FakeEmbedder, + FakeLLM, + patch_factories, + ) patch_factories(monkeypatch) config = _build_demo_config_from_env() @@ -490,10 +502,10 @@ def test_record_memory_update_vcr( """Memory update operation test: verify update memory attributes""" Memory = pytest.importorskip("mem0.memory.main").Memory - import sys + import sys # noqa: PLC0415 sys.path.insert(0, os.path.dirname(__file__)) - from conftest import ( + from conftest import ( # noqa: PLC0415 FakeEmbedder, FakeLLM, get_fake_vector_store, @@ -567,10 +579,10 @@ def test_record_memory_delete_vcr( """Memory delete operation test: verify delete memory attributes""" Memory = pytest.importorskip("mem0.memory.main").Memory - import sys + import sys # noqa: PLC0415 sys.path.insert(0, os.path.dirname(__file__)) - from conftest import ( + from conftest import ( # noqa: PLC0415 FakeEmbedder, FakeLLM, get_fake_vector_store, @@ -637,10 +649,10 @@ def test_record_memory_history_vcr( """Memory history operation test: verify get memory history attributes""" Memory = pytest.importorskip("mem0.memory.main").Memory - import sys + import sys # noqa: PLC0415 sys.path.insert(0, os.path.dirname(__file__)) - from conftest import ( + from conftest import ( # noqa: PLC0415 FakeEmbedder, FakeLLM, get_fake_vector_store, @@ -714,10 +726,14 @@ def test_record_memory_delete_all_vcr( """Memory delete_all operation test: verify delete all memory attributes""" Memory = pytest.importorskip("mem0.memory.main").Memory - import sys + import sys # noqa: PLC0415 sys.path.insert(0, os.path.dirname(__file__)) - from conftest import FakeEmbedder, FakeLLM, patch_factories + from conftest import ( # noqa: PLC0415 + FakeEmbedder, + FakeLLM, + patch_factories, + ) patch_factories(monkeypatch) config = _build_demo_config_from_env() diff --git a/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_memory_operations_vcr.py b/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_memory_operations_vcr.py index b748b3b7f..5f01fb51a 100644 --- a/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_memory_operations_vcr.py +++ b/instrumentation-loongsuite/loongsuite-instrumentation-mem0/tests/test_memory_operations_vcr.py @@ -202,7 +202,7 @@ def test_memory_add_full_flow( ) -> None: _patch_factories(monkeypatch) - from mem0.memory.main import Memory + from mem0.memory.main import Memory # noqa: PLC0415 m = cast(Any, Memory()) # Override instance internal dependencies to avoid real external calls @@ -241,7 +241,7 @@ def test_memory_search_full_flow( ) -> None: _patch_factories(monkeypatch) - from mem0.memory.main import Memory + from mem0.memory.main import Memory # noqa: PLC0415 m = cast(Any, Memory()) # Override instance internal dependencies @@ -289,14 +289,14 @@ def test_internal_subphases_attributes( Note: LLM and Embedding do not need to generate spans (handled by corresponding LLM plugins) """ - import os - import sys + import os # noqa: PLC0415 + import sys # noqa: PLC0415 - from mem0.configs.base import MemoryConfig, RerankerConfig - from mem0.memory.main import Memory + from mem0.configs.base import MemoryConfig, RerankerConfig # noqa: PLC0415 + from mem0.memory.main import Memory # noqa: PLC0415 sys.path.insert(0, os.path.dirname(__file__)) - from conftest import FakeEmbedder, FakeLLM + from conftest import FakeEmbedder, FakeLLM # noqa: PLC0415 # Configure reranker so Memory creates via factory (thus will be instrumented) config = MemoryConfig() @@ -342,7 +342,9 @@ def test_internal_subphases_attributes( assert any( s.attributes.get("gen_ai.memory.vector.method") in valid_vec_methods for s in vec_spans - ), f"Vector method should be one of valid values, actual: {[s.attributes.get('gen_ai.memory.vector.method') for s in vec_spans]}" + ), ( + f"Vector method should be one of valid values, actual: {[s.attributes.get('gen_ai.memory.vector.method') for s in vec_spans]}" + ) # Verify provider (now uses data_source.type) assert any( s.attributes.get("gen_ai.memory.data_source.type") is not None @@ -358,9 +360,9 @@ def test_internal_subphases_attributes( if m.reranker is not None: # If Memory instance has reranker, should be able to collect reranker span # Because reranker is created via factory, will be instrumented - assert ( - reranker_spans - ), "When reranker exists, should collect reranker stage spans" + assert reranker_spans, ( + "When reranker exists, should collect reranker stage spans" + ) # Verify attributes assert any( s.attributes.get("gen_ai.provider.name") is not None @@ -374,9 +376,9 @@ def test_internal_subphases_attributes( if s.attributes.get("gen_ai.memory.graph.method") is not None ] if m.enable_graph: - assert ( - graph_spans - ), "When graph is enabled, should collect graph stage spans" + assert graph_spans, ( + "When graph is enabled, should collect graph stage spans" + ) # 4. LLM and Embedding: do not require generating mem0 subphase spans # These should be handled by corresponding LLM/Embedding plugins @@ -390,13 +392,13 @@ def test_vector_operations_detailed_attributes( verify whether Vector operation detailed attributes are correctly collected. Including: provider, method, limit, filters.keys, result_count, etc. """ - import os - import sys + import os # noqa: PLC0415 + import sys # noqa: PLC0415 - from mem0.memory.main import Memory + from mem0.memory.main import Memory # noqa: PLC0415 sys.path.insert(0, os.path.dirname(__file__)) - from conftest import FakeEmbedder, FakeLLM + from conftest import FakeEmbedder, FakeLLM # noqa: PLC0415 m = cast(Any, Memory()) m.llm = FakeLLM() @@ -438,17 +440,17 @@ def test_vector_operations_detailed_attributes( or "gen_ai.memory.vector.k" in search_span.attributes ), "search span should contain limit or k" # Verify filter_keys (note: actual attribute name is filter_keys, not filters.keys) - assert ( - "gen_ai.memory.vector.filter_keys" in search_span.attributes - ), "search span should contain filter_keys" + assert "gen_ai.memory.vector.filter_keys" in search_span.attributes, ( + "search span should contain filter_keys" + ) filter_keys = search_span.attributes.get( "gen_ai.memory.vector.filter_keys" ) assert "user_id" in filter_keys, "filter_keys should contain user_id" # Verify result_count - assert ( - "gen_ai.memory.vector.result_count" in search_span.attributes - ), "search span should contain result_count" + assert "gen_ai.memory.vector.result_count" in search_span.attributes, ( + "search span should contain result_count" + ) @pytest.mark.vcr() @@ -459,14 +461,17 @@ def test_graph_operations_detailed_attributes( verify whether Graph operation detailed attributes are correctly collected. Including: provider, method, result_count, etc. """ - import os - import sys + import os # noqa: PLC0415 + import sys # noqa: PLC0415 - from mem0.configs.base import GraphStoreConfig, MemoryConfig - from mem0.memory.main import Memory + from mem0.configs.base import ( # noqa: PLC0415 + GraphStoreConfig, + MemoryConfig, + ) + from mem0.memory.main import Memory # noqa: PLC0415 sys.path.insert(0, os.path.dirname(__file__)) - from conftest import FakeEmbedder, FakeLLM + from conftest import FakeEmbedder, FakeLLM # noqa: PLC0415 # Enable graph (using kuzu as provider, but will be intercepted by patch_factories to return FakeGraphStore) config = MemoryConfig() @@ -511,9 +516,9 @@ def test_graph_operations_detailed_attributes( result_count = add_span.attributes.get( "gen_ai.memory.graph.result_count" ) - assert ( - result_count is not None and result_count >= 0 - ), f"add span should contain result_count, actual value: {result_count}" + assert result_count is not None and result_count >= 0, ( + f"add span should contain result_count, actual value: {result_count}" + ) @pytest.mark.vcr() @@ -524,14 +529,14 @@ def test_reranker_operations_detailed_attributes( verify whether Reranker operation detailed attributes are correctly collected. Including: provider, top_k, input_count, etc. """ - import os - import sys + import os # noqa: PLC0415 + import sys # noqa: PLC0415 - from mem0.configs.base import MemoryConfig, RerankerConfig - from mem0.memory.main import Memory + from mem0.configs.base import MemoryConfig, RerankerConfig # noqa: PLC0415 + from mem0.memory.main import Memory # noqa: PLC0415 sys.path.insert(0, os.path.dirname(__file__)) - from conftest import FakeEmbedder, FakeLLM + from conftest import FakeEmbedder, FakeLLM # noqa: PLC0415 config = MemoryConfig() config.reranker = RerankerConfig(provider="cohere", config={}) @@ -552,9 +557,9 @@ def test_reranker_operations_detailed_attributes( assert reranker_spans, "should collect reranker spans" reranker_span = reranker_spans[0] - assert ( - reranker_span.attributes.get("gen_ai.provider.name") == "fake" - ), "should contain correct provider.name" + assert reranker_span.attributes.get("gen_ai.provider.name") == "fake", ( + "should contain correct provider.name" + ) # Now uses gen_ai.rerank.documents_count instead of gen_ai.memory.reranker.input_count if "gen_ai.rerank.documents_count" in reranker_span.attributes: documents_count = reranker_span.attributes.get(