Skip to content

Commit 5b46d7c

Browse files
author
Max Rabin
committed
Run Upgrade Python syntax by using Pyupgrade, adding it to Ruff (UP).
1 parent c24060d commit 5b46d7c

33 files changed

Lines changed: 755 additions & 552 deletions

scripts/bump_version.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
import sys
44
from datetime import datetime
55
from pathlib import Path
6-
from typing import Optional, Tuple
76

87

98
def get_current_version() -> str:
@@ -16,7 +15,7 @@ def get_current_version() -> str:
1615
return match.group(1)
1716

1817

19-
def parse_version(version: str) -> Tuple[int, int, int, Optional[str]]:
18+
def parse_version(version: str) -> tuple[int, int, int, str | None]:
2019
"""Parse semantic version string."""
2120
match = re.match(r"(\d+)\.(\d+)\.(\d+)(?:-(.+))?", version)
2221
if not match:
@@ -135,7 +134,7 @@ def format_git_log(git_log: str) -> str:
135134
return "\n\n".join(sections)
136135

137136

138-
def get_git_log(since_tag: Optional[str] = None) -> str:
137+
def get_git_log(since_tag: str | None = None) -> str:
139138
"""Get git commit messages since last tag."""
140139
cmd = ["git", "log", "--pretty=format:- %s (%h)"]
141140
if since_tag:
@@ -219,7 +218,7 @@ def main():
219218
print(f"\n✓ Version bumped from {current} to {new}")
220219
print("\nNext steps:")
221220
print("1. Review changes: git diff")
222-
print("2. Commit: git add -A && git commit -m 'chore: bump version to {}'".format(new))
221+
print(f"2. Commit: git add -A && git commit -m 'chore: bump version to {new}'")
223222
print("3. Create PR or push to trigger release workflow")
224223

225224
except Exception as e:

src/bedrock_agentcore/evaluation/integrations/strands_agents_evals/evaluator.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import asyncio
44
import logging
5-
from typing import Any, List, Optional
5+
from typing import Any
66

77
import boto3
88
from botocore.config import Config
@@ -40,7 +40,7 @@ def _validate_spans(spans):
4040
return hasattr(first_span, "context") and hasattr(first_span, "instrumentation_scope")
4141

4242

43-
def _is_adot_format(spans: List[Any]) -> bool:
43+
def _is_adot_format(spans: list[Any]) -> bool:
4444
"""Check if spans are already in ADOT format.
4545
4646
ADOT format is detected by presence of 'scope' dict with 'name' field.
@@ -82,7 +82,7 @@ def __init__(
8282
evaluator_id: str,
8383
region: str = DEFAULT_REGION,
8484
test_pass_score: float = 0.7,
85-
config: Optional[Config] = None,
85+
config: Config | None = None,
8686
):
8787
"""Initialize the evaluator.
8888
@@ -109,7 +109,7 @@ def _get_default_config() -> Config:
109109
read_timeout=300,
110110
)
111111

112-
def evaluate(self, evaluation_case: EvaluationData[InputT, OutputT]) -> List[EvaluationOutput]:
112+
def evaluate(self, evaluation_case: EvaluationData[InputT, OutputT]) -> list[EvaluationOutput]:
113113
"""Evaluate agent output using AgentCore Evaluation API.
114114
115115
Args:
@@ -153,7 +153,7 @@ def evaluate(self, evaluation_case: EvaluationData[InputT, OutputT]) -> List[Eva
153153
for r in response["evaluationResults"]
154154
]
155155

156-
async def evaluate_async(self, evaluation_case: EvaluationData[InputT, OutputT]) -> List[EvaluationOutput]:
156+
async def evaluate_async(self, evaluation_case: EvaluationData[InputT, OutputT]) -> list[EvaluationOutput]:
157157
"""Evaluate agent output asynchronously using AgentCore Evaluation API.
158158
159159
Args:

src/bedrock_agentcore/evaluation/span_to_adot_serializer/adot_models.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
import logging
1313
from dataclasses import dataclass
14-
from typing import Any, Dict, List, Optional
14+
from typing import Any
1515

1616
logger = logging.getLogger(__name__)
1717

@@ -27,7 +27,7 @@ class SpanMetadata:
2727

2828
trace_id: str
2929
span_id: str
30-
parent_span_id: Optional[str]
30+
parent_span_id: str | None
3131
name: str
3232
start_time: int
3333
end_time: int
@@ -41,7 +41,7 @@ class SpanMetadata:
4141
class ResourceInfo:
4242
"""Span resource and scope information."""
4343

44-
resource_attributes: Dict[str, Any]
44+
resource_attributes: dict[str, Any]
4545
scope_name: str
4646
scope_version: str
4747

@@ -51,8 +51,8 @@ class ConversationTurn:
5151
"""A single user-assistant conversation turn."""
5252

5353
user_message: str
54-
assistant_messages: List[Dict[str, Any]]
55-
tool_results: List[str]
54+
assistant_messages: list[dict[str, Any]]
55+
tool_results: list[str]
5656

5757

5858
@dataclass
@@ -115,7 +115,7 @@ def extract_resource_info(span) -> ResourceInfo:
115115
)
116116

117117
@staticmethod
118-
def get_span_attributes(span) -> Dict[str, Any]:
118+
def get_span_attributes(span) -> dict[str, Any]:
119119
"""Safely extract span attributes."""
120120
return dict(span.attributes) if hasattr(span, "attributes") and span.attributes else {}
121121

@@ -140,8 +140,8 @@ class ADOTDocumentBuilder:
140140
def build_span_document(
141141
metadata: SpanMetadata,
142142
resource_info: ResourceInfo,
143-
attributes: Dict[str, Any],
144-
) -> Dict[str, Any]:
143+
attributes: dict[str, Any],
144+
) -> dict[str, Any]:
145145
"""Build ADOT span document."""
146146
return {
147147
"resource": {"attributes": resource_info.resource_attributes},
@@ -167,8 +167,8 @@ def _build_log_record_base(
167167
cls,
168168
metadata: SpanMetadata,
169169
resource_info: ResourceInfo,
170-
body: Dict[str, Any],
171-
) -> Dict[str, Any]:
170+
body: dict[str, Any],
171+
) -> dict[str, Any]:
172172
"""Build base ADOT log record structure shared by all log types."""
173173
return {
174174
"resource": {"attributes": resource_info.resource_attributes},
@@ -190,7 +190,7 @@ def build_conversation_log_record(
190190
conversation: ConversationTurn,
191191
metadata: SpanMetadata,
192192
resource_info: ResourceInfo,
193-
) -> Dict[str, Any]:
193+
) -> dict[str, Any]:
194194
"""Build ADOT log record for conversation turn."""
195195
output_messages = []
196196
for i, msg in enumerate(conversation.assistant_messages):
@@ -217,7 +217,7 @@ def build_tool_log_record(
217217
tool_exec: ToolExecution,
218218
metadata: SpanMetadata,
219219
resource_info: ResourceInfo,
220-
) -> Dict[str, Any]:
220+
) -> dict[str, Any]:
221221
"""Build ADOT log record for tool execution."""
222222
body = {
223223
"output": {

src/bedrock_agentcore/evaluation/span_to_adot_serializer/strands_converter.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
"""
1111

1212
import logging
13-
from typing import Any, Dict, List, Optional
13+
from typing import Any
1414

1515
from .adot_models import (
1616
ADOTDocumentBuilder,
@@ -36,7 +36,7 @@ class StrandsEventParser:
3636
EVENT_TOOL_MESSAGE = "gen_ai.tool.message"
3737

3838
@classmethod
39-
def extract_conversation_turn(cls, events: List[Any]) -> Optional[ConversationTurn]:
39+
def extract_conversation_turn(cls, events: list[Any]) -> ConversationTurn | None:
4040
"""Extract conversation turn from Strands span events."""
4141
user_message = None
4242
assistant_messages = []
@@ -83,7 +83,7 @@ def extract_conversation_turn(cls, events: List[Any]) -> Optional[ConversationTu
8383
return None
8484

8585
@classmethod
86-
def extract_tool_execution(cls, events: List[Any]) -> Optional[ToolExecution]:
86+
def extract_tool_execution(cls, events: list[Any]) -> ToolExecution | None:
8787
"""Extract tool execution from Strands span events."""
8888
tool_input = ""
8989
tool_output = ""
@@ -126,7 +126,7 @@ def __init__(self):
126126
self.event_parser = StrandsEventParser()
127127
self.doc_builder = ADOTDocumentBuilder()
128128

129-
def convert_span(self, span) -> List[Dict[str, Any]]:
129+
def convert_span(self, span) -> list[dict[str, Any]]:
130130
"""Convert a single span to ADOT documents."""
131131
documents = []
132132

@@ -160,7 +160,7 @@ def convert_span(self, span) -> List[Dict[str, Any]]:
160160

161161
return documents
162162

163-
def convert(self, raw_spans: List[Any]) -> List[Dict[str, Any]]:
163+
def convert(self, raw_spans: list[Any]) -> list[dict[str, Any]]:
164164
"""Convert list of Strands OTel spans to ADOT documents."""
165165
documents = []
166166
for span in raw_spans:
@@ -174,7 +174,7 @@ def convert(self, raw_spans: List[Any]) -> List[Dict[str, Any]]:
174174
# ==============================================================================
175175

176176

177-
def convert_strands_to_adot(raw_spans: List[Any]) -> List[Dict[str, Any]]:
177+
def convert_strands_to_adot(raw_spans: list[Any]) -> list[dict[str, Any]]:
178178
"""Convert Strands OTel spans to ADOT format for AgentCore evaluation.
179179
180180
Args:

src/bedrock_agentcore/evaluation/utils/cloudwatch_span_helper.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import logging
55
import time
66
from datetime import datetime
7-
from typing import Any, List
7+
from typing import Any
88

99
import boto3
1010

@@ -43,7 +43,7 @@ def query_log_group(
4343
session_id: str,
4444
start_time: datetime,
4545
end_time: datetime,
46-
) -> List[dict]:
46+
) -> list[dict]:
4747
"""Query a single CloudWatch log group for session data.
4848
4949
Args:
@@ -133,7 +133,7 @@ def fetch_spans(
133133
session_id: str,
134134
event_log_group: str,
135135
start_time: datetime,
136-
) -> List[dict]:
136+
) -> list[dict]:
137137
"""Fetch ADOT spans from CloudWatch with configurable event log group.
138138
139139
ADOT spans are always fetched from aws/spans. Event logs can be fetched from
@@ -185,7 +185,7 @@ def fetch_spans_from_cloudwatch(
185185
event_log_group: str,
186186
start_time: datetime,
187187
region: str = DEFAULT_REGION,
188-
) -> List[dict]:
188+
) -> list[dict]:
189189
"""Fetch ADOT spans from CloudWatch with configurable event log group.
190190
191191
Convenience function that creates a CloudWatchSpanFetcher and fetches spans.

src/bedrock_agentcore/identity/auth.py

Lines changed: 12 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@
44
import contextvars
55
import logging
66
import os
7+
from collections.abc import Callable
78
from functools import wraps
8-
from typing import Any, Callable, Dict, List, Literal, Optional
9+
from typing import Any, Literal
910

1011
import boto3
1112
from botocore.exceptions import ClientError
@@ -23,14 +24,14 @@ def requires_access_token(
2324
*,
2425
provider_name: str,
2526
into: str = "access_token",
26-
scopes: List[str],
27-
on_auth_url: Optional[Callable[[str], Any]] = None,
27+
scopes: list[str],
28+
on_auth_url: Callable[[str], Any] | None = None,
2829
auth_flow: Literal["M2M", "USER_FEDERATION"],
29-
callback_url: Optional[str] = None,
30+
callback_url: str | None = None,
3031
force_authentication: bool = False,
31-
token_poller: Optional[TokenPoller] = None,
32-
custom_state: Optional[str] = None,
33-
custom_parameters: Optional[Dict[str, str]] = None,
32+
token_poller: TokenPoller | None = None,
33+
custom_state: str | None = None,
34+
custom_parameters: dict[str, str] | None = None,
3435
) -> Callable:
3536
"""Decorator that fetches an OAuth2 access token before calling the decorated function.
3637
@@ -103,10 +104,10 @@ def sync_wrapper(*args: Any, **kwargs_func: Any) -> Any:
103104

104105
def requires_iam_access_token(
105106
*,
106-
audience: List[str],
107+
audience: list[str],
107108
signing_algorithm: str = "ES384",
108109
duration_seconds: int = 300,
109-
tags: Optional[List[Dict[str, str]]] = None,
110+
tags: list[dict[str, str]] | None = None,
110111
into: str = "access_token",
111112
) -> Callable:
112113
"""Decorator that fetches an AWS IAM JWT token before calling the decorated function.
@@ -268,7 +269,7 @@ def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
268269
return decorator
269270

270271

271-
def _get_oauth2_callback_url(user_provided_oauth2_callback_url: Optional[str]):
272+
def _get_oauth2_callback_url(user_provided_oauth2_callback_url: str | None):
272273
if user_provided_oauth2_callback_url:
273274
return user_provided_oauth2_callback_url
274275

@@ -301,7 +302,7 @@ async def _set_up_local_auth(client: IdentityClient) -> str:
301302
config = {}
302303
if config_path.exists():
303304
try:
304-
with open(config_path, "r", encoding="utf-8") as file:
305+
with open(config_path, encoding="utf-8") as file:
305306
config = json.load(file) or {}
306307
except Exception:
307308
print("Could not find existing workload identity and user id")

0 commit comments

Comments
 (0)