Skip to content

The agent engineering platform.

core: Bump ruff version to 0.11 (#30519)

Christophe Bornete181d4321411
diff --git a/libs/core/langchain_core/_api/beta_decorator.py b/libs/core/langchain_core/_api/beta_decorator.py
index b141526332..f527cc116a 100644
--- a/libs/core/langchain_core/_api/beta_decorator.py
+++ b/libs/core/langchain_core/_api/beta_decorator.py
@@ -143,7 +143,7 @@ def beta(
obj.__init__ = functools.wraps(obj.__init__)( # type: ignore[misc]
warn_if_direct_instance
)
- return cast(T, obj)
+ return cast("T", obj)
elif isinstance(obj, property):
# note(erick): this block doesn't seem to be used?
@@ -217,7 +217,7 @@ def beta(
"""
wrapper = functools.wraps(wrapped)(wrapper)
wrapper.__doc__ = new_doc
- return cast(T, wrapper)
+ return cast("T", wrapper)
old_doc = inspect.cleandoc(old_doc or "").strip("\n") or ""
components = [message, addendum]
@@ -228,7 +228,7 @@ def beta(
finalized = finalize(awarning_emitting_wrapper, new_doc)
else:
finalized = finalize(warning_emitting_wrapper, new_doc)
- return cast(T, finalized)
+ return cast("T", finalized)
return beta
diff --git a/libs/core/langchain_core/_api/deprecation.py b/libs/core/langchain_core/_api/deprecation.py
index ad3d806b0d..ac1f1e0616 100644
--- a/libs/core/langchain_core/_api/deprecation.py
+++ b/libs/core/langchain_core/_api/deprecation.py
@@ -216,7 +216,7 @@ def deprecated(
obj.__init__ = functools.wraps(obj.__init__)( # type: ignore[misc]
warn_if_direct_instance
)
- return cast(T, obj)
+ return cast("T", obj)
elif isinstance(obj, FieldInfoV1):
wrapped = None
@@ -229,7 +229,7 @@ def deprecated(
def finalize(wrapper: Callable[..., Any], new_doc: str) -> T:
return cast(
- T,
+ "T",
FieldInfoV1(
default=obj.default,
default_factory=obj.default_factory,
@@ -250,7 +250,7 @@ def deprecated(
def finalize(wrapper: Callable[..., Any], new_doc: str) -> T:
return cast(
- T,
+ "T",
FieldInfoV2(
default=obj.default,
default_factory=obj.default_factory,
@@ -264,7 +264,7 @@ def deprecated(
if not _obj_type:
_obj_type = "attribute"
wrapped = None
- _name = _name or cast(Union[type, Callable], obj.fget).__qualname__
+ _name = _name or cast("Union[type, Callable]", obj.fget).__qualname__
old_doc = obj.__doc__
class _DeprecatedProperty(property):
@@ -311,14 +311,14 @@ def deprecated(
def finalize(wrapper: Callable[..., Any], new_doc: str) -> T:
"""Finalize the property."""
return cast(
- T,
+ "T",
_DeprecatedProperty(
fget=obj.fget, fset=obj.fset, fdel=obj.fdel, doc=new_doc
),
)
else:
- _name = _name or cast(Union[type, Callable], obj).__qualname__
+ _name = _name or cast("Union[type, Callable]", obj).__qualname__
if not _obj_type:
# edge case: when a function is within another function
# within a test, this will call it a "method" not a "function"
@@ -338,7 +338,7 @@ def deprecated(
"""
wrapper = functools.wraps(wrapped)(wrapper)
wrapper.__doc__ = new_doc
- return cast(T, wrapper)
+ return cast("T", wrapper)
old_doc = inspect.cleandoc(old_doc or "").strip("\n")
@@ -391,7 +391,7 @@ def deprecated(
finalized = finalize(awarning_emitting_wrapper, new_doc)
else:
finalized = finalize(warning_emitting_wrapper, new_doc)
- return cast(T, finalized)
+ return cast("T", finalized)
return deprecate
diff --git a/libs/core/langchain_core/callbacks/file.py b/libs/core/langchain_core/callbacks/file.py
index b68b3ba22e..3ee4e18e5d 100644
--- a/libs/core/langchain_core/callbacks/file.py
+++ b/libs/core/langchain_core/callbacks/file.py
@@ -31,7 +31,7 @@ class FileCallbackHandler(BaseCallbackHandler):
mode: The mode to open the file in. Defaults to "a".
color: The color to use for the text. Defaults to None.
"""
- self.file = cast(TextIO, Path(filename).open(mode, encoding="utf-8")) # noqa: SIM115
+ self.file = cast("TextIO", Path(filename).open(mode, encoding="utf-8")) # noqa: SIM115
self.color = color
def __del__(self) -> None:
diff --git a/libs/core/langchain_core/callbacks/manager.py b/libs/core/langchain_core/callbacks/manager.py
index 689003de3e..62aa8f73d3 100644
--- a/libs/core/langchain_core/callbacks/manager.py
+++ b/libs/core/langchain_core/callbacks/manager.py
@@ -232,7 +232,7 @@ def shielded(func: Func) -> Func:
async def wrapped(*args: Any, **kwargs: Any) -> Any:
return await asyncio.shield(func(*args, **kwargs))
- return cast(Func, wrapped)
+ return cast("Func", wrapped)
def handle_event(
@@ -308,7 +308,7 @@ def handle_event(
# The solution is to create a new loop in a new thread.
with ThreadPoolExecutor(1) as executor:
executor.submit(
- cast(Callable, copy_context().run), _run_coros, coros
+ cast("Callable", copy_context().run), _run_coros, coros
).result()
else:
_run_coros(coros)
@@ -362,7 +362,7 @@ async def _ahandle_event_for_handler(
await asyncio.get_event_loop().run_in_executor(
None,
cast(
- Callable,
+ "Callable",
functools.partial(
copy_context().run, event, *args, **kwargs
),
@@ -2395,7 +2395,7 @@ def _configure(
run_tree.trace_id,
run_tree.dotted_order,
)
- handler.run_map[str(run_tree.id)] = cast(Run, run_tree)
+ handler.run_map[str(run_tree.id)] = cast("Run", run_tree)
for var, inheritable, handler_class, env_var in _configure_hooks:
create_one = (
env_var is not None
@@ -2403,7 +2403,9 @@ def _configure(
and handler_class is not None
)
if var.get() is not None or create_one:
- var_handler = var.get() or cast(type[BaseCallbackHandler], handler_class)()
+ var_handler = (
+ var.get() or cast("type[BaseCallbackHandler]", handler_class)()
+ )
if handler_class is None:
if not any(
handler is var_handler # direct pointer comparison
diff --git a/libs/core/langchain_core/documents/base.py b/libs/core/langchain_core/documents/base.py
index 8d39daaa0c..d1710499ed 100644
--- a/libs/core/langchain_core/documents/base.py
+++ b/libs/core/langchain_core/documents/base.py
@@ -136,7 +136,7 @@ class Blob(BaseMedia):
case that value will be used instead.
"""
if self.metadata and "source" in self.metadata:
- return cast(Optional[str], self.metadata["source"])
+ return cast("Optional[str]", self.metadata["source"])
return str(self.path) if self.path else None
@model_validator(mode="before")
diff --git a/libs/core/langchain_core/indexing/api.py b/libs/core/langchain_core/indexing/api.py
index 4dd21de4f4..80a9fb5dd7 100644
--- a/libs/core/langchain_core/indexing/api.py
+++ b/libs/core/langchain_core/indexing/api.py
@@ -395,7 +395,7 @@ def index(
if cleanup == "scoped_full":
scoped_full_cleanup_source_ids.add(source_id)
# source ids cannot be None after for loop above.
- source_ids = cast(Sequence[str], source_ids) # type: ignore[assignment]
+ source_ids = cast("Sequence[str]", source_ids) # type: ignore[assignment]
exists_batch = record_manager.exists([doc.uid for doc in hashed_docs])
@@ -461,7 +461,7 @@ def index(
)
raise AssertionError(msg)
- _source_ids = cast(Sequence[str], source_ids)
+ _source_ids = cast("Sequence[str]", source_ids)
uids_to_delete = record_manager.list_keys(
group_ids=_source_ids, before=index_start_dt
@@ -710,7 +710,7 @@ async def aindex(
if cleanup == "scoped_full":
scoped_full_cleanup_source_ids.add(source_id)
# source ids cannot be None after for loop above.
- source_ids = cast(Sequence[str], source_ids)
+ source_ids = cast("Sequence[str]", source_ids)
exists_batch = await record_manager.aexists([doc.uid for doc in hashed_docs])
@@ -776,7 +776,7 @@ async def aindex(
)
raise AssertionError(msg)
- _source_ids = cast(Sequence[str], source_ids)
+ _source_ids = cast("Sequence[str]", source_ids)
uids_to_delete = await record_manager.alist_keys(
group_ids=_source_ids, before=index_start_dt
diff --git a/libs/core/langchain_core/indexing/in_memory.py b/libs/core/langchain_core/indexing/in_memory.py
index cf12d0012f..e166f5b158 100644
--- a/libs/core/langchain_core/indexing/in_memory.py
+++ b/libs/core/langchain_core/indexing/in_memory.py
@@ -41,7 +41,7 @@ class InMemoryDocumentIndex(DocumentIndex):
id_ = item.id
self.store[id_] = item_
- ok_ids.append(cast(str, item_.id))
+ ok_ids.append(cast("str", item_.id))
return UpsertResponse(succeeded=ok_ids, failed=[])
diff --git a/libs/core/langchain_core/language_models/chat_models.py b/libs/core/langchain_core/language_models/chat_models.py
index db9a809819..bde6052992 100644
--- a/libs/core/langchain_core/language_models/chat_models.py
+++ b/libs/core/langchain_core/language_models/chat_models.py
@@ -303,7 +303,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
) -> BaseMessage:
config = ensure_config(config)
return cast(
- ChatGeneration,
+ "ChatGeneration",
self.generate_prompt(
[self._convert_input(input)],
stop=stop,
@@ -335,7 +335,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
run_id=config.pop("run_id", None),
**kwargs,
)
- return cast(ChatGeneration, llm_result.generations[0][0]).message
+ return cast("ChatGeneration", llm_result.generations[0][0]).message
def _should_stream(
self,
@@ -383,7 +383,8 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
if not self._should_stream(async_api=False, **{**kwargs, "stream": True}):
# model doesn't implement streaming, so use default implementation
yield cast(
- BaseMessageChunk, self.invoke(input, config=config, stop=stop, **kwargs)
+ "BaseMessageChunk",
+ self.invoke(input, config=config, stop=stop, **kwargs),
)
else:
config = ensure_config(config)
@@ -430,7 +431,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
chunk.message.id = f"run-{run_manager.run_id}"
chunk.message.response_metadata = _gen_info_and_msg_metadata(chunk)
run_manager.on_llm_new_token(
- cast(str, chunk.message.content), chunk=chunk
+ cast("str", chunk.message.content), chunk=chunk
)
yield chunk.message
if generation is None:
@@ -464,7 +465,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
if not self._should_stream(async_api=True, **{**kwargs, "stream": True}):
# No async or sync stream is implemented, so fall back to ainvoke
yield cast(
- BaseMessageChunk,
+ "BaseMessageChunk",
await self.ainvoke(input, config=config, stop=stop, **kwargs),
)
return
@@ -518,7 +519,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
chunk.message.id = f"run-{run_manager.run_id}"
chunk.message.response_metadata = _gen_info_and_msg_metadata(chunk)
await run_manager.on_llm_new_token(
- cast(str, chunk.message.content), chunk=chunk
+ cast("str", chunk.message.content), chunk=chunk
)
yield chunk.message
if generation is None:
@@ -899,7 +900,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
if chunk.message.id is None:
chunk.message.id = f"run-{run_manager.run_id}"
run_manager.on_llm_new_token(
- cast(str, chunk.message.content), chunk=chunk
+ cast("str", chunk.message.content), chunk=chunk
)
chunks.append(chunk)
result = generate_from_stream(iter(chunks))
@@ -972,7 +973,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
if chunk.message.id is None:
chunk.message.id = f"run-{run_manager.run_id}"
await run_manager.on_llm_new_token(
- cast(str, chunk.message.content), chunk=chunk
+ cast("str", chunk.message.content), chunk=chunk
)
chunks.append(chunk)
result = generate_from_stream(iter(chunks))
@@ -1307,7 +1308,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
)
if isinstance(schema, type) and is_basemodel_subclass(schema):
output_parser: OutputParserLike = PydanticToolsParser(
- tools=[cast(TypeBaseModel, schema)], first_tool_only=True
+ tools=[cast("TypeBaseModel", schema)], first_tool_only=True
)
else:
key_name = convert_to_openai_tool(schema)["function"]["name"]
diff --git a/libs/core/langchain_core/language_models/fake_chat_models.py b/libs/core/langchain_core/language_models/fake_chat_models.py
index 9bd62f1267..5a6a659046 100644
--- a/libs/core/langchain_core/language_models/fake_chat_models.py
+++ b/libs/core/langchain_core/language_models/fake_chat_models.py
@@ -262,7 +262,7 @@ class GenericFakeChatModel(BaseChatModel):
msg = "Expected content to be a string."
raise ValueError(msg)
- content_chunks = cast(list[str], re.split(r"(\s)", content))
+ content_chunks = cast("list[str]", re.split(r"(\s)", content))
for token in content_chunks:
chunk = ChatGenerationChunk(
@@ -280,7 +280,7 @@ class GenericFakeChatModel(BaseChatModel):
for fkey, fvalue in value.items():
if isinstance(fvalue, str):
# Break function call by `,`
- fvalue_chunks = cast(list[str], re.split(r"(,)", fvalue))
+ fvalue_chunks = cast("list[str]", re.split(r"(,)", fvalue))
for fvalue_chunk in fvalue_chunks:
chunk = ChatGenerationChunk(
message=AIMessageChunk(
diff --git a/libs/core/langchain_core/language_models/llms.py b/libs/core/langchain_core/language_models/llms.py
index 3c5ed7337f..5049842fd4 100644
--- a/libs/core/langchain_core/language_models/llms.py
+++ b/libs/core/langchain_core/language_models/llms.py
@@ -449,7 +449,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
return [g[0].text for g in llm_result.generations]
except Exception as e:
if return_exceptions:
- return cast(list[str], [e for _ in inputs])
+ return cast("list[str]", [e for _ in inputs])
else:
raise
else:
@@ -495,7 +495,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
return [g[0].text for g in llm_result.generations]
except Exception as e:
if return_exceptions:
- return cast(list[str], [e for _ in inputs])
+ return cast("list[str]", [e for _ in inputs])
else:
raise
else:
@@ -901,13 +901,15 @@ class BaseLLM(BaseLanguageModel[str], ABC):
):
msg = "run_name must be a list of the same length as prompts"
raise ValueError(msg)
- callbacks = cast(list[Callbacks], callbacks)
- tags_list = cast(list[Optional[list[str]]], tags or ([None] * len(prompts)))
+ callbacks = cast("list[Callbacks]", callbacks)
+ tags_list = cast(
+ "list[Optional[list[str]]]", tags or ([None] * len(prompts))
+ )
metadata_list = cast(
- list[Optional[dict[str, Any]]], metadata or ([{}] * len(prompts))
+ "list[Optional[dict[str, Any]]]", metadata or ([{}] * len(prompts))
)
run_name_list = run_name or cast(
- list[Optional[str]], ([None] * len(prompts))
+ "list[Optional[str]]", ([None] * len(prompts))
)
callback_managers = [
CallbackManager.configure(
@@ -925,16 +927,16 @@ class BaseLLM(BaseLanguageModel[str], ABC):
# We've received a single callbacks arg to apply to all inputs
callback_managers = [
CallbackManager.configure(
- cast(Callbacks, callbacks),
+ cast("Callbacks", callbacks),
self.callbacks,
self.verbose,
- cast(list[str], tags),
+ cast("list[str]", tags),
self.tags,
- cast(dict[str, Any], metadata),
+ cast("dict[str, Any]", metadata),
self.metadata,
)
] * len(prompts)
- run_name_list = [cast(Optional[str], run_name)] * len(prompts)
+ run_name_list = [cast("Optional[str]", run_name)] * len(prompts)
run_ids_list = self._get_run_ids_list(run_id, prompts)
params = self.dict()
params["stop"] = stop
@@ -1143,13 +1145,15 @@ class BaseLLM(BaseLanguageModel[str], ABC):
):
msg = "run_name must be a list of the same length as prompts"
raise ValueError(msg)
- callbacks = cast(list[Callbacks], callbacks)
- tags_list = cast(list[Optional[list[str]]], tags or ([None] * len(prompts)))
+ callbacks = cast("list[Callbacks]", callbacks)
+ tags_list = cast(
+ "list[Optional[list[str]]]", tags or ([None] * len(prompts))
+ )
metadata_list = cast(
- list[Optional[dict[str, Any]]], metadata or ([{}] * len(prompts))
+ "list[Optional[dict[str, Any]]]", metadata or ([{}] * len(prompts))
)
run_name_list = run_name or cast(
- list[Optional[str]], ([None] * len(prompts))
+ "list[Optional[str]]", ([None] * len(prompts))
)
callback_managers = [
AsyncCallbackManager.configure(
@@ -1167,16 +1171,16 @@ class BaseLLM(BaseLanguageModel[str], ABC):
# We've received a single callbacks arg to apply to all inputs
callback_managers = [
AsyncCallbackManager.configure(
- cast(Callbacks, callbacks),
+ cast("Callbacks", callbacks),
self.callbacks,
self.verbose,
- cast(list[str], tags),
+ cast("list[str]", tags),
self.tags,
- cast(dict[str, Any], metadata),
+ cast("dict[str, Any]", metadata),
self.metadata,
)
] * len(prompts)
- run_name_list = [cast(Optional[str], run_name)] * len(prompts)
+ run_name_list = [cast("Optional[str]", run_name)] * len(prompts)
run_ids_list = self._get_run_ids_list(run_id, prompts)
params = self.dict()
params["stop"] = stop
diff --git a/libs/core/langchain_core/load/serializable.py b/libs/core/langchain_core/load/serializable.py
index 7655438be9..d5751c9677 100644
--- a/libs/core/langchain_core/load/serializable.py
+++ b/libs/core/langchain_core/load/serializable.py
@@ -237,7 +237,7 @@ class Serializable(BaseModel, ABC):
raise ValueError(msg)
# Get a reference to self bound to each class in the MRO
- this = cast(Serializable, self if cls is None else super(cls, self))
+ this = cast("Serializable", self if cls is None else super(cls, self))
secrets.update(this.lc_secrets)
# Now also add the aliases for the secrets
diff --git a/libs/core/langchain_core/messages/ai.py b/libs/core/langchain_core/messages/ai.py
index 1926706047..38ff432afd 100644
--- a/libs/core/langchain_core/messages/ai.py
+++ b/libs/core/langchain_core/messages/ai.py
@@ -500,14 +500,14 @@ def add_usage(
if not (left or right):
return UsageMetadata(input_tokens=0, output_tokens=0, total_tokens=0)
if not (left and right):
- return cast(UsageMetadata, left or right)
+ return cast("UsageMetadata", left or right)
return UsageMetadata(
**cast(
- UsageMetadata,
+ "UsageMetadata",
_dict_int_op(
- cast(dict, left),
- cast(dict, right),
+ cast("dict", left),
+ cast("dict", right),
operator.add,
),
)
@@ -557,14 +557,14 @@ def subtract_usage(
if not (left or right):
return UsageMetadata(input_tokens=0, output_tokens=0, total_tokens=0)
if not (left and right):
- return cast(UsageMetadata, left or right)
+ return cast("UsageMetadata", left or right)
return UsageMetadata(
**cast(
- UsageMetadata,
+ "UsageMetadata",
_dict_int_op(
- cast(dict, left),
- cast(dict, right),
+ cast("dict", left),
+ cast("dict", right),
(lambda le, ri: max(le - ri, 0)),
),
)
diff --git a/libs/core/langchain_core/messages/base.py b/libs/core/langchain_core/messages/base.py
index 25e37d5174..423687426d 100644
--- a/libs/core/langchain_core/messages/base.py
+++ b/libs/core/langchain_core/messages/base.py
@@ -160,13 +160,13 @@ def merge_content(
if isinstance(merged, str):
# If the next chunk is also a string, then merge them naively
if isinstance(content, str):
- merged = cast(str, merged) + content
+ merged = cast("str", merged) + content
# If the next chunk is a list, add the current to the start of the list
else:
merged = [merged] + content # type: ignore
elif isinstance(content, list):
# If both are lists
- merged = merge_lists(cast(list, merged), content) # type: ignore
+ merged = merge_lists(cast("list", merged), content) # type: ignore
# If the first content is a list, and the second content is a string
else:
# If the last element of the first content is a string
diff --git a/libs/core/langchain_core/messages/utils.py b/libs/core/langchain_core/messages/utils.py
index 5fc86222b2..ce645f0ee6 100644
--- a/libs/core/langchain_core/messages/utils.py
+++ b/libs/core/langchain_core/messages/utils.py
@@ -908,7 +908,7 @@ def trim_messages(
try:
from langchain_text_splitters import TextSplitter
except ImportError:
- text_splitter_fn: Optional[Callable] = cast(Optional[Callable], text_splitter)
+ text_splitter_fn: Optional[Callable] = cast("Optional[Callable]", text_splitter)
else:
if isinstance(text_splitter, TextSplitter):
text_splitter_fn = text_splitter.split_text
@@ -1148,7 +1148,7 @@ def convert_to_openai_messages(
raise ValueError(err)
if not any(
tool_call["id"] == block["id"]
- for tool_call in cast(AIMessage, message).tool_calls
+ for tool_call in cast("AIMessage", message).tool_calls
):
oai_msg["tool_calls"] = oai_msg.get("tool_calls", [])
oai_msg["tool_calls"].append(
diff --git a/libs/core/langchain_core/prompt_values.py b/libs/core/langchain_core/prompt_values.py
index c3092d9245..220550de8e 100644
--- a/libs/core/langchain_core/prompt_values.py
+++ b/libs/core/langchain_core/prompt_values.py
@@ -124,7 +124,7 @@ class ImagePromptValue(PromptValue):
def to_messages(self) -> list[BaseMessage]:
"""Return prompt (image URL) as messages."""
- return [HumanMessage(content=[cast(dict, self.image_url)])]
+ return [HumanMessage(content=[cast("dict", self.image_url)])]
class ChatPromptValueConcrete(ChatPromptValue):
diff --git a/libs/core/langchain_core/prompts/chat.py b/libs/core/langchain_core/prompts/chat.py
index 288e71849f..23daa02716 100644
--- a/libs/core/langchain_core/prompts/chat.py
+++ b/libs/core/langchain_core/prompts/chat.py
@@ -530,14 +530,14 @@ class _StringImageMessagePromptTemplate(BaseMessagePromptTemplate):
if isinstance(tmpl, str):
text: str = tmpl
else:
- text = cast(_TextTemplateParam, tmpl)["text"] # type: ignore[assignment]
+ text = cast("_TextTemplateParam", tmpl)["text"] # type: ignore[assignment]
prompt.append(
PromptTemplate.from_template(
text, template_format=template_format
)
)
elif isinstance(tmpl, dict) and "image_url" in tmpl:
- img_template = cast(_ImageTemplateParam, tmpl)["image_url"]
+ img_template = cast("_ImageTemplateParam", tmpl)["image_url"]
input_variables = []
if isinstance(img_template, str):
vars = get_template_variables(img_template, template_format)
@@ -1024,7 +1024,7 @@ class ChatPromptTemplate(BaseChatPromptTemplate):
"partial_variables": partial_vars,
**kwargs,
}
- cast(type[ChatPromptTemplate], super()).__init__(messages=_messages, **kwargs)
+ cast("type[ChatPromptTemplate]", super()).__init__(messages=_messages, **kwargs)
@classmethod
def get_lc_namespace(cls) -> list[str]:
@@ -1382,11 +1382,11 @@ def _create_template_from_message_type(
)
elif message_type in ("ai", "assistant"):
message = AIMessagePromptTemplate.from_template(
- cast(str, template), template_format=template_format
+ cast("str", template), template_format=template_format
)
elif message_type == "system":
message = SystemMessagePromptTemplate.from_template(
- cast(str, template), template_format=template_format
+ cast("str", template), template_format=template_format
)
elif message_type == "placeholder":
if isinstance(template, str):
@@ -1484,7 +1484,7 @@ def _convert_to_message(
else:
_message = message_type_str(
prompt=PromptTemplate.from_template(
- cast(str, template), template_format=template_format
+ cast("str", template), template_format=template_format
)
)
else:
diff --git a/libs/core/langchain_core/runnables/base.py b/libs/core/langchain_core/runnables/base.py
index 4fbb1f9620..12c545f4b7 100644
--- a/libs/core/langchain_core/runnables/base.py
+++ b/libs/core/langchain_core/runnables/base.py
@@ -782,10 +782,10 @@ class Runnable(Generic[Input, Output], ABC):
# If there's only one input, don't bother with the executor
if len(inputs) == 1:
- return cast(list[Output], [invoke(inputs[0], configs[0])])
+ return cast("list[Output]", [invoke(inputs[0], configs[0])])
with get_executor_for_config(configs[0]) as executor:
- return cast(list[Output], list(executor.map(invoke, inputs, configs)))
+ return cast("list[Output]", list(executor.map(invoke, inputs, configs)))
@overload
def batch_as_completed(
@@ -1532,7 +1532,7 @@ class Runnable(Generic[Input, Output], ABC):
return RunnableBinding(
bound=self,
config=cast(
- RunnableConfig,
+ "RunnableConfig",
{**(config or {}), **kwargs},
), # type: ignore[misc]
kwargs={},
@@ -1921,7 +1921,7 @@ class Runnable(Generic[Input, Output], ABC):
child_config = patch_config(config, callbacks=run_manager.get_child())
with set_config_context(child_config) as context:
output = cast(
- Output,
+ "Output",
context.run(
call_func_with_variable_args, # type: ignore[arg-type]
func, # type: ignore[arg-type]
@@ -2036,7 +2036,7 @@ class Runnable(Generic[Input, Output], ABC):
for run_manager in run_managers:
run_manager.on_chain_error(e)
if return_exceptions:
- return cast(list[Output], [e for _ in input])
+ return cast("list[Output]", [e for _ in input])
else:
raise
else:
@@ -2048,7 +2048,7 @@ class Runnable(Generic[Input, Output], ABC):
else:
run_manager.on_chain_end(out)
if return_exceptions or first_exception is None:
- return cast(list[Output], output)
+ return cast("list[Output]", output)
else:
raise first_exception
@@ -2112,7 +2112,7 @@ class Runnable(Generic[Input, Output], ABC):
*(run_manager.on_chain_error(e) for run_manager in run_managers)
)
if return_exceptions:
- return cast(list[Output], [e for _ in input])
+ return cast("list[Output]", [e for _ in input])
else:
raise
else:
@@ -2126,7 +2126,7 @@ class Runnable(Generic[Input, Output], ABC):
coros.append(run_manager.on_chain_end(out))
await asyncio.gather(*coros)
if return_exceptions or first_exception is None:
- return cast(list[Output], output)
+ return cast("list[Output]", output)
else:
raise first_exception
@@ -2183,7 +2183,7 @@ class Runnable(Generic[Input, Output], ABC):
iterator = context.run(transformer, input_for_transform, **kwargs) # type: ignore[arg-type]
if stream_handler := next(
(
- cast(_StreamingCallbackHandler, h)
+ cast("_StreamingCallbackHandler", h)
for h in run_manager.handlers
# instance check OK here, it's a mixin
if isinstance(h, _StreamingCallbackHandler) # type: ignore[misc]
@@ -2286,7 +2286,7 @@ class Runnable(Generic[Input, Output], ABC):
if stream_handler := next(
(
- cast(_StreamingCallbackHandler, h)
+ cast("_StreamingCallbackHandler", h)
for h in run_manager.handlers
# instance check OK here, it's a mixin
if isinstance(h, _StreamingCallbackHandler) # type: ignore[misc]
@@ -2307,7 +2307,7 @@ class Runnable(Generic[Input, Output], ABC):
context=context,
)
else:
- chunk = cast(Output, await py_anext(iterator))
+ chunk = cast("Output", await py_anext(iterator))
yield chunk
if final_output_supported:
if final_output is None:
@@ -3029,7 +3029,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
raise
else:
run_manager.on_chain_end(input)
- return cast(Output, input)
+ return cast("Output", input)
async def ainvoke(
self,
@@ -3072,7 +3072,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
raise
else:
await run_manager.on_chain_end(input)
- return cast(Output, input)
+ return cast("Output", input)
def batch(
self,
@@ -3162,7 +3162,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
inputs = []
for i in range(len(configs)):
if i in failed_inputs_map:
- inputs.append(cast(Input, failed_inputs_map[i]))
+ inputs.append(cast("Input", failed_inputs_map[i]))
else:
inputs.append(inputs_copy.pop(0))
else:
@@ -3185,7 +3185,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
for rm in run_managers:
rm.on_chain_error(e)
if return_exceptions:
- return cast(list[Output], [e for _ in inputs])
+ return cast("list[Output]", [e for _ in inputs])
else:
raise
else:
@@ -3197,7 +3197,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
else:
run_manager.on_chain_end(out)
if return_exceptions or first_exception is None:
- return cast(list[Output], inputs)
+ return cast("list[Output]", inputs)
else:
raise first_exception
@@ -3292,7 +3292,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
inputs = []
for i in range(len(configs)):
if i in failed_inputs_map:
- inputs.append(cast(Input, failed_inputs_map[i]))
+ inputs.append(cast("Input", failed_inputs_map[i]))
else:
inputs.append(inputs_copy.pop(0))
else:
@@ -3313,7 +3313,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
except BaseException as e:
await asyncio.gather(*(rm.on_chain_error(e) for rm in run_managers))
if return_exceptions:
- return cast(list[Output], [e for _ in inputs])
+ return cast("list[Output]", [e for _ in inputs])
else:
raise
else:
@@ -3327,7 +3327,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
coros.append(run_manager.on_chain_end(out))
await asyncio.gather(*coros)
if return_exceptions or first_exception is None:
- return cast(list[Output], inputs)
+ return cast("list[Output]", inputs)
else:
raise first_exception
@@ -3346,7 +3346,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
# transform the input stream of each step with the next
# steps that don't natively support transforming an input stream will
# buffer input in memory until all available, and then start emitting output
- final_pipeline = cast(Iterator[Output], input)
+ final_pipeline = cast("Iterator[Output]", input)
for idx, step in enumerate(steps):
config = patch_config(
config, callbacks=run_manager.get_child(f"seq:step:{idx + 1}")
@@ -3374,7 +3374,7 @@ class RunnableSequence(RunnableSerializable[Input, Output]):
# transform the input stream of each step with the next
# steps that don't natively support transforming an input stream will
# buffer input in memory until all available, and then start emitting output
- final_pipeline = cast(AsyncIterator[Output], input)
+ final_pipeline = cast("AsyncIterator[Output]", input)
for idx, step in enumerate(steps):
config = patch_config(
config,
@@ -4189,7 +4189,7 @@ class RunnableGenerator(Runnable[Input, Output]):
final: Optional[Output] = None
for output in self.stream(input, config, **kwargs):
final = output if final is None else final + output # type: ignore[operator]
- return cast(Output, final)
+ return cast("Output", final)
def atransform(
self,
@@ -4222,7 +4222,7 @@ class RunnableGenerator(Runnable[Input, Output]):
final: Optional[Output] = None
async for output in self.astream(input, config, **kwargs):
final = output if final is None else final + output # type: ignore[operator]
- return cast(Output, final)
+ return cast("Output", final)
class RunnableLambda(Runnable[Input, Output]):
@@ -4336,7 +4336,7 @@ class RunnableLambda(Runnable[Input, Output]):
self.afunc = func
func_for_name = func
elif callable(func):
- self.func = cast(Callable[[Input], Output], func)
+ self.func = cast("Callable[[Input], Output]", func)
func_for_name = func
else:
msg = (
@@ -4556,7 +4556,7 @@ class RunnableLambda(Runnable[Input, Output]):
if inspect.isgeneratorfunction(self.func):
output: Optional[Output] = None
for chunk in call_func_with_variable_args(
- cast(Callable[[Input], Iterator[Output]], self.func),
+ cast("Callable[[Input], Iterator[Output]]", self.func),
input,
config,
run_manager,
@@ -4589,7 +4589,7 @@ class RunnableLambda(Runnable[Input, Output]):
recursion_limit=recursion_limit - 1,
),
)
- return cast(Output, output)
+ return cast("Output", output)
async def _ainvoke(
self,
@@ -4611,7 +4611,7 @@ class RunnableLambda(Runnable[Input, Output]):
) -> Output:
output: Optional[Output] = None
for chunk in call_func_with_variable_args(
- cast(Callable[[Input], Iterator[Output]], self.func),
+ cast("Callable[[Input], Iterator[Output]]", self.func),
input,
config,
run_manager.get_sync(),
@@ -4624,7 +4624,7 @@ class RunnableLambda(Runnable[Input, Output]):
output = output + chunk # type: ignore[operator]
except TypeError:
output = chunk
- return cast(Output, output)
+ return cast("Output", output)
else:
@@ -4648,9 +4648,9 @@ class RunnableLambda(Runnable[Input, Output]):
output: Optional[Output] = None
async with aclosing(
cast(
- AsyncGenerator[Any, Any],
+ "AsyncGenerator[Any, Any]",
acall_func_with_variable_args(
- cast(Callable, afunc),
+ cast("Callable", afunc),
input,
config,
run_manager,
@@ -4659,7 +4659,7 @@ class RunnableLambda(Runnable[Input, Output]):
)
) as stream:
async for chunk in cast(
- AsyncIterator[Output],
+ "AsyncIterator[Output]",
stream,
):
if output is None:
@@ -4671,7 +4671,7 @@ class RunnableLambda(Runnable[Input, Output]):
output = chunk
else:
output = await acall_func_with_variable_args(
- cast(Callable, afunc), input, config, run_manager, **kwargs
+ cast("Callable", afunc), input, config, run_manager, **kwargs
)
# If the output is a Runnable, invoke it
if isinstance(output, Runnable):
@@ -4689,7 +4689,7 @@ class RunnableLambda(Runnable[Input, Output]):
recursion_limit=recursion_limit - 1,
),
)
- return cast(Output, output)
+ return cast("Output", output)
def _config(
self, config: Optional[RunnableConfig], callable: Callable[..., Any]
@@ -4779,7 +4779,7 @@ class RunnableLambda(Runnable[Input, Output]):
if inspect.isgeneratorfunction(self.func):
output: Optional[Output] = None
for chunk in call_func_with_variable_args(
- self.func, cast(Input, final), config, run_manager, **kwargs
+ self.func, cast("Input", final), config, run_manager, **kwargs
):
yield chunk
if output is None:
@@ -4791,7 +4791,7 @@ class RunnableLambda(Runnable[Input, Output]):
output = chunk
else:
output = call_func_with_variable_args(
- self.func, cast(Input, final), config, run_manager, **kwargs
+ self.func, cast("Input", final), config, run_manager, **kwargs
)
# If the output is a Runnable, use its stream output
@@ -4813,7 +4813,7 @@ class RunnableLambda(Runnable[Input, Output]):
yield chunk
elif not inspect.isgeneratorfunction(self.func):
# Otherwise, just yield it
- yield cast(Output, output)
+ yield cast("Output", output)
def transform(
self,
@@ -4895,10 +4895,10 @@ class RunnableLambda(Runnable[Input, Output]):
if is_async_generator(afunc):
output: Optional[Output] = None
async for chunk in cast(
- AsyncIterator[Output],
+ "AsyncIterator[Output]",
acall_func_with_variable_args(
- cast(Callable, afunc),
- cast(Input, final),
+ cast("Callable", afunc),
+ cast("Input", final),
config,
run_manager,
**kwargs,
@@ -4914,7 +4914,11 @@ class RunnableLambda(Runnable[Input, Output]):
output = chunk
else:
output = await acall_func_with_variable_args(
- cast(Callable, afunc), cast(Input, final), config, run_manager, **kwargs
+ cast("Callable", afunc),
+ cast("Input", final),
+ config,
+ run_manager,
+ **kwargs,
)
# If the output is a Runnable, use its astream output
@@ -4936,7 +4940,7 @@ class RunnableLambda(Runnable[Input, Output]):
yield chunk
elif not is_async_generator(afunc):
# Otherwise, just yield it
- yield cast(Output, output)
+ yield cast("Output", output)
async def atransform(
self,
@@ -5301,7 +5305,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
@override
def InputType(self) -> type[Input]:
return (
- cast(type[Input], self.custom_input_type)
+ cast("type[Input]", self.custom_input_type)
if self.custom_input_type is not None
else self.bound.InputType
)
@@ -5310,7 +5314,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
@override
def OutputType(self) -> type[Output]:
return (
- cast(type[Output], self.custom_output_type)
+ cast("type[Output]", self.custom_output_type)
if self.custom_output_type is not None
else self.bound.OutputType
)
@@ -5383,7 +5387,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
) -> list[Output]:
if isinstance(config, list):
configs = cast(
- list[RunnableConfig],
+ "list[RunnableConfig]",
[self._merge_configs(conf) for conf in config],
)
else:
@@ -5405,7 +5409,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
) -> list[Output]:
if isinstance(config, list):
configs = cast(
- list[RunnableConfig],
+ "list[RunnableConfig]",
[self._merge_configs(conf) for conf in config],
)
else:
@@ -5447,7 +5451,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
) -> Iterator[tuple[int, Union[Output, Exception]]]:
if isinstance(config, Sequence):
configs = cast(
- list[RunnableConfig],
+ "list[RunnableConfig]",
[self._merge_configs(conf) for conf in config],
)
else:
@@ -5498,7 +5502,7 @@ class RunnableBindingBase(RunnableSerializable[Input, Output]):
) -> AsyncIterator[tuple[int, Union[Output, Exception]]]:
if isinstance(config, Sequence):
configs = cast(
- list[RunnableConfig],
+ "list[RunnableConfig]",
[self._merge_configs(conf) for conf in config],
)
else:
@@ -5665,7 +5669,7 @@ class RunnableBinding(RunnableBindingBase[Input, Output]):
return self.__class__(
bound=self.bound,
kwargs=self.kwargs,
- config=cast(RunnableConfig, {**self.config, **(config or {}), **kwargs}),
+ config=cast("RunnableConfig", {**self.config, **(config or {}), **kwargs}),
custom_input_type=self.custom_input_type,
custom_output_type=self.custom_output_type,
)
@@ -5835,9 +5839,9 @@ def coerce_to_runnable(thing: RunnableLike) -> Runnable[Input, Output]:
elif is_async_generator(thing) or inspect.isgeneratorfunction(thing):
return RunnableGenerator(thing)
elif callable(thing):
- return RunnableLambda(cast(Callable[[Input], Output], thing))
+ return RunnableLambda(cast("Callable[[Input], Output]", thing))
elif isinstance(thing, dict):
- return cast(Runnable[Input, Output], RunnableParallel(thing))
+ return cast("Runnable[Input, Output]", RunnableParallel(thing))
else:
msg = (
f"Expected a Runnable, callable or dict."
diff --git a/libs/core/langchain_core/runnables/branch.py b/libs/core/langchain_core/runnables/branch.py
index 56c4388618..788e90f703 100644
--- a/libs/core/langchain_core/runnables/branch.py
+++ b/libs/core/langchain_core/runnables/branch.py
@@ -105,7 +105,7 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
raise TypeError(msg)
default_ = cast(
- Runnable[Input, Output], coerce_to_runnable(cast(RunnableLike, default))
+ "Runnable[Input, Output]", coerce_to_runnable(cast("RunnableLike", default))
)
_branches = []
@@ -125,7 +125,7 @@ class RunnableBranch(RunnableSerializable[Input, Output]):
)
raise ValueError(msg)
condition, runnable = branch
- condition = cast(Runnable[Input, bool], coerce_to_runnable(condition))
+ condition = cast("Runnable[Input, bool]", coerce_to_runnable(condition))
runnable = coerce_to_runnable(runnable)
_branches.append((condition, runnable))
diff --git a/libs/core/langchain_core/runnables/config.py b/libs/core/langchain_core/runnables/config.py
index 8f06209cb9..3c0a8d3308 100644
--- a/libs/core/langchain_core/runnables/config.py
+++ b/libs/core/langchain_core/runnables/config.py
@@ -200,7 +200,7 @@ def ensure_config(config: Optional[RunnableConfig] = None) -> RunnableConfig:
if var_config := var_child_runnable_config.get():
empty.update(
cast(
- RunnableConfig,
+ "RunnableConfig",
{
k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]
for k, v in var_config.items()
@@ -211,7 +211,7 @@ def ensure_config(config: Optional[RunnableConfig] = None) -> RunnableConfig:
if config is not None:
empty.update(
cast(
- RunnableConfig,
+ "RunnableConfig",
{
k: v.copy() if k in COPIABLE_KEYS else v # type: ignore[attr-defined]
for k, v in config.items()
@@ -271,7 +271,7 @@ def get_config_list(
stacklevel=3,
)
subsequent = cast(
- RunnableConfig, {k: v for k, v in config.items() if k != "run_id"}
+ "RunnableConfig", {k: v for k, v in config.items() if k != "run_id"}
)
return [
ensure_config(subsequent) if i else ensure_config(config)
@@ -533,7 +533,7 @@ class ContextThreadPoolExecutor(ThreadPoolExecutor):
Future[T]: The future for the function.
"""
return super().submit(
- cast(Callable[..., T], partial(copy_context().run, func, *args, **kwargs))
+ cast("Callable[..., T]", partial(copy_context().run, func, *args, **kwargs))
)
def map(
@@ -621,7 +621,7 @@ async def run_in_executor(
# Use default executor with context copied from current context
return await asyncio.get_running_loop().run_in_executor(
None,
- cast(Callable[..., T], partial(copy_context().run, wrapper)),
+ cast("Callable[..., T]", partial(copy_context().run, wrapper)),
)
return await asyncio.get_running_loop().run_in_executor(executor_or_config, wrapper)
diff --git a/libs/core/langchain_core/runnables/configurable.py b/libs/core/langchain_core/runnables/configurable.py
index 79473e5d26..244b6bfcf2 100644
--- a/libs/core/langchain_core/runnables/configurable.py
+++ b/libs/core/langchain_core/runnables/configurable.py
@@ -122,7 +122,7 @@ class DynamicRunnable(RunnableSerializable[Input, Output]):
runnable: Runnable[Input, Output] = self
while isinstance(runnable, DynamicRunnable):
runnable, config = runnable._prepare(merge_configs(runnable.config, config))
- return runnable, cast(RunnableConfig, config)
+ return runnable, cast("RunnableConfig", config)
@abstractmethod
def _prepare(
@@ -178,10 +178,10 @@ class DynamicRunnable(RunnableSerializable[Input, Output]):
# If there's only one input, don't bother with the executor
if len(inputs) == 1:
- return cast(list[Output], [invoke(prepared[0], inputs[0])])
+ return cast("list[Output]", [invoke(prepared[0], inputs[0])])
with get_executor_for_config(configs[0]) as executor:
- return cast(list[Output], list(executor.map(invoke, prepared, inputs)))
+ return cast("list[Output]", list(executor.map(invoke, prepared, inputs)))
async def abatch(
self,
@@ -271,7 +271,7 @@ class DynamicRunnable(RunnableSerializable[Input, Output]):
and "configurable" in arg
and isinstance(arg["configurable"], dict)
):
- runnable, config = self.prepare(cast(RunnableConfig, arg))
+ runnable, config = self.prepare(cast("RunnableConfig", arg))
kwargs = {**kwargs, "config": config}
return getattr(runnable, name)(*args, **kwargs)
@@ -281,7 +281,7 @@ class DynamicRunnable(RunnableSerializable[Input, Output]):
and "configurable" in arg
and isinstance(arg["configurable"], dict)
):
- runnable, config = self.prepare(cast(RunnableConfig, arg))
+ runnable, config = self.prepare(cast("RunnableConfig", arg))
argsl = list(args)
argsl[idx] = config
return getattr(runnable, name)(*argsl, **kwargs)
@@ -563,7 +563,7 @@ class RunnableConfigurableAlternatives(DynamicRunnable[Input, Output]):
for v in list(self.alternatives.keys()) + [self.default_key]
),
)
- _enums_for_spec[self.which] = cast(type[StrEnum], which_enum)
+ _enums_for_spec[self.which] = cast("type[StrEnum]", which_enum)
return get_unique_config_specs(
# which alternative
[
@@ -617,7 +617,7 @@ class RunnableConfigurableAlternatives(DynamicRunnable[Input, Output]):
# remap configurable keys for the chosen alternative
if self.prefix_keys:
config = cast(
- RunnableConfig,
+ "RunnableConfig",
{
**config,
"configurable": {
@@ -696,7 +696,7 @@ def make_options_spec(
spec.name or spec.id,
((v, v) for v in list(spec.options.keys())),
)
- _enums_for_spec[spec] = cast(type[StrEnum], enum)
+ _enums_for_spec[spec] = cast("type[StrEnum]", enum)
if isinstance(spec, ConfigurableFieldSingleOption):
return ConfigurableFieldSpec(
id=spec.id,
diff --git a/libs/core/langchain_core/runnables/fallbacks.py b/libs/core/langchain_core/runnables/fallbacks.py
index 20bfa7e752..10c8a4adba 100644
--- a/libs/core/langchain_core/runnables/fallbacks.py
+++ b/libs/core/langchain_core/runnables/fallbacks.py
@@ -317,12 +317,12 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
if not return_exceptions:
first_to_raise = first_to_raise or output
else:
- handled_exceptions[i] = cast(BaseException, output)
+ handled_exceptions[i] = cast("BaseException", output)
run_again.pop(i)
elif isinstance(output, self.exceptions_to_handle):
if self.exception_key:
input[self.exception_key] = output # type: ignore
- handled_exceptions[i] = cast(BaseException, output)
+ handled_exceptions[i] = cast("BaseException", output)
else:
run_managers[i].on_chain_end(output)
to_return[i] = output
@@ -413,12 +413,12 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
if not return_exceptions:
first_to_raise = first_to_raise or output
else:
- handled_exceptions[i] = cast(BaseException, output)
+ handled_exceptions[i] = cast("BaseException", output)
run_again.pop(i)
elif isinstance(output, self.exceptions_to_handle):
if self.exception_key:
input[self.exception_key] = output # type: ignore
- handled_exceptions[i] = cast(BaseException, output)
+ handled_exceptions[i] = cast("BaseException", output)
else:
to_return[i] = output
await run_managers[i].on_chain_end(output)
@@ -547,7 +547,7 @@ class RunnableWithFallbacks(RunnableSerializable[Input, Output]):
context=context,
)
else:
- chunk = cast(Output, await py_anext(stream))
+ chunk = cast("Output", await py_anext(stream))
except self.exceptions_to_handle as e:
first_error = e if first_error is None else first_error
last_error = e
diff --git a/libs/core/langchain_core/runnables/passthrough.py b/libs/core/langchain_core/runnables/passthrough.py
index 95c27e7bcc..718e855229 100644
--- a/libs/core/langchain_core/runnables/passthrough.py
+++ b/libs/core/langchain_core/runnables/passthrough.py
@@ -565,7 +565,7 @@ class RunnableAssign(RunnableSerializable[dict[str, Any], dict[str, Any]]):
if filtered:
yield filtered
# yield map output
- yield cast(dict[str, Any], first_map_chunk_future.result())
+ yield cast("dict[str, Any]", first_map_chunk_future.result())
for chunk in map_output:
yield chunk
diff --git a/libs/core/langchain_core/runnables/retry.py b/libs/core/langchain_core/runnables/retry.py
index 4320a79446..5d7a74685c 100644
--- a/libs/core/langchain_core/runnables/retry.py
+++ b/libs/core/langchain_core/runnables/retry.py
@@ -245,7 +245,7 @@ class RunnableRetry(RunnableBindingBase[Input, Output]):
attempt.retry_state.set_result(result)
except RetryError as e:
if result is not_set:
- result = cast(list[Output], [e] * len(inputs))
+ result = cast("list[Output]", [e] * len(inputs))
outputs: list[Union[Output, Exception]] = []
for idx in range(len(inputs)):
@@ -311,7 +311,7 @@ class RunnableRetry(RunnableBindingBase[Input, Output]):
attempt.retry_state.set_result(result)
except RetryError as e:
if result is not_set:
- result = cast(list[Output], [e] * len(inputs))
+ result = cast("list[Output]", [e] * len(inputs))
outputs: list[Union[Output, Exception]] = []
for idx in range(len(inputs)):
diff --git a/libs/core/langchain_core/runnables/router.py b/libs/core/langchain_core/runnables/router.py
index 8d679ad35c..856bec5df7 100644
--- a/libs/core/langchain_core/runnables/router.py
+++ b/libs/core/langchain_core/runnables/router.py
@@ -158,7 +158,7 @@ class RouterRunnable(RunnableSerializable[RouterInput, Output]):
configs = get_config_list(config, len(inputs))
with get_executor_for_config(configs[0]) as executor:
return cast(
- list[Output],
+ "list[Output]",
list(executor.map(invoke, runnables, actual_inputs, configs)),
)
diff --git a/libs/core/langchain_core/tools/base.py b/libs/core/langchain_core/tools/base.py
index 87a8c80b86..aa555d3862 100644
--- a/libs/core/langchain_core/tools/base.py
+++ b/libs/core/langchain_core/tools/base.py
@@ -941,11 +941,11 @@ def _prep_run_args(
) -> tuple[Union[str, dict], dict]:
config = ensure_config(config)
if _is_tool_call(input):
- tool_call_id: Optional[str] = cast(ToolCall, input)["id"]
- tool_input: Union[str, dict] = cast(ToolCall, input)["args"].copy()
+ tool_call_id: Optional[str] = cast("ToolCall", input)["id"]
+ tool_input: Union[str, dict] = cast("ToolCall", input)["args"].copy()
else:
tool_call_id = None
- tool_input = cast(Union[str, dict], input)
+ tool_input = cast("Union[str, dict]", input)
return (
tool_input,
dict(
diff --git a/libs/core/langchain_core/tracers/context.py b/libs/core/langchain_core/tracers/context.py
index 5e516a7817..5d31bd334b 100644
--- a/libs/core/langchain_core/tracers/context.py
+++ b/libs/core/langchain_core/tracers/context.py
@@ -128,9 +128,7 @@ def _get_trace_callbacks(
example_id=example_id,
)
if callback_manager is None:
- from langchain_core.callbacks.base import Callbacks
-
- cb = cast(Callbacks, [tracer])
+ cb = cast("Callbacks", [tracer])
else:
if not any(
isinstance(handler, LangChainTracer)
@@ -206,13 +204,12 @@ def register_configure_hook(
if env_var is not None and handle_class is None:
msg = "If env_var is set, handle_class must also be set to a non-None value."
raise ValueError(msg)
- from langchain_core.callbacks.base import BaseCallbackHandler
_configure_hooks.append(
(
# the typings of ContextVar do not have the generic arg set as covariant
# so we have to cast it
- cast(ContextVar[Optional[BaseCallbackHandler]], context_var),
+ cast("ContextVar[Optional[BaseCallbackHandler]]", context_var),
inheritable,
handle_class,
env_var,
diff --git a/libs/core/langchain_core/tracers/core.py b/libs/core/langchain_core/tracers/core.py
index 599c4000cd..1f6e05dbc6 100644
--- a/libs/core/langchain_core/tracers/core.py
+++ b/libs/core/langchain_core/tracers/core.py
@@ -285,7 +285,7 @@ class _TracerCore(ABC):
output_generation = llm_run.outputs["generations"][i][j]
if "message" in output_generation:
output_generation["message"] = dumpd(
- cast(ChatGeneration, generation).message
+ cast("ChatGeneration", generation).message
)
llm_run.end_time = datetime.now(timezone.utc)
llm_run.events.append({"name": "end", "time": llm_run.end_time})
diff --git a/libs/core/langchain_core/tracers/evaluation.py b/libs/core/langchain_core/tracers/evaluation.py
index 057b8f4565..a1e9dac63c 100644
--- a/libs/core/langchain_core/tracers/evaluation.py
+++ b/libs/core/langchain_core/tracers/evaluation.py
@@ -90,7 +90,7 @@ class EvaluatorCallbackHandler(BaseTracer):
self.executor = ThreadPoolExecutor(max_workers=max_concurrency)
weakref.finalize(
self,
- lambda: cast(ThreadPoolExecutor, self.executor).shutdown(wait=True),
+ lambda: cast("ThreadPoolExecutor", self.executor).shutdown(wait=True),
)
else:
self.executor = None
@@ -156,7 +156,7 @@ class EvaluatorCallbackHandler(BaseTracer):
if isinstance(results, EvaluationResult):
results_ = [results]
elif isinstance(results, dict) and "results" in results:
- results_ = cast(list[EvaluationResult], results["results"])
+ results_ = cast("list[EvaluationResult]", results["results"])
else:
msg = (
f"Invalid evaluation result type {type(results)}."
diff --git a/libs/core/langchain_core/tracers/event_stream.py b/libs/core/langchain_core/tracers/event_stream.py
index 2a5f6b5f84..52f897ba29 100644
--- a/libs/core/langchain_core/tracers/event_stream.py
+++ b/libs/core/langchain_core/tracers/event_stream.py
@@ -185,7 +185,7 @@ class _AstreamEventsCallbackHandler(AsyncCallbackHandler, _StreamingCallbackHand
run_info = self.run_map.get(run_id)
if run_info is None:
# run has finished, don't issue any stream events
- yield cast(T, first)
+ yield cast("T", first)
return
if tap is sentinel:
# if we are the first to tap, issue stream events
@@ -199,7 +199,7 @@ class _AstreamEventsCallbackHandler(AsyncCallbackHandler, _StreamingCallbackHand
"parent_ids": self._get_parent_ids(run_id),
}
self._send({**event, "data": {"chunk": first}}, run_info["run_type"])
- yield cast(T, first)
+ yield cast("T", first)
# consume the rest of the output
async for chunk in output:
self._send(
@@ -209,7 +209,7 @@ class _AstreamEventsCallbackHandler(AsyncCallbackHandler, _StreamingCallbackHand
yield chunk
else:
# otherwise just pass through
- yield cast(T, first)
+ yield cast("T", first)
# consume the rest of the output
async for chunk in output:
yield chunk
@@ -235,7 +235,7 @@ class _AstreamEventsCallbackHandler(AsyncCallbackHandler, _StreamingCallbackHand
run_info = self.run_map.get(run_id)
if run_info is None:
# run has finished, don't issue any stream events
- yield cast(T, first)
+ yield cast("T", first)
return
if tap is sentinel:
# if we are the first to tap, issue stream events
@@ -249,7 +249,7 @@ class _AstreamEventsCallbackHandler(AsyncCallbackHandler, _StreamingCallbackHand
"parent_ids": self._get_parent_ids(run_id),
}
self._send({**event, "data": {"chunk": first}}, run_info["run_type"])
- yield cast(T, first)
+ yield cast("T", first)
# consume the rest of the output
for chunk in output:
self._send(
@@ -259,7 +259,7 @@ class _AstreamEventsCallbackHandler(AsyncCallbackHandler, _StreamingCallbackHand
yield chunk
else:
# otherwise just pass through
- yield cast(T, first)
+ yield cast("T", first)
# consume the rest of the output
for chunk in output:
yield chunk
@@ -423,14 +423,14 @@ class _AstreamEventsCallbackHandler(AsyncCallbackHandler, _StreamingCallbackHand
if chunk is None:
chunk_ = AIMessageChunk(content=token)
else:
- chunk_ = cast(ChatGenerationChunk, chunk).message
+ chunk_ = cast("ChatGenerationChunk", chunk).message
elif run_info["run_type"] == "llm":
event = "on_llm_stream"
if chunk is None:
chunk_ = GenerationChunk(text=token)
else:
- chunk_ = cast(GenerationChunk, chunk)
+ chunk_ = cast("GenerationChunk", chunk)
else:
msg = f"Unexpected run type: {run_info['run_type']}"
raise ValueError(msg)
@@ -461,7 +461,7 @@ class _AstreamEventsCallbackHandler(AsyncCallbackHandler, _StreamingCallbackHand
output: Union[dict, BaseMessage] = {}
if run_info["run_type"] == "chat_model":
- generations = cast(list[list[ChatGenerationChunk]], response.generations)
+ generations = cast("list[list[ChatGenerationChunk]]", response.generations)
for gen in generations:
if output != {}:
break
@@ -471,7 +471,7 @@ class _AstreamEventsCallbackHandler(AsyncCallbackHandler, _StreamingCallbackHand
event = "on_chat_model_end"
elif run_info["run_type"] == "llm":
- generations = cast(list[list[GenerationChunk]], response.generations)
+ generations = cast("list[list[GenerationChunk]]", response.generations)
output = {
"generations": [
[
@@ -942,7 +942,7 @@ async def _astream_events_implementation_v2(
# Assign the stream handler to the config
config = ensure_config(config)
- run_id = cast(UUID, config.setdefault("run_id", uuid4()))
+ run_id = cast("UUID", config.setdefault("run_id", uuid4()))
callbacks = config.get("callbacks")
if callbacks is None:
config["callbacks"] = [event_streamer]
diff --git a/libs/core/langchain_core/utils/aiter.py b/libs/core/langchain_core/utils/aiter.py
index b4e26915a3..4e82d9fb3c 100644
--- a/libs/core/langchain_core/utils/aiter.py
+++ b/libs/core/langchain_core/utils/aiter.py
@@ -55,7 +55,7 @@ def py_anext(
"""
try:
__anext__ = cast(
- Callable[[AsyncIterator[T]], Awaitable[T]], type(iterator).__anext__
+ "Callable[[AsyncIterator[T]], Awaitable[T]]", type(iterator).__anext__
)
except AttributeError as e:
msg = f"{iterator!r} is not an async iterator"
diff --git a/libs/core/langchain_core/utils/function_calling.py b/libs/core/langchain_core/utils/function_calling.py
index 5cacfc3256..25248ab870 100644
--- a/libs/core/langchain_core/utils/function_calling.py
+++ b/libs/core/langchain_core/utils/function_calling.py
@@ -244,10 +244,9 @@ convert_python_function_to_openai_function = deprecated(
def _convert_typed_dict_to_openai_function(typed_dict: type) -> FunctionDescription:
visited: dict = {}
- from pydantic.v1 import BaseModel
model = cast(
- type[BaseModel],
+ "type[BaseModel]",
_convert_any_typed_dicts_to_pydantic(typed_dict, visited=visited),
)
return _convert_pydantic_to_openai_function(model) # type: ignore
@@ -471,15 +470,17 @@ def convert_to_openai_function(
if function_copy and "properties" in function_copy:
oai_function["parameters"] = function_copy
elif isinstance(function, type) and is_basemodel_subclass(function):
- oai_function = cast(dict, _convert_pydantic_to_openai_function(function))
+ oai_function = cast("dict", _convert_pydantic_to_openai_function(function))
elif is_typeddict(function):
oai_function = cast(
- dict, _convert_typed_dict_to_openai_function(cast(type, function))
+ "dict", _convert_typed_dict_to_openai_function(cast("type", function))
)
elif isinstance(function, BaseTool):
- oai_function = cast(dict, _format_tool_to_openai_function(function))
+ oai_function = cast("dict", _format_tool_to_openai_function(function))
elif callable(function):
- oai_function = cast(dict, _convert_python_function_to_openai_function(function))
+ oai_function = cast(
+ "dict", _convert_python_function_to_openai_function(function)
+ )
else:
msg = (
f"Unsupported function\n\n{function}\n\nFunctions must be passed in"
@@ -775,7 +776,7 @@ def _py_38_safe_origin(origin: type) -> type:
collections.abc.MutableMapping: typing.MutableMapping,
**origin_union_type_map,
}
- return cast(type, origin_map.get(origin, origin))
+ return cast("type", origin_map.get(origin, origin))
def _recursive_set_additional_properties_false(
diff --git a/libs/core/langchain_core/utils/mustache.py b/libs/core/langchain_core/utils/mustache.py
index 3a95e06bb0..6e12964f7b 100644
--- a/libs/core/langchain_core/utils/mustache.py
+++ b/libs/core/langchain_core/utils/mustache.py
@@ -360,7 +360,7 @@ def _get_key(
# Move into the scope
try:
# Try subscripting (Normal dictionaries)
- resolved_scope = cast(dict[str, Any], resolved_scope)[child]
+ resolved_scope = cast("dict[str, Any]", resolved_scope)[child]
except (TypeError, AttributeError):
try:
resolved_scope = getattr(resolved_scope, child)
@@ -618,7 +618,7 @@ def render(
scope = _get_key(
key, scopes, warn=warn, keep=keep, def_ldel=def_ldel, def_rdel=def_rdel
)
- scopes.insert(0, cast(Literal[False], not scope))
+ scopes.insert(0, cast("Literal[False]", not scope))
# If we're a partial
elif tag == "partial":
diff --git a/libs/core/langchain_core/utils/pydantic.py b/libs/core/langchain_core/utils/pydantic.py
index 0aff29c1bb..d7afe6b626 100644
--- a/libs/core/langchain_core/utils/pydantic.py
+++ b/libs/core/langchain_core/utils/pydantic.py
@@ -473,7 +473,7 @@ def _create_root_model(
except TypeError:
pass
custom_root_type = type(name, (RootModel,), base_class_attributes)
- return cast(type[BaseModel], custom_root_type)
+ return cast("type[BaseModel]", custom_root_type)
@lru_cache(maxsize=256)
@@ -598,7 +598,7 @@ def create_model_v2(
Returns:
Type[BaseModel]: The created model.
"""
- field_definitions = cast(dict[str, Any], field_definitions or {}) # type: ignore[no-redef]
+ field_definitions = cast("dict[str, Any]", field_definitions or {}) # type: ignore[no-redef]
if root:
if field_definitions:
diff --git a/libs/core/pyproject.toml b/libs/core/pyproject.toml
index f7350e0e16..7f50acb0ff 100644
--- a/libs/core/pyproject.toml
+++ b/libs/core/pyproject.toml
@@ -28,7 +28,7 @@ repository = "https://github.com/langchain-ai/langchain"
[dependency-groups]
lint = [
- "ruff<1.0.0,>=0.9.2",
+ "ruff<0.12.0,>=0.11.2",
]
typing = [
"mypy<1.11,>=1.10",
diff --git a/libs/core/tests/unit_tests/example_selectors/test_similarity.py b/libs/core/tests/unit_tests/example_selectors/test_similarity.py
index 5a5f40d197..0936bb2bd7 100644
--- a/libs/core/tests/unit_tests/example_selectors/test_similarity.py
+++ b/libs/core/tests/unit_tests/example_selectors/test_similarity.py
@@ -127,7 +127,7 @@ def test_from_examples() -> None:
assert selector.vectorstore_kwargs == {"vs_foo": "vs_bar"}
assert isinstance(selector.vectorstore, DummyVectorStore)
- vector_store = cast(DummyVectorStore, selector.vectorstore)
+ vector_store = cast("DummyVectorStore", selector.vectorstore)
assert vector_store.embeddings is embeddings
assert vector_store.init_arg == "some_init_arg"
assert vector_store.texts == ["bar"]
@@ -153,7 +153,7 @@ async def test_afrom_examples() -> None:
assert selector.vectorstore_kwargs == {"vs_foo": "vs_bar"}
assert isinstance(selector.vectorstore, DummyVectorStore)
- vector_store = cast(DummyVectorStore, selector.vectorstore)
+ vector_store = cast("DummyVectorStore", selector.vectorstore)
assert vector_store.embeddings is embeddings
assert vector_store.init_arg == "some_init_arg"
assert vector_store.texts == ["bar"]
@@ -207,7 +207,7 @@ def test_mmr_from_examples() -> None:
assert selector.vectorstore_kwargs == {"vs_foo": "vs_bar"}
assert isinstance(selector.vectorstore, DummyVectorStore)
- vector_store = cast(DummyVectorStore, selector.vectorstore)
+ vector_store = cast("DummyVectorStore", selector.vectorstore)
assert vector_store.embeddings is embeddings
assert vector_store.init_arg == "some_init_arg"
assert vector_store.texts == ["bar"]
@@ -235,7 +235,7 @@ async def test_mmr_afrom_examples() -> None:
assert selector.vectorstore_kwargs == {"vs_foo": "vs_bar"}
assert isinstance(selector.vectorstore, DummyVectorStore)
- vector_store = cast(DummyVectorStore, selector.vectorstore)
+ vector_store = cast("DummyVectorStore", selector.vectorstore)
assert vector_store.embeddings is embeddings
assert vector_store.init_arg == "some_init_arg"
assert vector_store.texts == ["bar"]
diff --git a/libs/core/tests/unit_tests/output_parsers/test_list_parser.py b/libs/core/tests/unit_tests/output_parsers/test_list_parser.py
index 6336f8abb1..1b176706e2 100644
--- a/libs/core/tests/unit_tests/output_parsers/test_list_parser.py
+++ b/libs/core/tests/unit_tests/output_parsers/test_list_parser.py
@@ -101,7 +101,7 @@ def test_numbered_list() -> None:
(text2, ["apple", "banana", "cherry"]),
(text3, []),
]:
- expectedlist = [[a] for a in cast(list[str], expected)]
+ expectedlist = [[a] for a in cast("list[str]", expected)]
assert parser.parse(text) == expected
assert add(parser.transform(t for t in text)) == (expected or None)
assert list(parser.transform(t for t in text)) == expectedlist
@@ -137,7 +137,7 @@ def test_markdown_list() -> None:
(text2, ["apple", "banana", "cherry"]),
(text3, []),
]:
- expectedlist = [[a] for a in cast(list[str], expected)]
+ expectedlist = [[a] for a in cast("list[str]", expected)]
assert parser.parse(text) == expected
assert add(parser.transform(t for t in text)) == (expected or None)
assert list(parser.transform(t for t in text)) == expectedlist
@@ -240,7 +240,7 @@ async def test_numbered_list_async() -> None:
(text2, ["apple", "banana", "cherry"]),
(text3, []),
]:
- expectedlist = [[a] for a in cast(list[str], expected)]
+ expectedlist = [[a] for a in cast("list[str]", expected)]
assert await parser.aparse(text) == expected
assert await aadd(parser.atransform(aiter_from_iter(t for t in text))) == (
expected or None
@@ -283,7 +283,7 @@ async def test_markdown_list_async() -> None:
(text2, ["apple", "banana", "cherry"]),
(text3, []),
]:
- expectedlist = [[a] for a in cast(list[str], expected)]
+ expectedlist = [[a] for a in cast("list[str]", expected)]
assert await parser.aparse(text) == expected
assert await aadd(parser.atransform(aiter_from_iter(t for t in text))) == (
expected or None
diff --git a/libs/core/tests/unit_tests/prompts/test_chat.py b/libs/core/tests/unit_tests/prompts/test_chat.py
index 32ad050077..020c959778 100644
--- a/libs/core/tests/unit_tests/prompts/test_chat.py
+++ b/libs/core/tests/unit_tests/prompts/test_chat.py
@@ -929,7 +929,7 @@ async def test_chat_tmpl_serdes(snapshot: SnapshotAssertion) -> None:
("system", [{"text": "You are an AI assistant named {name}."}]),
SystemMessagePromptTemplate.from_template("you are {foo}"),
cast(
- tuple,
+ "tuple",
(
"human",
[
diff --git a/libs/core/tests/unit_tests/prompts/test_structured.py b/libs/core/tests/unit_tests/prompts/test_structured.py
index 921ff68a0f..9a955fa67b 100644
--- a/libs/core/tests/unit_tests/prompts/test_structured.py
+++ b/libs/core/tests/unit_tests/prompts/test_structured.py
@@ -19,7 +19,7 @@ def _fake_runnable(
if isclass(schema) and is_basemodel_subclass(schema):
return schema(name="yo", value=value)
else:
- params = cast(dict, schema)["parameters"]
+ params = cast("dict", schema)["parameters"]
return {k: 1 if k != "value" else value for k, v in params.items()}
diff --git a/libs/core/tests/unit_tests/runnables/test_config.py b/libs/core/tests/unit_tests/runnables/test_config.py
index 678a808622..dc7f1c5d0c 100644
--- a/libs/core/tests/unit_tests/runnables/test_config.py
+++ b/libs/core/tests/unit_tests/runnables/test_config.py
@@ -48,7 +48,7 @@ def test_ensure_config() -> None:
"tags": ["tag3", "tag4"],
},
)
- config = ctx.run(ensure_config, cast(RunnableConfig, arg))
+ config = ctx.run(ensure_config, cast("RunnableConfig", arg))
assert len(arg["callbacks"]) == 1, (
"ensure_config should not modify the original config"
)
@@ -147,7 +147,7 @@ async def test_merge_config_callbacks() -> None:
def test_config_arbitrary_keys() -> None:
base: RunnablePassthrough[Any] = RunnablePassthrough()
bound = base.with_config(my_custom_key="my custom value")
- config = cast(RunnableBinding, bound).config
+ config = cast("RunnableBinding", bound).config
assert config.get("my_custom_key") == "my custom value"
diff --git a/libs/core/tests/unit_tests/runnables/test_runnable.py b/libs/core/tests/unit_tests/runnables/test_runnable.py
index dd28080ea2..12c0fad86d 100644
--- a/libs/core/tests/unit_tests/runnables/test_runnable.py
+++ b/libs/core/tests/unit_tests/runnables/test_runnable.py
@@ -2436,7 +2436,7 @@ async def test_stream_log_retriever() -> None:
):
del op["value"]["id"]
- assert sorted(cast(RunLog, add(stream_log)).state["logs"]) == [
+ assert sorted(cast("RunLog", add(stream_log)).state["logs"]) == [
"ChatPromptTemplate",
"FakeListLLM",
"FakeListLLM:2",
@@ -2632,7 +2632,7 @@ def test_combining_sequences(
lambda x: {"question": x[0] + x[1]}
)
- chain2 = cast(RunnableSequence, input_formatter | prompt2 | chat2 | parser2)
+ chain2 = cast("RunnableSequence", input_formatter | prompt2 | chat2 | parser2)
assert isinstance(chain, RunnableSequence)
assert chain2.first == input_formatter
@@ -2640,7 +2640,7 @@ def test_combining_sequences(
assert chain2.last == parser2
assert dumps(chain2, pretty=True) == snapshot
- combined_chain = cast(RunnableSequence, chain | chain2)
+ combined_chain = cast("RunnableSequence", chain | chain2)
assert combined_chain.first == prompt
assert combined_chain.middle == [
@@ -3278,7 +3278,7 @@ async def test_map_astream() -> None:
final_state = chunk
else:
final_state += chunk
- final_state = cast(RunLog, final_state)
+ final_state = cast("RunLog", final_state)
assert final_state.state["final_output"] == final_value
assert len(final_state.state["streamed_output"]) == len(streamed_chunks)
@@ -3312,7 +3312,7 @@ async def test_map_astream() -> None:
final_state = chunk
else:
final_state += chunk
- final_state = cast(RunLog, final_state)
+ final_state = cast("RunLog", final_state)
assert final_state.state["final_output"] == final_value
assert len(final_state.state["streamed_output"]) == len(streamed_chunks)
@@ -3328,7 +3328,7 @@ async def test_map_astream() -> None:
final_state = chunk
else:
final_state += chunk
- final_state = cast(RunLog, final_state)
+ final_state = cast("RunLog", final_state)
assert final_state.state["final_output"] == final_value
assert len(final_state.state["streamed_output"]) == len(streamed_chunks)
@@ -4032,7 +4032,7 @@ async def test_runnable_lambda_astream() -> None:
output = [
chunk
async for chunk in cast(
- AsyncIterator[str], RunnableLambda(lambda x: llm).astream("")
+ "AsyncIterator[str]", RunnableLambda(lambda x: llm).astream("")
)
]
assert output == list(llm_res)
@@ -5350,7 +5350,7 @@ def test_default_transform_with_dicts() -> None:
def invoke(
self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Output:
- return cast(Output, input) # type: ignore
+ return cast("Output", input) # type: ignore
runnable = CustomRunnable[dict[str, str], dict[str, str]]()
chunks = iter(
@@ -5371,7 +5371,7 @@ async def test_default_atransform_with_dicts() -> None:
def invoke(
self, input: Input, config: Optional[RunnableConfig] = None, **kwargs: Any
) -> Output:
- return cast(Output, input)
+ return cast("Output", input)
runnable = CustomRunnable[dict[str, str], dict[str, str]]()
diff --git a/libs/core/tests/unit_tests/runnables/test_runnable_events_v1.py b/libs/core/tests/unit_tests/runnables/test_runnable_events_v1.py
index 9aab4eef34..634dd866a4 100644
--- a/libs/core/tests/unit_tests/runnables/test_runnable_events_v1.py
+++ b/libs/core/tests/unit_tests/runnables/test_runnable_events_v1.py
@@ -42,7 +42,7 @@ def _with_nulled_run_id(events: Sequence[StreamEvent]) -> list[StreamEvent]:
assert "parent_ids" in event, "Parent ids should be present in the event."
assert event["parent_ids"] == [], "Parent ids should be empty."
- return cast(list[StreamEvent], [{**event, "run_id": ""} for event in events])
+ return cast("list[StreamEvent]", [{**event, "run_id": ""} for event in events])
async def _as_async_iterator(iterable: list) -> AsyncIterator:
diff --git a/libs/core/tests/unit_tests/runnables/test_runnable_events_v2.py b/libs/core/tests/unit_tests/runnables/test_runnable_events_v2.py
index e1e1f37b90..82b2309168 100644
--- a/libs/core/tests/unit_tests/runnables/test_runnable_events_v2.py
+++ b/libs/core/tests/unit_tests/runnables/test_runnable_events_v2.py
@@ -68,7 +68,7 @@ def _with_nulled_run_id(events: Sequence[StreamEvent]) -> list[StreamEvent]:
)
return cast(
- list[StreamEvent],
+ "list[StreamEvent]",
[{**event, "run_id": "", "parent_ids": []} for event in events],
)
diff --git a/libs/core/tests/unit_tests/test_tools.py b/libs/core/tests/unit_tests/test_tools.py
index 18f11bdc26..156556f390 100644
--- a/libs/core/tests/unit_tests/test_tools.py
+++ b/libs/core/tests/unit_tests/test_tools.py
@@ -203,7 +203,7 @@ def test_decorator_with_specified_schema() -> None:
assert isinstance(tool_func, BaseTool)
assert tool_func.args_schema == _MockSchema
- @tool(args_schema=cast(ArgsSchema, _MockSchemaV1))
+ @tool(args_schema=cast("ArgsSchema", _MockSchemaV1))
def tool_func_v1(arg1: int, arg2: bool, arg3: Optional[dict] = None) -> str:
return f"{arg1} {arg2} {arg3}"
@@ -1935,7 +1935,7 @@ def test_structured_tool_with_different_pydantic_versions(pydantic_model: Any) -
assert foo_tool.invoke({"a": 5, "b": "hello"}) == "foo"
- args_schema = cast(BaseModel, foo_tool.args_schema)
+ args_schema = cast("BaseModel", foo_tool.args_schema)
args_json_schema = (
args_schema.model_json_schema()
if hasattr(args_schema, "model_json_schema")
@@ -2484,7 +2484,7 @@ def test_tool_decorator_description() -> None:
assert foo.description == "Foo."
assert (
- cast(BaseModel, foo.tool_call_schema).model_json_schema()["description"]
+ cast("BaseModel", foo.tool_call_schema).model_json_schema()["description"]
== "Foo."
)
@@ -2496,7 +2496,7 @@ def test_tool_decorator_description() -> None:
assert foo_description.description == "description"
assert (
- cast(BaseModel, foo_description.tool_call_schema).model_json_schema()[
+ cast("BaseModel", foo_description.tool_call_schema).model_json_schema()[
"description"
]
== "description"
@@ -2514,7 +2514,7 @@ def test_tool_decorator_description() -> None:
assert foo_args_schema.description == "Bar."
assert (
- cast(BaseModel, foo_args_schema.tool_call_schema).model_json_schema()[
+ cast("BaseModel", foo_args_schema.tool_call_schema).model_json_schema()[
"description"
]
== "Bar."
@@ -2527,7 +2527,7 @@ def test_tool_decorator_description() -> None:
assert foo_args_schema_description.description == "description"
assert (
cast(
- BaseModel, foo_args_schema_description.tool_call_schema
+ "BaseModel", foo_args_schema_description.tool_call_schema
).model_json_schema()["description"]
== "description"
)
@@ -2552,13 +2552,13 @@ def test_tool_decorator_description() -> None:
assert foo_args_jsons_schema.description == "JSON Schema."
assert (
- cast(dict, foo_args_jsons_schema.tool_call_schema)["description"]
+ cast("dict", foo_args_jsons_schema.tool_call_schema)["description"]
== "JSON Schema."
)
assert foo_args_jsons_schema_with_description.description == "description"
assert (
- cast(dict, foo_args_jsons_schema_with_description.tool_call_schema)[
+ cast("dict", foo_args_jsons_schema_with_description.tool_call_schema)[
"description"
]
== "description"
diff --git a/libs/core/uv.lock b/libs/core/uv.lock
index fdbfad5601..309da3d6b0 100644
--- a/libs/core/uv.lock
+++ b/libs/core/uv.lock
@@ -1,4 +1,5 @@
version = 1
+revision = 1
requires-python = ">=3.9, <4.0"
resolution-markers = [
"python_full_version >= '3.12.4'",
@@ -998,7 +999,7 @@ dev = [
{ name = "jupyter", specifier = ">=1.0.0,<2.0.0" },
{ name = "setuptools", specifier = ">=67.6.1,<68.0.0" },
]
-lint = [{ name = "ruff", specifier = ">=0.9.2,<1.0.0" }]
+lint = [{ name = "ruff", specifier = ">=0.11.2,<0.12.0" }]
test = [
{ name = "blockbuster", specifier = "~=1.5.18" },
{ name = "freezegun", specifier = ">=1.2.2,<2.0.0" },
@@ -1026,7 +1027,7 @@ typing = [
[[package]]
name = "langchain-tests"
-version = "0.3.16"
+version = "0.3.17"
source = { directory = "../standard-tests" }
dependencies = [
{ name = "httpx" },
@@ -2261,27 +2262,27 @@ wheels = [
[[package]]
name = "ruff"
-version = "0.9.4"
-source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/c0/17/529e78f49fc6f8076f50d985edd9a2cf011d1dbadb1cdeacc1d12afc1d26/ruff-0.9.4.tar.gz", hash = "sha256:6907ee3529244bb0ed066683e075f09285b38dd5b4039370df6ff06041ca19e7", size = 3599458 }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/b6/f8/3fafb7804d82e0699a122101b5bee5f0d6e17c3a806dcbc527bb7d3f5b7a/ruff-0.9.4-py3-none-linux_armv6l.whl", hash = "sha256:64e73d25b954f71ff100bb70f39f1ee09e880728efb4250c632ceed4e4cdf706", size = 11668400 },
- { url = "https://files.pythonhosted.org/packages/2e/a6/2efa772d335da48a70ab2c6bb41a096c8517ca43c086ea672d51079e3d1f/ruff-0.9.4-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:6ce6743ed64d9afab4fafeaea70d3631b4d4b28b592db21a5c2d1f0ef52934bf", size = 11628395 },
- { url = "https://files.pythonhosted.org/packages/dc/d7/cd822437561082f1c9d7225cc0d0fbb4bad117ad7ac3c41cd5d7f0fa948c/ruff-0.9.4-py3-none-macosx_11_0_arm64.whl", hash = "sha256:54499fb08408e32b57360f6f9de7157a5fec24ad79cb3f42ef2c3f3f728dfe2b", size = 11090052 },
- { url = "https://files.pythonhosted.org/packages/9e/67/3660d58e893d470abb9a13f679223368ff1684a4ef40f254a0157f51b448/ruff-0.9.4-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:37c892540108314a6f01f105040b5106aeb829fa5fb0561d2dcaf71485021137", size = 11882221 },
- { url = "https://files.pythonhosted.org/packages/79/d1/757559995c8ba5f14dfec4459ef2dd3fcea82ac43bc4e7c7bf47484180c0/ruff-0.9.4-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:de9edf2ce4b9ddf43fd93e20ef635a900e25f622f87ed6e3047a664d0e8f810e", size = 11424862 },
- { url = "https://files.pythonhosted.org/packages/c0/96/7915a7c6877bb734caa6a2af424045baf6419f685632469643dbd8eb2958/ruff-0.9.4-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:87c90c32357c74f11deb7fbb065126d91771b207bf9bfaaee01277ca59b574ec", size = 12626735 },
- { url = "https://files.pythonhosted.org/packages/0e/cc/dadb9b35473d7cb17c7ffe4737b4377aeec519a446ee8514123ff4a26091/ruff-0.9.4-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:56acd6c694da3695a7461cc55775f3a409c3815ac467279dfa126061d84b314b", size = 13255976 },
- { url = "https://files.pythonhosted.org/packages/5f/c3/ad2dd59d3cabbc12df308cced780f9c14367f0321e7800ca0fe52849da4c/ruff-0.9.4-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:e0c93e7d47ed951b9394cf352d6695b31498e68fd5782d6cbc282425655f687a", size = 12752262 },
- { url = "https://files.pythonhosted.org/packages/c7/17/5f1971e54bd71604da6788efd84d66d789362b1105e17e5ccc53bba0289b/ruff-0.9.4-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:1d4c8772670aecf037d1bf7a07c39106574d143b26cfe5ed1787d2f31e800214", size = 14401648 },
- { url = "https://files.pythonhosted.org/packages/30/24/6200b13ea611b83260501b6955b764bb320e23b2b75884c60ee7d3f0b68e/ruff-0.9.4-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bfc5f1d7afeda8d5d37660eeca6d389b142d7f2b5a1ab659d9214ebd0e025231", size = 12414702 },
- { url = "https://files.pythonhosted.org/packages/34/cb/f5d50d0c4ecdcc7670e348bd0b11878154bc4617f3fdd1e8ad5297c0d0ba/ruff-0.9.4-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:faa935fc00ae854d8b638c16a5f1ce881bc3f67446957dd6f2af440a5fc8526b", size = 11859608 },
- { url = "https://files.pythonhosted.org/packages/d6/f4/9c8499ae8426da48363bbb78d081b817b0f64a9305f9b7f87eab2a8fb2c1/ruff-0.9.4-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:a6c634fc6f5a0ceae1ab3e13c58183978185d131a29c425e4eaa9f40afe1e6d6", size = 11485702 },
- { url = "https://files.pythonhosted.org/packages/18/59/30490e483e804ccaa8147dd78c52e44ff96e1c30b5a95d69a63163cdb15b/ruff-0.9.4-py3-none-musllinux_1_2_i686.whl", hash = "sha256:433dedf6ddfdec7f1ac7575ec1eb9844fa60c4c8c2f8887a070672b8d353d34c", size = 12067782 },
- { url = "https://files.pythonhosted.org/packages/3d/8c/893fa9551760b2f8eb2a351b603e96f15af167ceaf27e27ad873570bc04c/ruff-0.9.4-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:d612dbd0f3a919a8cc1d12037168bfa536862066808960e0cc901404b77968f0", size = 12483087 },
- { url = "https://files.pythonhosted.org/packages/23/15/f6751c07c21ca10e3f4a51ea495ca975ad936d780c347d9808bcedbd7182/ruff-0.9.4-py3-none-win32.whl", hash = "sha256:db1192ddda2200671f9ef61d9597fcef89d934f5d1705e571a93a67fb13a4402", size = 9852302 },
- { url = "https://files.pythonhosted.org/packages/12/41/2d2d2c6a72e62566f730e49254f602dfed23019c33b5b21ea8f8917315a1/ruff-0.9.4-py3-none-win_amd64.whl", hash = "sha256:05bebf4cdbe3ef75430d26c375773978950bbf4ee3c95ccb5448940dc092408e", size = 10850051 },
- { url = "https://files.pythonhosted.org/packages/c6/e6/3d6ec3bc3d254e7f005c543a661a41c3e788976d0e52a1ada195bd664344/ruff-0.9.4-py3-none-win_arm64.whl", hash = "sha256:585792f1e81509e38ac5123492f8875fbc36f3ede8185af0a26df348e5154f41", size = 10078251 },
+version = "0.11.2"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/90/61/fb87430f040e4e577e784e325351186976516faef17d6fcd921fe28edfd7/ruff-0.11.2.tar.gz", hash = "sha256:ec47591497d5a1050175bdf4e1a4e6272cddff7da88a2ad595e1e326041d8d94", size = 3857511 }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/62/99/102578506f0f5fa29fd7e0df0a273864f79af044757aef73d1cae0afe6ad/ruff-0.11.2-py3-none-linux_armv6l.whl", hash = "sha256:c69e20ea49e973f3afec2c06376eb56045709f0212615c1adb0eda35e8a4e477", size = 10113146 },
+ { url = "https://files.pythonhosted.org/packages/74/ad/5cd4ba58ab602a579997a8494b96f10f316e874d7c435bcc1a92e6da1b12/ruff-0.11.2-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:2c5424cc1c4eb1d8ecabe6d4f1b70470b4f24a0c0171356290b1953ad8f0e272", size = 10867092 },
+ { url = "https://files.pythonhosted.org/packages/fc/3e/d3f13619e1d152c7b600a38c1a035e833e794c6625c9a6cea6f63dbf3af4/ruff-0.11.2-py3-none-macosx_11_0_arm64.whl", hash = "sha256:ecf20854cc73f42171eedb66f006a43d0a21bfb98a2523a809931cda569552d9", size = 10224082 },
+ { url = "https://files.pythonhosted.org/packages/90/06/f77b3d790d24a93f38e3806216f263974909888fd1e826717c3ec956bbcd/ruff-0.11.2-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0c543bf65d5d27240321604cee0633a70c6c25c9a2f2492efa9f6d4b8e4199bb", size = 10394818 },
+ { url = "https://files.pythonhosted.org/packages/99/7f/78aa431d3ddebfc2418cd95b786642557ba8b3cb578c075239da9ce97ff9/ruff-0.11.2-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:20967168cc21195db5830b9224be0e964cc9c8ecf3b5a9e3ce19876e8d3a96e3", size = 9952251 },
+ { url = "https://files.pythonhosted.org/packages/30/3e/f11186d1ddfaca438c3bbff73c6a2fdb5b60e6450cc466129c694b0ab7a2/ruff-0.11.2-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:955a9ce63483999d9f0b8f0b4a3ad669e53484232853054cc8b9d51ab4c5de74", size = 11563566 },
+ { url = "https://files.pythonhosted.org/packages/22/6c/6ca91befbc0a6539ee133d9a9ce60b1a354db12c3c5d11cfdbf77140f851/ruff-0.11.2-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:86b3a27c38b8fce73bcd262b0de32e9a6801b76d52cdb3ae4c914515f0cef608", size = 12208721 },
+ { url = "https://files.pythonhosted.org/packages/19/b0/24516a3b850d55b17c03fc399b681c6a549d06ce665915721dc5d6458a5c/ruff-0.11.2-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a3b66a03b248c9fcd9d64d445bafdf1589326bee6fc5c8e92d7562e58883e30f", size = 11662274 },
+ { url = "https://files.pythonhosted.org/packages/d7/65/76be06d28ecb7c6070280cef2bcb20c98fbf99ff60b1c57d2fb9b8771348/ruff-0.11.2-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0397c2672db015be5aa3d4dac54c69aa012429097ff219392c018e21f5085147", size = 13792284 },
+ { url = "https://files.pythonhosted.org/packages/ce/d2/4ceed7147e05852876f3b5f3fdc23f878ce2b7e0b90dd6e698bda3d20787/ruff-0.11.2-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:869bcf3f9abf6457fbe39b5a37333aa4eecc52a3b99c98827ccc371a8e5b6f1b", size = 11327861 },
+ { url = "https://files.pythonhosted.org/packages/c4/78/4935ecba13706fd60ebe0e3dc50371f2bdc3d9bc80e68adc32ff93914534/ruff-0.11.2-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:2a2b50ca35457ba785cd8c93ebbe529467594087b527a08d487cf0ee7b3087e9", size = 10276560 },
+ { url = "https://files.pythonhosted.org/packages/81/7f/1b2435c3f5245d410bb5dc80f13ec796454c21fbda12b77d7588d5cf4e29/ruff-0.11.2-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:7c69c74bf53ddcfbc22e6eb2f31211df7f65054bfc1f72288fc71e5f82db3eab", size = 9945091 },
+ { url = "https://files.pythonhosted.org/packages/39/c4/692284c07e6bf2b31d82bb8c32f8840f9d0627d92983edaac991a2b66c0a/ruff-0.11.2-py3-none-musllinux_1_2_i686.whl", hash = "sha256:6e8fb75e14560f7cf53b15bbc55baf5ecbe373dd5f3aab96ff7aa7777edd7630", size = 10977133 },
+ { url = "https://files.pythonhosted.org/packages/94/cf/8ab81cb7dd7a3b0a3960c2769825038f3adcd75faf46dd6376086df8b128/ruff-0.11.2-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:842a472d7b4d6f5924e9297aa38149e5dcb1e628773b70e6387ae2c97a63c58f", size = 11378514 },
+ { url = "https://files.pythonhosted.org/packages/d9/3a/a647fa4f316482dacf2fd68e8a386327a33d6eabd8eb2f9a0c3d291ec549/ruff-0.11.2-py3-none-win32.whl", hash = "sha256:aca01ccd0eb5eb7156b324cfaa088586f06a86d9e5314b0eb330cb48415097cc", size = 10319835 },
+ { url = "https://files.pythonhosted.org/packages/86/54/3c12d3af58012a5e2cd7ebdbe9983f4834af3f8cbea0e8a8c74fa1e23b2b/ruff-0.11.2-py3-none-win_amd64.whl", hash = "sha256:3170150172a8f994136c0c66f494edf199a0bbea7a409f649e4bc8f4d7084080", size = 11373713 },
+ { url = "https://files.pythonhosted.org/packages/d6/d4/dd813703af8a1e2ac33bf3feb27e8a5ad514c9f219df80c64d69807e7f71/ruff-0.11.2-py3-none-win_arm64.whl", hash = "sha256:52933095158ff328f4c77af3d74f0379e34fd52f175144cefc1b192e7ccd32b4", size = 10441990 },
]
[[package]]