anthropic[patch]: ruff fixes and rules (#31899)

* bump ruff deps
* add more thorough ruff rules
* fix said rules
This commit is contained in:
Mason Daugherty
2025-07-07 18:32:27 -04:00
committed by GitHub
parent e7eac27241
commit 2a7645300c
18 changed files with 430 additions and 311 deletions

View File

@@ -1,3 +1,5 @@
from __future__ import annotations
import re
import warnings
from collections.abc import AsyncIterator, Iterator, Mapping
@@ -85,8 +87,7 @@ class _AnthropicCommon(BaseLanguageModel):
@classmethod
def build_extra(cls, values: dict) -> Any:
all_required_field_names = get_pydantic_field_names(cls)
values = _build_model_kwargs(values, all_required_field_names)
return values
return _build_model_kwargs(values, all_required_field_names)
@model_validator(mode="after")
def validate_environment(self) -> Self:
@@ -125,11 +126,12 @@ class _AnthropicCommon(BaseLanguageModel):
@property
def _identifying_params(self) -> Mapping[str, Any]:
"""Get the identifying parameters."""
return {**{}, **self._default_params}
return {**self._default_params}
def _get_anthropic_stop(self, stop: Optional[list[str]] = None) -> list[str]:
if not self.HUMAN_PROMPT or not self.AI_PROMPT:
raise NameError("Please ensure the anthropic package is loaded")
msg = "Please ensure the anthropic package is loaded"
raise NameError(msg)
if stop is None:
stop = []
@@ -152,6 +154,7 @@ class AnthropicLLM(LLM, _AnthropicCommon):
from langchain_anthropic import AnthropicLLM
model = AnthropicLLM()
"""
model_config = ConfigDict(
@@ -166,7 +169,7 @@ class AnthropicLLM(LLM, _AnthropicCommon):
warnings.warn(
"This Anthropic LLM is deprecated. "
"Please use `from langchain_anthropic import ChatAnthropic` "
"instead"
"instead",
)
return values
@@ -199,7 +202,9 @@ class AnthropicLLM(LLM, _AnthropicCommon):
}
def _get_ls_params(
self, stop: Optional[list[str]] = None, **kwargs: Any
self,
stop: Optional[list[str]] = None,
**kwargs: Any,
) -> LangSmithParams:
"""Get standard params for tracing."""
params = super()._get_ls_params(stop=stop, **kwargs)
@@ -213,7 +218,8 @@ class AnthropicLLM(LLM, _AnthropicCommon):
def _wrap_prompt(self, prompt: str) -> str:
if not self.HUMAN_PROMPT or not self.AI_PROMPT:
raise NameError("Please ensure the anthropic package is loaded")
msg = "Please ensure the anthropic package is loaded"
raise NameError(msg)
if prompt.startswith(self.HUMAN_PROMPT):
return prompt # Already wrapped.
@@ -238,6 +244,8 @@ class AnthropicLLM(LLM, _AnthropicCommon):
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
run_manager: Optional callback manager for LLM run.
kwargs: Additional keyword arguments to pass to the model.
Returns:
The string generated by the model.
@@ -253,7 +261,10 @@ class AnthropicLLM(LLM, _AnthropicCommon):
if self.streaming:
completion = ""
for chunk in self._stream(
prompt=prompt, stop=stop, run_manager=run_manager, **kwargs
prompt=prompt,
stop=stop,
run_manager=run_manager,
**kwargs,
):
completion += chunk.text
return completion
@@ -281,7 +292,10 @@ class AnthropicLLM(LLM, _AnthropicCommon):
if self.streaming:
completion = ""
async for chunk in self._astream(
prompt=prompt, stop=stop, run_manager=run_manager, **kwargs
prompt=prompt,
stop=stop,
run_manager=run_manager,
**kwargs,
):
completion += chunk.text
return completion
@@ -308,8 +322,12 @@ class AnthropicLLM(LLM, _AnthropicCommon):
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
run_manager: Optional callback manager for LLM run.
kwargs: Additional keyword arguments to pass to the model.
Returns:
A generator representing the stream of tokens from Anthropic.
Example:
.. code-block:: python
@@ -319,12 +337,16 @@ class AnthropicLLM(LLM, _AnthropicCommon):
generator = anthropic.stream(prompt)
for token in generator:
yield token
"""
stop = self._get_anthropic_stop(stop)
params = {**self._default_params, **kwargs}
for token in self.client.completions.create(
prompt=self._wrap_prompt(prompt), stop_sequences=stop, stream=True, **params
prompt=self._wrap_prompt(prompt),
stop_sequences=stop,
stream=True,
**params,
):
chunk = GenerationChunk(text=token.completion)
@@ -344,8 +366,12 @@ class AnthropicLLM(LLM, _AnthropicCommon):
Args:
prompt: The prompt to pass into the model.
stop: Optional list of stop words to use when generating.
run_manager: Optional callback manager for LLM run.
kwargs: Additional keyword arguments to pass to the model.
Returns:
A generator representing the stream of tokens from Anthropic.
Example:
.. code-block:: python
@@ -354,6 +380,7 @@ class AnthropicLLM(LLM, _AnthropicCommon):
generator = anthropic.stream(prompt)
for token in generator:
yield token
"""
stop = self._get_anthropic_stop(stop)
params = {**self._default_params, **kwargs}
@@ -372,15 +399,16 @@ class AnthropicLLM(LLM, _AnthropicCommon):
def get_num_tokens(self, text: str) -> int:
"""Calculate number of tokens."""
raise NotImplementedError(
msg = (
"Anthropic's legacy count_tokens method was removed in anthropic 0.39.0 "
"and langchain-anthropic 0.3.0. Please use "
"ChatAnthropic.get_num_tokens_from_messages instead."
)
raise NotImplementedError(
msg,
)
@deprecated(since="0.1.0", removal="1.0.0", alternative="AnthropicLLM")
class Anthropic(AnthropicLLM):
"""Anthropic large language model."""
pass