Skip to content

Commit d451de2

Browse files
committed
chore: fix ruff check failure
Change-Id: Ib739c8edde37921c0c8b6b9d7289465d28896af3 Co-developed-by: Cursor <noreply@cursor.com>
1 parent 503edcf commit d451de2

File tree

8 files changed

+144
-141
lines changed

8 files changed

+144
-141
lines changed

instrumentation-loongsuite/loongsuite-instrumentation-google-adk/examples/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ async def run_conversation(
247247

248248
except Exception as e:
249249
logger.error(f"处理消息时出错: {e}")
250-
import traceback
250+
import traceback # noqa: PLC0415
251251

252252
logger.error(f"详细错误信息: {traceback.format_exc()}")
253253
raise HTTPException(status_code=500, detail=f"处理消息失败: {str(e)}")

instrumentation-loongsuite/loongsuite-instrumentation-google-adk/src/opentelemetry/instrumentation/google_adk/__init__.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
from opentelemetry.util.genai.extended_handler import ExtendedTelemetryHandler
2727

2828
from .internal._plugin import GoogleAdkObservabilityPlugin
29-
from .version import __version__
29+
from .version import __version__ as __version__ # noqa: F401
3030

3131
_logger = logging.getLogger(__name__)
3232

@@ -168,7 +168,7 @@ def _instrument(self, **kwargs):
168168
- logger_provider: Custom logger provider
169169
"""
170170
# Check if google-adk is installed
171-
import importlib.util
171+
import importlib.util # noqa: PLC0415
172172

173173
if importlib.util.find_spec("google.adk.runners") is None:
174174
_logger.warning(
@@ -181,7 +181,9 @@ def _instrument(self, **kwargs):
181181
logger_provider = kwargs.get("logger_provider")
182182

183183
# Create or get the global plugin instance
184-
_create_plugin_if_needed(tracer_provider, meter_provider, logger_provider)
184+
_create_plugin_if_needed(
185+
tracer_provider, meter_provider, logger_provider
186+
)
185187

186188
# Wrap the Runner initialization to auto-inject our plugin
187189
try:
@@ -205,7 +207,7 @@ def _uninstrument(self, **kwargs):
205207

206208
try:
207209
# Unwrap the Runner initialization
208-
from google.adk.runners import Runner
210+
from google.adk.runners import Runner # noqa: PLC0415
209211

210212
unwrap(Runner, "__init__")
211213

instrumentation-loongsuite/loongsuite-instrumentation-google-adk/src/opentelemetry/instrumentation/google_adk/internal/_plugin.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -92,13 +92,11 @@ async def before_run_callback(
9292
According to OTel GenAI conventions, Runner is treated as a top-level agent.
9393
"""
9494
try:
95-
# Extract conversation_id and user_id
95+
# Extract conversation_id
9696
conversation_id = None
97-
user_id = None
9897

9998
if invocation_context.session:
10099
conversation_id = invocation_context.session.id
101-
user_id = getattr(invocation_context, "user_id", None)
102100

103101
# Create invocation object
104102
invocation = InvokeAgentInvocation(
@@ -269,17 +267,13 @@ async def before_agent_callback(
269267
Start Agent execution - create invoke_agent span.
270268
"""
271269
try:
272-
# Extract conversation_id and user_id
270+
# Extract conversation_id
273271
conversation_id = None
274-
user_id = None
275272

276273
if callback_context._invocation_context.session:
277274
conversation_id = (
278275
callback_context._invocation_context.session.id
279276
)
280-
user_id = getattr(
281-
callback_context._invocation_context, "user_id", None
282-
)
283277

284278
# Create invocation object
285279
invocation = InvokeAgentInvocation(
@@ -304,7 +298,9 @@ async def before_agent_callback(
304298
agent_key = f"agent_{id(agent)}_{conversation_id}"
305299
self._active_agent_invocations[agent_key] = invocation
306300

307-
_logger.debug(f"Started Agent invocation: invoke_agent {agent.name}")
301+
_logger.debug(
302+
f"Started Agent invocation: invoke_agent {agent.name}"
303+
)
308304

309305
except Exception as e:
310306
_logger.exception(f"Error in before_agent_callback: {e}")
@@ -376,7 +372,7 @@ async def before_model_callback(
376372
invocation.attributes["gen_ai.conversation.id"] = (
377373
callback_context._invocation_context.session.id
378374
)
379-
375+
380376
user_id = getattr(callback_context, "user_id", None)
381377
if not user_id:
382378
user_id = getattr(
@@ -465,7 +461,9 @@ async def after_model_callback(
465461
model_name = self._resolve_model_name(
466462
llm_response, request_key, llm_invocation
467463
)
468-
_logger.debug(f"Finished LLM invocation for model {model_name}")
464+
_logger.debug(
465+
f"Finished LLM invocation for model {model_name}"
466+
)
469467

470468
except Exception as e:
471469
_logger.exception(f"Error in after_model_callback: {e}")
@@ -718,7 +716,9 @@ def _convert_llm_response_to_output_messages(
718716

719717
try:
720718
# Extract finish reason
721-
finish_reason = getattr(llm_response, "finish_reason", None) or "stop"
719+
finish_reason = (
720+
getattr(llm_response, "finish_reason", None) or "stop"
721+
)
722722
if hasattr(finish_reason, "value"):
723723
finish_reason = finish_reason.value
724724
elif not isinstance(finish_reason, (str, int, float, bool)):

instrumentation-loongsuite/loongsuite-instrumentation-google-adk/tests/conftest.py

Lines changed: 28 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,7 @@
33

44
import json
55
import os
6-
import re
7-
from typing import List, Optional
6+
from typing import List
87

98
import pytest
109
import yaml
@@ -28,7 +27,6 @@
2827
from opentelemetry.sdk.trace.export.in_memory_span_exporter import (
2928
InMemorySpanExporter,
3029
)
31-
from opentelemetry.sdk.trace.sampling import ALWAYS_OFF
3230
from opentelemetry.util.genai.environment_variables import (
3331
OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT,
3432
)
@@ -189,11 +187,11 @@ def instrument_with_content_and_events(
189187
def find_spans_by_operation(spans: List, operation_name: str) -> List:
190188
"""
191189
Find spans by operation name.
192-
190+
193191
Args:
194192
spans: List of spans to search
195193
operation_name: Operation name to search for (e.g., "chat", "invoke_agent")
196-
194+
197195
Returns:
198196
List of spans matching the operation name
199197
"""
@@ -207,11 +205,11 @@ def find_spans_by_operation(spans: List, operation_name: str) -> List:
207205
def find_spans_by_name_prefix(spans: List, prefix: str) -> List:
208206
"""
209207
Find spans by name prefix.
210-
208+
211209
Args:
212210
spans: List of spans to search
213211
prefix: Prefix to match against span names
214-
212+
215213
Returns:
216214
List of spans with names starting with the prefix
217215
"""
@@ -221,37 +219,38 @@ def find_spans_by_name_prefix(spans: List, prefix: str) -> List:
221219
def print_span_tree(spans: List, indent: int = 0):
222220
"""
223221
Print span hierarchy as a tree structure.
224-
222+
225223
Args:
226224
spans: List of spans to print
227225
indent: Current indentation level
228226
"""
229227
# Build a map of span_id -> span for quick lookup
230228
span_map = {span.context.span_id: span for span in spans}
231-
229+
232230
# Find root spans (spans with no parent or parent not in the list)
233231
root_spans = [
234232
span
235233
for span in spans
236-
if span.parent is None
237-
or span.parent.span_id not in span_map
234+
if span.parent is None or span.parent.span_id not in span_map
238235
]
239-
236+
240237
def print_span_recursive(span, level=0):
241238
"""Recursively print span and its children"""
242239
prefix = " " * level
243240
operation = span.attributes.get("gen_ai.operation.name", "unknown")
244241
print(f"{prefix}- {span.name} ({operation})")
245-
242+
246243
# Find children
247244
children = [
248-
s for s in spans
249-
if s.parent is not None and s.parent.span_id == span.context.span_id
245+
s
246+
for s in spans
247+
if s.parent is not None
248+
and s.parent.span_id == span.context.span_id
250249
]
251-
250+
252251
for child in children:
253252
print_span_recursive(child, level + 1)
254-
253+
255254
for root_span in root_spans:
256255
print_span_recursive(root_span, indent)
257256

@@ -273,20 +272,20 @@ def literal_block_scalar_presenter(dumper, data):
273272

274273
def process_string_value(string_value):
275274
"""Format JSON or return long string as LiteralBlockScalar"""
276-
import gzip
277-
275+
import gzip # noqa: PLC0415
276+
278277
# Handle bytes type - decompress if gzip, then decode
279278
if isinstance(string_value, bytes):
280279
try:
281280
# Check if gzip compressed (magic number 0x1f 0x8b)
282-
if string_value[:2] == b'\x1f\x8b':
283-
string_value = gzip.decompress(string_value).decode('utf-8')
281+
if string_value[:2] == b"\x1f\x8b":
282+
string_value = gzip.decompress(string_value).decode("utf-8")
284283
else:
285-
string_value = string_value.decode('utf-8')
284+
string_value = string_value.decode("utf-8")
286285
except Exception:
287286
# If we can't decode, return as-is (will be handled by YAML)
288287
return string_value
289-
288+
290289
try:
291290
json_data = json.loads(string_value)
292291
return LiteralBlockScalar(json.dumps(json_data, indent=2))
@@ -344,13 +343,13 @@ def fixture_vcr(vcr):
344343
def normalize_request_headers(request):
345344
"""
346345
Normalize request headers by removing dynamic headers that change between requests.
347-
346+
348347
This function removes headers like x-stainless-retry-count that may differ
349348
between recording and playback, causing VCR matching failures.
350-
349+
351350
Args:
352351
request: VCR request object
353-
352+
354353
Returns:
355354
Request object with normalized headers
356355
"""
@@ -418,7 +417,9 @@ def vcr_config():
418417
"before_record_request": normalize_request_headers,
419418
# Ignore LiteLLM's model price fetching requests to avoid matching issues
420419
# These requests are made by LiteLLM internally and don't affect our tests
421-
"ignore_hosts": ["raw.githubusercontent.com"], # Ignore LiteLLM model price requests
420+
"ignore_hosts": [
421+
"raw.githubusercontent.com"
422+
], # Ignore LiteLLM model price requests
422423
# Allow recording new interactions when cassette exists
423424
"record_mode": "new_episodes",
424425
}

0 commit comments

Comments
 (0)