Skip to content

The agent engineering platform.

style(core): fix some ruff preview rules (#38656)

Christophe Bornet08c95c9f5b02
diff --git a/libs/core/langchain_core/language_models/_compat_bridge.py b/libs/core/langchain_core/language_models/_compat_bridge.py
index d05ffebab7..81f592f043 100644
--- a/libs/core/langchain_core/language_models/_compat_bridge.py
+++ b/libs/core/langchain_core/language_models/_compat_bridge.py
@@ -270,7 +270,7 @@ def _start_skeleton(block: CompatBlock) -> ContentBlock:
stripped: CompatBlock = {k: v for k, v in block.items() if k not in _HEAVY_FIELDS}
# Restore required-but-heavy fields with minimal placeholders so the
# start event still validates against the CDDL shape of the block type.
- if btype in ("tool_call", "server_tool_call"):
+ if btype in {"tool_call", "server_tool_call"}:
stripped["args"] = {}
elif btype == "non_standard":
stripped["value"] = {}
@@ -289,7 +289,7 @@ def _should_emit_delta(block: CompatBlock) -> bool:
return bool(block.get("text"))
if btype == "reasoning":
return bool(block.get("reasoning"))
- if btype in ("tool_call_chunk", "server_tool_call_chunk"):
+ if btype in {"tool_call_chunk", "server_tool_call_chunk"}:
return bool(
block.get("args") or block.get("id") or block.get("name"),
)
@@ -315,7 +315,7 @@ def _accumulate(state: CompatBlock | None, delta: CompatBlock) -> CompatBlock:
# on later deltas. Merging (not replacing) keeps earlier keys
# intact while picking up these late-arriving fields.
for key, value in delta.items():
- if key in ("type", "text") or value is None:
+ if key in {"type", "text"} or value is None:
continue
if key == "extras" and isinstance(value, dict):
state["extras"] = {**(state.get("extras") or {}), **value}
@@ -328,13 +328,13 @@ def _accumulate(state: CompatBlock | None, delta: CompatBlock) -> CompatBlock:
# as `extras.signature`; merging (not replacing) keeps earlier
# keys intact.
for key, value in delta.items():
- if key in ("type", "reasoning") or value is None:
+ if key in {"type", "reasoning"} or value is None:
continue
if key == "extras" and isinstance(value, dict):
state["extras"] = {**(state.get("extras") or {}), **value}
else:
state[key] = value
- elif btype in ("tool_call_chunk", "server_tool_call_chunk") and dtype == btype:
+ elif btype in {"tool_call_chunk", "server_tool_call_chunk"} and dtype == btype:
state["args"] = (state.get("args", "") or "") + (delta.get("args") or "")
if delta.get("id") is not None:
state["id"] = delta["id"]
@@ -343,7 +343,7 @@ def _accumulate(state: CompatBlock | None, delta: CompatBlock) -> CompatBlock:
elif btype == dtype and "data" in delta:
state["data"] = (state.get("data", "") or "") + (delta.get("data") or "")
for key, value in delta.items():
- if key in ("type", "data") or value is None:
+ if key in {"type", "data"} or value is None:
continue
if key == "extras" and isinstance(value, dict):
state["extras"] = {**(state.get("extras") or {}), **value}
@@ -432,7 +432,7 @@ def _finalize_block(block: CompatBlock) -> FinalizedContentBlock:
their terminal shape.
"""
btype = block.get("type")
- if btype in ("tool_call_chunk", "server_tool_call_chunk"):
+ if btype in {"tool_call_chunk", "server_tool_call_chunk"}:
# Carry provider-specific fields from the accumulated chunk onto
# the finalized block. Drop the chunk-only keys we rewrite
# explicitly. `index` is stripped on client-side
@@ -445,7 +445,7 @@ def _finalize_block(block: CompatBlock) -> FinalizedContentBlock:
client_tool_call = btype == "tool_call_chunk"
extras_drop = {"type", "id", "name", "args"}
if client_tool_call:
- extras_drop = extras_drop | {"index"}
+ extras_drop |= {"index"}
extras = {
k: v for k, v in block.items() if k not in extras_drop and v is not None
}
@@ -666,10 +666,10 @@ def chunks_to_events(
blocks[key] = (wire_idx, _accumulate(existing, block))
if _should_emit_delta(block):
wire_idx, current = blocks[key]
- is_block_delta = block.get("type") in (
+ is_block_delta = block.get("type") in {
"tool_call_chunk",
"server_tool_call_chunk",
- )
+ }
delta_source = current if is_block_delta else block
yield ContentBlockDeltaData(
event="content-block-delta",
@@ -746,10 +746,10 @@ async def achunks_to_events(
blocks[key] = (wire_idx, _accumulate(existing, block))
if _should_emit_delta(block):
wire_idx, current = blocks[key]
- is_block_delta = block.get("type") in (
+ is_block_delta = block.get("type") in {
"tool_call_chunk",
"server_tool_call_chunk",
- )
+ }
delta_source = current if is_block_delta else block
yield ContentBlockDeltaData(
event="content-block-delta",
diff --git a/libs/core/langchain_core/language_models/chat_model_stream.py b/libs/core/langchain_core/language_models/chat_model_stream.py
index a5e9a0a2af..045e9a0375 100644
--- a/libs/core/langchain_core/language_models/chat_model_stream.py
+++ b/libs/core/langchain_core/language_models/chat_model_stream.py
@@ -140,7 +140,7 @@ def _sweep_chunk_store(
extras = {
k: v
for k, v in chunk.items()
- if k not in ("type", "id", "name", "args") and v is not None
+ if k not in {"type", "id", "name", "args"} and v is not None
}
final_block = finalize_tool_call_chunk(
raw_args=chunk.get("args"),
@@ -864,7 +864,7 @@ class _ChatModelStreamBase:
if idx is not None and idx in self._server_tool_call_chunks:
del self._server_tool_call_chunks[idx]
finalized = itc
- elif btype in (
+ elif btype in {
"server_tool_call",
"server_tool_result",
"image",
@@ -872,7 +872,7 @@ class _ChatModelStreamBase:
"video",
"file",
"non_standard",
- ):
+ }:
if btype == "server_tool_call" and idx is not None:
self._server_tool_call_chunks.pop(idx, None)
finalized = cast("FinalizedContentBlock", block)
@@ -888,7 +888,7 @@ class _ChatModelStreamBase:
# `tool_call` / `invalid_tool_call` blocks are excluded: v1
# finalization drops `index` on them so further deltas
# cannot clobber already-parsed args, and v2 mirrors that.
- if btype not in ("tool_call", "invalid_tool_call"):
+ if btype not in {"tool_call", "invalid_tool_call"}:
finalized.setdefault("index", idx)
self._blocks[idx] = finalized
diff --git a/libs/core/langchain_core/runnables/base.py b/libs/core/langchain_core/runnables/base.py
index 2631319f28..c6a31a9a79 100644
--- a/libs/core/langchain_core/runnables/base.py
+++ b/libs/core/langchain_core/runnables/base.py
@@ -4276,8 +4276,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
for future in completed_futures:
(step_name, generator) = futures.pop(future)
try:
- chunk = AddableDict({step_name: future.result()})
- yield chunk
+ yield AddableDict({step_name: future.result()})
futures[executor.submit(next, generator)] = (
step_name,
generator,
@@ -4349,8 +4348,7 @@ class RunnableParallel(RunnableSerializable[Input, dict[str, Any]]):
for task in completed_tasks:
(step_name, generator) = tasks.pop(task)
try:
- chunk = AddableDict({step_name: task.result()})
- yield chunk
+ yield AddableDict({step_name: task.result()})
new_task = asyncio.create_task(get_next_chunk(generator))
tasks[new_task] = (step_name, generator)
except StopAsyncIteration:
diff --git a/libs/core/langchain_core/utils/_merge.py b/libs/core/langchain_core/utils/_merge.py
index d6e0cce4db..8ddc797f62 100644
--- a/libs/core/langchain_core/utils/_merge.py
+++ b/libs/core/langchain_core/utils/_merge.py
@@ -121,8 +121,8 @@ def merge_lists(left: list[Any] | None, *others: list[Any] | None) -> list[Any]
"index" in e_left
and e_left["index"] == e["index"] # index matches
and ( # IDs not inconsistent
- e_left.get("id") in (None, "")
- or e.get("id") in (None, "")
+ e_left.get("id") in {None, ""}
+ or e.get("id") in {None, ""}
or e_left.get("id") == e.get("id")
)
)
diff --git a/libs/core/tests/unit_tests/language_models/test_chat_model_streamer.py b/libs/core/tests/unit_tests/language_models/test_chat_model_streamer.py
index 6370f4a7c4..f46593ca91 100644
--- a/libs/core/tests/unit_tests/language_models/test_chat_model_streamer.py
+++ b/libs/core/tests/unit_tests/language_models/test_chat_model_streamer.py
@@ -364,8 +364,8 @@ class TestCancellation:
"""
model = FakeListChatModel(responses=["abcdefghij"], sleep=0.05)
stream = await model.astream_events("test", version="v3")
- aiter_ = stream.text.__aiter__()
- await aiter_.__anext__()
+ aiter_ = aiter(stream.text)
+ await anext(aiter_)
task = stream._producer_task
assert task is not None
diff --git a/libs/core/tests/unit_tests/language_models/test_chat_model_v3_stream.py b/libs/core/tests/unit_tests/language_models/test_chat_model_v3_stream.py
index ba30e2c4db..9fccf8b26b 100644
--- a/libs/core/tests/unit_tests/language_models/test_chat_model_v3_stream.py
+++ b/libs/core/tests/unit_tests/language_models/test_chat_model_v3_stream.py
@@ -854,8 +854,8 @@ class TestAsyncStreamAclose:
stream = await model.astream_events("test", version="v3")
# Pull the first delta so the producer enters the gated section.
- aiter_ = stream.text.__aiter__()
- first = await aiter_.__anext__()
+ aiter_ = aiter(stream.text)
+ first = await anext(aiter_)
assert first == "first"
assert stream._producer_task is not None
assert not stream._producer_task.done()
@@ -870,8 +870,8 @@ class TestAsyncStreamAclose:
gate = asyncio.Event()
model = _GatedStreamModel(gate=gate)
stream = await model.astream_events("test", version="v3")
- aiter_ = stream.text.__aiter__()
- await aiter_.__anext__()
+ aiter_ = aiter(stream.text)
+ await anext(aiter_)
await stream.aclose()
await stream.aclose() # second call must not raise
@@ -884,8 +884,8 @@ class TestAsyncStreamAclose:
async with stream as s:
assert s is stream
- aiter_ = stream.text.__aiter__()
- await aiter_.__anext__()
+ aiter_ = aiter(stream.text)
+ await anext(aiter_)
assert stream._producer_task is not None
assert stream._producer_task.done()
@@ -907,8 +907,8 @@ class TestAsyncStreamAclose:
# Prime the producer so it enters `_astream`'s forever-blocking
# await.
- aiter_ = stream.text.__aiter__()
- await aiter_.__anext__()
+ aiter_ = aiter(stream.text)
+ await anext(aiter_)
closer_returned_normally = False
@@ -1015,8 +1015,8 @@ class TestAsyncStreamAclose:
"test", config={"callbacks": [handler]}, version="v3"
)
- aiter_ = stream.text.__aiter__()
- await aiter_.__anext__()
+ aiter_ = aiter(stream.text)
+ await anext(aiter_)
await stream.aclose()
diff --git a/libs/core/tests/unit_tests/language_models/test_compat_bridge.py b/libs/core/tests/unit_tests/language_models/test_compat_bridge.py
index 3fd5f0c6f7..0030e2c381 100644
--- a/libs/core/tests/unit_tests/language_models/test_compat_bridge.py
+++ b/libs/core/tests/unit_tests/language_models/test_compat_bridge.py
@@ -252,7 +252,7 @@ def test_chunks_to_events_block_transitions_keep_stable_indices() -> None:
lifecycle = [
(e["event"], e["index"])
for e in events_any
- if e["event"] in ("content-block-start", "content-block-finish")
+ if e["event"] in {"content-block-start", "content-block-finish"}
]
assert lifecycle == [
("content-block-start", 0),
diff --git a/libs/core/tests/unit_tests/language_models/test_v1_parity.py b/libs/core/tests/unit_tests/language_models/test_v1_parity.py
index 36b0141e23..371d29b7e1 100644
--- a/libs/core/tests/unit_tests/language_models/test_v1_parity.py
+++ b/libs/core/tests/unit_tests/language_models/test_v1_parity.py
@@ -46,7 +46,7 @@ class _ScriptedChunkModel(BaseChatModel):
def _merged(self) -> AIMessageChunk:
merged = self.scripted_chunks[0]
for c in self.scripted_chunks[1:]:
- merged = merged + c
+ merged += c
return merged
@override
@@ -117,7 +117,7 @@ def _collect_v1_message(model: BaseChatModel, input_text: str) -> AIMessage:
raise RuntimeError(msg)
merged = chunks[0]
for c in chunks[1:]:
- merged = merged + c
+ merged += c
return AIMessage(
content=merged.content,
id=merged.id,
diff --git a/libs/core/tests/unit_tests/prompts/test_structured.py b/libs/core/tests/unit_tests/prompts/test_structured.py
index c5310b1557..b69a7ba9e0 100644
--- a/libs/core/tests/unit_tests/prompts/test_structured.py
+++ b/libs/core/tests/unit_tests/prompts/test_structured.py
@@ -21,7 +21,7 @@ def _fake_runnable(
if isclass(schema) and issubclass(schema, BaseModel):
return schema(name="yo", value=value)
params = cast("dict[str, Any]", schema)["parameters"]
- return {k: 1 if k != "value" else value for k, v in params.items()}
+ return {k: 1 if k != "value" else value for k in params}
class FakeStructuredChatModel(FakeListChatModel):
diff --git a/libs/core/tests/unit_tests/test_tools.py b/libs/core/tests/unit_tests/test_tools.py
index 2c0a94ff8c..9a881e3cf4 100644
--- a/libs/core/tests/unit_tests/test_tools.py
+++ b/libs/core/tests/unit_tests/test_tools.py
@@ -853,7 +853,12 @@ def test_exception_handling_callable_message_content_blocks() -> None:
tool_ = _FakeExceptionTool(handle_tool_error=handling)
actual = tool_.invoke(
- {"type": "tool_call", "args": {}, "name": "exception", "id": "call_1"}
+ {
+ "type": "tool_call",
+ "args": {},
+ "name": "exception",
+ "id": "call_1",
+ }
)
assert isinstance(actual, ToolMessage)
@@ -870,7 +875,12 @@ def test_exception_handling_callable_message_content_blocks_sequence() -> None:
tool_ = _FakeExceptionTool(handle_tool_error=handling)
actual = tool_.invoke(
- {"type": "tool_call", "args": {}, "name": "exception", "id": "call_1"}
+ {
+ "type": "tool_call",
+ "args": {},
+ "name": "exception",
+ "id": "call_1",
+ }
)
assert isinstance(actual, ToolMessage)
@@ -887,7 +897,12 @@ def test_exception_handling_callable_invalid_blocks_stringified() -> None:
tool_ = _FakeExceptionTool(handle_tool_error=handling)
actual = tool_.invoke(
- {"type": "tool_call", "args": {}, "name": "exception", "id": "call_1"}
+ {
+ "type": "tool_call",
+ "args": {},
+ "name": "exception",
+ "id": "call_1",
+ }
)
assert isinstance(actual, ToolMessage)
@@ -935,7 +950,12 @@ async def test_async_exception_handling_callable_message_content_blocks() -> Non
tool_ = _FakeExceptionTool(handle_tool_error=handling)
actual = await tool_.ainvoke(
- {"type": "tool_call", "args": {}, "name": "exception", "id": "call_1"}
+ {
+ "type": "tool_call",
+ "args": {},
+ "name": "exception",
+ "id": "call_1",
+ }
)
assert isinstance(actual, ToolMessage)
@@ -954,7 +974,12 @@ async def test_async_exception_handling_callable_message_content_blocks_sequence
tool_ = _FakeExceptionTool(handle_tool_error=handling)
actual = await tool_.ainvoke(
- {"type": "tool_call", "args": {}, "name": "exception", "id": "call_1"}
+ {
+ "type": "tool_call",
+ "args": {},
+ "name": "exception",
+ "id": "call_1",
+ }
)
assert isinstance(actual, ToolMessage)
@@ -3928,7 +3953,12 @@ def test_tool_invoke_returns_list_of_mixin() -> None:
]
result = multi.invoke(
- {"type": "tool_call", "args": {"x": 3}, "name": "multi", "id": "outer"}
+ {
+ "type": "tool_call",
+ "args": {"x": 3},
+ "name": "multi",
+ "id": "outer",
+ }
)
assert isinstance(result, list)
assert len(result) == 3