partners[lint]: run pyupgrade to get code in line with 3.9 standards (#30781)

Using `pyupgrade` to get all `partners` code up to 3.9 standards
(mostly, fixing old `typing` imports).
This commit is contained in:
Sydney Runkle
2025-04-11 07:18:44 -04:00
committed by GitHub
parent e72f3c26a0
commit 8c6734325b
123 changed files with 1000 additions and 1109 deletions

View File

@@ -1,7 +1,6 @@
"""Standard LangChain interface tests"""
import os
from typing import Type
from langchain_core.language_models import BaseChatModel
from langchain_tests.integration_tests import ChatModelIntegrationTests
@@ -14,7 +13,7 @@ OPENAI_API_BASE = os.environ.get("AZURE_OPENAI_API_BASE", "")
class TestAzureOpenAIStandard(ChatModelIntegrationTests):
@property
def chat_model_class(self) -> Type[BaseChatModel]:
def chat_model_class(self) -> type[BaseChatModel]:
return AzureChatOpenAI
@property
@@ -40,7 +39,7 @@ class TestAzureOpenAIStandardLegacy(ChatModelIntegrationTests):
"""Test a legacy model."""
@property
def chat_model_class(self) -> Type[BaseChatModel]:
def chat_model_class(self) -> type[BaseChatModel]:
return AzureChatOpenAI
@property

View File

@@ -2,9 +2,10 @@
import base64
import json
from collections.abc import AsyncIterator
from pathlib import Path
from textwrap import dedent
from typing import Any, AsyncIterator, List, Literal, Optional, cast
from typing import Any, Literal, Optional, cast
import httpx
import openai
@@ -531,14 +532,14 @@ class MakeASandwich(BaseModel):
bread_type: str
cheese_type: str
condiments: List[str]
vegetables: List[str]
condiments: list[str]
vegetables: list[str]
def test_tool_use() -> None:
llm = ChatOpenAI(model="gpt-4-turbo", temperature=0)
llm_with_tool = llm.bind_tools(tools=[GenerateUsername], tool_choice=True)
msgs: List = [HumanMessage("Sally has green hair, what would her username be?")]
msgs: list = [HumanMessage("Sally has green hair, what would her username be?")]
ai_msg = llm_with_tool.invoke(msgs)
assert isinstance(ai_msg, AIMessage)
@@ -583,7 +584,7 @@ def test_manual_tool_call_msg(use_responses_api: bool) -> None:
model="gpt-3.5-turbo-0125", temperature=0, use_responses_api=use_responses_api
)
llm_with_tool = llm.bind_tools(tools=[GenerateUsername])
msgs: List = [
msgs: list = [
HumanMessage("Sally has green hair, what would her username be?"),
AIMessage(
content="",
@@ -1045,7 +1046,7 @@ def test_audio_output_modality() -> None:
},
)
history: List[BaseMessage] = [
history: list[BaseMessage] = [
HumanMessage("Make me a short audio clip of you yelling")
]

View File

@@ -1,7 +1,7 @@
"""Standard LangChain interface tests"""
from pathlib import Path
from typing import Dict, List, Literal, Type, cast
from typing import Literal, cast
from langchain_core.language_models import BaseChatModel
from langchain_core.messages import AIMessage
@@ -14,7 +14,7 @@ REPO_ROOT_DIR = Path(__file__).parents[6]
class TestOpenAIStandard(ChatModelIntegrationTests):
@property
def chat_model_class(self) -> Type[BaseChatModel]:
def chat_model_class(self) -> type[BaseChatModel]:
return ChatOpenAI
@property
@@ -36,9 +36,9 @@ class TestOpenAIStandard(ChatModelIntegrationTests):
@property
def supported_usage_metadata_details(
self,
) -> Dict[
) -> dict[
Literal["invoke", "stream"],
List[
list[
Literal[
"audio_input",
"audio_output",
@@ -51,7 +51,7 @@ class TestOpenAIStandard(ChatModelIntegrationTests):
return {"invoke": ["reasoning_output", "cache_read_input"], "stream": []}
def invoke_with_cache_read_input(self, *, stream: bool = False) -> AIMessage:
with open(REPO_ROOT_DIR / "README.md", "r") as f:
with open(REPO_ROOT_DIR / "README.md") as f:
readme = f.read()
input_ = f"""What's langchain? Here's the langchain README:

View File

@@ -2,7 +2,7 @@
import json
import os
from typing import Any, Optional, cast
from typing import Annotated, Any, Optional, cast
import openai
import pytest
@@ -13,7 +13,7 @@ from langchain_core.messages import (
BaseMessageChunk,
)
from pydantic import BaseModel
from typing_extensions import Annotated, TypedDict
from typing_extensions import TypedDict
from langchain_openai import ChatOpenAI

View File

@@ -1,7 +1,5 @@
"""Standard LangChain interface tests for Responses API"""
from typing import Type
import pytest
from langchain_core.language_models import BaseChatModel
@@ -11,7 +9,7 @@ from tests.integration_tests.chat_models.test_base_standard import TestOpenAISta
class TestOpenAIResponses(TestOpenAIStandard):
@property
def chat_model_class(self) -> Type[BaseChatModel]:
def chat_model_class(self) -> type[BaseChatModel]:
return ChatOpenAI
@property

View File

@@ -1,7 +1,5 @@
"""Standard LangChain interface tests"""
from typing import Type
from langchain_core.embeddings import Embeddings
from langchain_tests.integration_tests.embeddings import EmbeddingsIntegrationTests
@@ -10,7 +8,7 @@ from langchain_openai import OpenAIEmbeddings
class TestOpenAIStandard(EmbeddingsIntegrationTests):
@property
def embeddings_class(self) -> Type[Embeddings]:
def embeddings_class(self) -> type[Embeddings]:
return OpenAIEmbeddings
@property

View File

@@ -1,7 +1,8 @@
"""Test AzureOpenAI wrapper."""
import os
from typing import Any, Generator
from collections.abc import Generator
from typing import Any
import pytest
from langchain_core.callbacks import CallbackManager

View File

@@ -1,6 +1,6 @@
"""Test OpenAI llm."""
from typing import Generator
from collections.abc import Generator
import pytest
from langchain_core.callbacks import CallbackManager

View File

@@ -1,7 +1,5 @@
"""Standard LangChain interface tests"""
from typing import Tuple, Type
import pytest
from langchain_core.language_models import BaseChatModel
from langchain_core.tools import BaseTool
@@ -12,7 +10,7 @@ from langchain_openai import AzureChatOpenAI
class TestOpenAIStandard(ChatModelUnitTests):
@property
def chat_model_class(self) -> Type[BaseChatModel]:
def chat_model_class(self) -> type[BaseChatModel]:
return AzureChatOpenAI
@property
@@ -30,7 +28,7 @@ class TestOpenAIStandard(ChatModelUnitTests):
super().test_bind_tool_pydantic(model, my_adder_tool)
@property
def init_from_env_params(self) -> Tuple[dict, dict, dict]:
def init_from_env_params(self) -> tuple[dict, dict, dict]:
return (
{
"AZURE_OPENAI_API_KEY": "api_key",

View File

@@ -3,7 +3,7 @@
import json
from functools import partial
from types import TracebackType
from typing import Any, Dict, List, Literal, Optional, Type, Union, cast
from typing import Any, Literal, Optional, Union, cast
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -241,7 +241,7 @@ class MockAsyncContextManager:
async def __aexit__(
self,
exc_type: Optional[Type[BaseException]],
exc_type: Optional[type[BaseException]],
exc: Optional[BaseException],
tb: Optional[TracebackType],
) -> None:
@@ -270,7 +270,7 @@ class MockSyncContextManager:
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_type: Optional[type[BaseException]],
exc: Optional[BaseException],
tb: Optional[TracebackType],
) -> None:
@@ -382,7 +382,7 @@ DEEPSEEK_STREAM_DATA = """{"id":"d3610c24e6b42518a7883ea57c3ea2c3","choices":[{"
@pytest.fixture
def mock_deepseek_completion() -> List[Dict]:
def mock_deepseek_completion() -> list[dict]:
list_chunk_data = DEEPSEEK_STREAM_DATA.split("\n")
result_list = []
for msg in list_chunk_data:
@@ -450,7 +450,7 @@ OPENAI_STREAM_DATA = """{"id":"chatcmpl-9nhARrdUiJWEMd5plwV1Gc9NCjb9M","object":
@pytest.fixture
def mock_openai_completion() -> List[Dict]:
def mock_openai_completion() -> list[dict]:
list_chunk_data = OPENAI_STREAM_DATA.split("\n")
result_list = []
for msg in list_chunk_data:
@@ -615,7 +615,7 @@ def test_openai_invoke_name(mock_client: MagicMock) -> None:
def test_custom_token_counting() -> None:
def token_encoder(text: str) -> List[int]:
def token_encoder(text: str) -> list[int]:
return [1, 2, 3]
llm = ChatOpenAI(custom_get_token_ids=token_encoder)
@@ -662,8 +662,8 @@ class MakeASandwich(BaseModel):
bread_type: str
cheese_type: str
condiments: List[str]
vegetables: List[str]
condiments: list[str]
vegetables: list[str]
@pytest.mark.parametrize(
@@ -695,7 +695,7 @@ def test_bind_tools_tool_choice(tool_choice: Any, strict: Optional[bool]) -> Non
@pytest.mark.parametrize("include_raw", [True, False])
@pytest.mark.parametrize("strict", [True, False, None])
def test_with_structured_output(
schema: Union[Type, Dict[str, Any], None],
schema: Union[type, dict[str, Any], None],
method: Literal["function_calling", "json_mode", "json_schema"],
include_raw: bool,
strict: Optional[bool],
@@ -787,7 +787,7 @@ class Foo(BaseModel):
# FooV1
],
)
def test_schema_from_with_structured_output(schema: Type) -> None:
def test_schema_from_with_structured_output(schema: type) -> None:
"""Test schema from with_structured_output."""
llm = ChatOpenAI(model="gpt-4o")

View File

@@ -1,7 +1,5 @@
"""Standard LangChain interface tests"""
from typing import Tuple, Type
from langchain_core.language_models import BaseChatModel
from langchain_tests.unit_tests import ChatModelUnitTests
@@ -10,11 +8,11 @@ from langchain_openai import ChatOpenAI
class TestOpenAIStandard(ChatModelUnitTests):
@property
def chat_model_class(self) -> Type[BaseChatModel]:
def chat_model_class(self) -> type[BaseChatModel]:
return ChatOpenAI
@property
def init_from_env_params(self) -> Tuple[dict, dict, dict]:
def init_from_env_params(self) -> tuple[dict, dict, dict]:
return (
{
"OPENAI_API_KEY": "api_key",

View File

@@ -1,7 +1,5 @@
"""Standard LangChain interface tests"""
from typing import Tuple, Type
from langchain_core.language_models import BaseChatModel
from langchain_tests.unit_tests import ChatModelUnitTests
@@ -10,7 +8,7 @@ from langchain_openai import ChatOpenAI
class TestOpenAIResponses(ChatModelUnitTests):
@property
def chat_model_class(self) -> Type[BaseChatModel]:
def chat_model_class(self) -> type[BaseChatModel]:
return ChatOpenAI
@property
@@ -18,7 +16,7 @@ class TestOpenAIResponses(ChatModelUnitTests):
return {"use_responses_api": True}
@property
def init_from_env_params(self) -> Tuple[dict, dict, dict]:
def init_from_env_params(self) -> tuple[dict, dict, dict]:
return (
{
"OPENAI_API_KEY": "api_key",

View File

@@ -1,5 +1,3 @@
from typing import Tuple, Type
from langchain_core.embeddings import Embeddings
from langchain_tests.unit_tests.embeddings import EmbeddingsUnitTests
@@ -8,7 +6,7 @@ from langchain_openai import AzureOpenAIEmbeddings
class TestAzureOpenAIStandard(EmbeddingsUnitTests):
@property
def embeddings_class(self) -> Type[Embeddings]:
def embeddings_class(self) -> type[Embeddings]:
return AzureOpenAIEmbeddings
@property
@@ -16,7 +14,7 @@ class TestAzureOpenAIStandard(EmbeddingsUnitTests):
return {"api_key": "api_key", "azure_endpoint": "https://endpoint.com"}
@property
def init_from_env_params(self) -> Tuple[dict, dict, dict]:
def init_from_env_params(self) -> tuple[dict, dict, dict]:
return (
{
"AZURE_OPENAI_API_KEY": "api_key",

View File

@@ -1,7 +1,5 @@
"""Standard LangChain interface tests"""
from typing import Tuple, Type
from langchain_core.embeddings import Embeddings
from langchain_tests.unit_tests.embeddings import EmbeddingsUnitTests
@@ -10,11 +8,11 @@ from langchain_openai import OpenAIEmbeddings
class TestOpenAIStandard(EmbeddingsUnitTests):
@property
def embeddings_class(self) -> Type[Embeddings]:
def embeddings_class(self) -> type[Embeddings]:
return OpenAIEmbeddings
@property
def init_from_env_params(self) -> Tuple[dict, dict, dict]:
def init_from_env_params(self) -> tuple[dict, dict, dict]:
return (
{
"OPENAI_API_KEY": "api_key",

View File

@@ -1,7 +1,7 @@
"""A fake callback handler for testing purposes."""
from itertools import chain
from typing import Any, Dict, List, Optional, Union
from typing import Any, Optional, Union
from uuid import UUID
from langchain_core.callbacks.base import AsyncCallbackHandler, BaseCallbackHandler
@@ -15,7 +15,7 @@ class BaseFakeCallbackHandler(BaseModel):
starts: int = 0
ends: int = 0
errors: int = 0
errors_args: List[Any] = []
errors_args: list[Any] = []
text: int = 0
ignore_llm_: bool = False
ignore_chain_: bool = False
@@ -195,8 +195,8 @@ class FakeCallbackHandler(BaseCallbackHandler, BaseFakeCallbackHandlerMixin):
class FakeCallbackHandlerWithChatStart(FakeCallbackHandler):
def on_chat_model_start(
self,
serialized: Dict[str, Any],
messages: List[List[BaseMessage]],
serialized: dict[str, Any],
messages: list[list[BaseMessage]],
*,
run_id: UUID,
parent_run_id: Optional[UUID] = None,

View File

@@ -1,5 +1,4 @@
import os
from typing import List
import pytest
@@ -65,7 +64,7 @@ def test_get_token_ids(model: str) -> None:
def test_custom_token_counting() -> None:
def token_encoder(text: str) -> List[int]:
def token_encoder(text: str) -> list[int]:
return [1, 2, 3]
llm = OpenAI(custom_get_token_ids=token_encoder)

View File

@@ -1,4 +1,4 @@
from typing import Type, cast
from typing import cast
import pytest
from langchain_core.load import dumpd
@@ -72,7 +72,7 @@ def test_azure_openai_embeddings_secrets() -> None:
@pytest.mark.parametrize(
"model_class", [AzureChatOpenAI, AzureOpenAI, AzureOpenAIEmbeddings]
)
def test_azure_openai_api_key_is_secret_string(model_class: Type) -> None:
def test_azure_openai_api_key_is_secret_string(model_class: type) -> None:
"""Test that the API key is stored as a SecretStr."""
model = model_class(
openai_api_key="secret-api-key",
@@ -88,7 +88,7 @@ def test_azure_openai_api_key_is_secret_string(model_class: Type) -> None:
"model_class", [AzureChatOpenAI, AzureOpenAI, AzureOpenAIEmbeddings]
)
def test_azure_openai_api_key_masked_when_passed_from_env(
model_class: Type, monkeypatch: MonkeyPatch, capsys: CaptureFixture
model_class: type, monkeypatch: MonkeyPatch, capsys: CaptureFixture
) -> None:
"""Test that the API key is masked when passed from an environment variable."""
monkeypatch.setenv("AZURE_OPENAI_API_KEY", "secret-api-key")
@@ -109,7 +109,7 @@ def test_azure_openai_api_key_masked_when_passed_from_env(
"model_class", [AzureChatOpenAI, AzureOpenAI, AzureOpenAIEmbeddings]
)
def test_azure_openai_api_key_masked_when_passed_via_constructor(
model_class: Type, capsys: CaptureFixture
model_class: type, capsys: CaptureFixture
) -> None:
"""Test that the API key is masked when passed via the constructor."""
model = model_class(
@@ -133,7 +133,7 @@ def test_azure_openai_api_key_masked_when_passed_via_constructor(
"model_class", [AzureChatOpenAI, AzureOpenAI, AzureOpenAIEmbeddings]
)
def test_azure_openai_uses_actual_secret_value_from_secretstr(
model_class: Type,
model_class: type,
) -> None:
"""Test that the actual secret value is correctly retrieved."""
model = model_class(
@@ -147,7 +147,7 @@ def test_azure_openai_uses_actual_secret_value_from_secretstr(
@pytest.mark.parametrize("model_class", [ChatOpenAI, OpenAI, OpenAIEmbeddings])
def test_openai_api_key_is_secret_string(model_class: Type) -> None:
def test_openai_api_key_is_secret_string(model_class: type) -> None:
"""Test that the API key is stored as a SecretStr."""
model = model_class(openai_api_key="secret-api-key")
assert isinstance(model.openai_api_key, SecretStr)
@@ -155,7 +155,7 @@ def test_openai_api_key_is_secret_string(model_class: Type) -> None:
@pytest.mark.parametrize("model_class", [ChatOpenAI, OpenAI, OpenAIEmbeddings])
def test_openai_api_key_masked_when_passed_from_env(
model_class: Type, monkeypatch: MonkeyPatch, capsys: CaptureFixture
model_class: type, monkeypatch: MonkeyPatch, capsys: CaptureFixture
) -> None:
"""Test that the API key is masked when passed from an environment variable."""
monkeypatch.setenv("OPENAI_API_KEY", "secret-api-key")
@@ -168,7 +168,7 @@ def test_openai_api_key_masked_when_passed_from_env(
@pytest.mark.parametrize("model_class", [ChatOpenAI, OpenAI, OpenAIEmbeddings])
def test_openai_api_key_masked_when_passed_via_constructor(
model_class: Type, capsys: CaptureFixture
model_class: type, capsys: CaptureFixture
) -> None:
"""Test that the API key is masked when passed via the constructor."""
model = model_class(openai_api_key="secret-api-key")
@@ -179,14 +179,14 @@ def test_openai_api_key_masked_when_passed_via_constructor(
@pytest.mark.parametrize("model_class", [ChatOpenAI, OpenAI, OpenAIEmbeddings])
def test_openai_uses_actual_secret_value_from_secretstr(model_class: Type) -> None:
def test_openai_uses_actual_secret_value_from_secretstr(model_class: type) -> None:
"""Test that the actual secret value is correctly retrieved."""
model = model_class(openai_api_key="secret-api-key")
assert cast(SecretStr, model.openai_api_key).get_secret_value() == "secret-api-key"
@pytest.mark.parametrize("model_class", [AzureChatOpenAI, AzureOpenAI])
def test_azure_serialized_secrets(model_class: Type) -> None:
def test_azure_serialized_secrets(model_class: type) -> None:
"""Test that the actual secret value is correctly retrieved."""
model = model_class(
openai_api_key="secret-api-key", api_version="foo", azure_endpoint="foo"