Merge branch 'master' into eugene/0.2rc

pull/21191/head
Eugene Yurtsev 2 months ago
commit 35e857131e

@ -1526,7 +1526,7 @@ ASTRA_DB_CACHE_DEFAULT_COLLECTION_NAME = "langchain_astradb_cache"
@deprecated(
since="0.0.28",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_astradb.AstraDBCache",
)
class AstraDBCache(BaseCache):
@ -1731,7 +1731,7 @@ def _async_lru_cache(maxsize: int = 128, typed: bool = False) -> Callable:
@deprecated(
since="0.0.28",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_astradb.AstraDBSemanticCache",
)
class AstraDBSemanticCache(BaseCache):

@ -65,7 +65,7 @@ def _get_message_data(service: Any, message: Any) -> ChatSession:
@deprecated(
since="0.0.32",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_community.GMailLoader",
)
class GMailLoader(BaseChatLoader):

@ -26,7 +26,7 @@ DEFAULT_COLLECTION_NAME = "langchain_message_store"
@deprecated(
since="0.0.25",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_astradb.AstraDBChatMessageHistory",
)
class AstraDBChatMessageHistory(BaseChatMessageHistory):

@ -2,11 +2,10 @@
from __future__ import annotations
import json
import typing
import uuid
from typing import List
from typing import TYPE_CHECKING, List, Optional
if typing.TYPE_CHECKING:
if TYPE_CHECKING:
from cassandra.cluster import Session
from langchain_core.chat_history import BaseChatMessageHistory
@ -26,8 +25,8 @@ class CassandraChatMessageHistory(BaseChatMessageHistory):
Args:
session_id: arbitrary key that is used to store the messages
of a single chat session.
session: a Cassandra `Session` object (an open DB connection)
keyspace: name of the keyspace to use.
session: Cassandra driver session. If not provided, it is resolved from cassio.
keyspace: Cassandra key space. If not provided, it is resolved from cassio.
table_name: name of the table to use.
ttl_seconds: time-to-live (seconds) for automatic expiration
of stored entries. None (default) for no expiration.
@ -36,10 +35,10 @@ class CassandraChatMessageHistory(BaseChatMessageHistory):
def __init__(
self,
session_id: str,
session: Session,
keyspace: str,
session: Optional[Session] = None,
keyspace: Optional[str] = None,
table_name: str = DEFAULT_TABLE_NAME,
ttl_seconds: typing.Optional[int] = DEFAULT_TTL_SECONDS,
ttl_seconds: Optional[int] = DEFAULT_TTL_SECONDS,
) -> None:
try:
from cassio.table import ClusteredCassandraTable
@ -74,7 +73,11 @@ class CassandraChatMessageHistory(BaseChatMessageHistory):
return messages
def add_message(self, message: BaseMessage) -> None:
"""Write a message to the table"""
"""Write a message to the table
Args:
message: A message to write.
"""
this_row_id = uuid.uuid1()
self.table.put(
partition_id=self.session_id,

@ -18,7 +18,7 @@ DEFAULT_COLLECTION_NAME = "message_store"
@deprecated(
since="0.0.25",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_mongodb.MongoDBChatMessageHistory",
)
class MongoDBChatMessageHistory(BaseChatMessageHistory):

@ -73,7 +73,7 @@ def convert_messages_to_prompt_anthropic(
@deprecated(
since="0.0.28",
removal="0.2",
removal="0.3",
alternative_import="langchain_anthropic.ChatAnthropic",
)
class ChatAnthropic(BaseChatModel, _AnthropicCommon):

@ -19,7 +19,7 @@ logger = logging.getLogger(__name__)
@deprecated(
since="0.0.10",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_openai.AzureChatOpenAI",
)
class AzureChatOpenAI(ChatOpenAI):

@ -96,7 +96,7 @@ def get_cohere_chat_request(
@deprecated(
since="0.0.30", removal="0.2.0", alternative_import="langchain_cohere.ChatCohere"
since="0.0.30", removal="0.3.0", alternative_import="langchain_cohere.ChatCohere"
)
class ChatCohere(BaseChatModel, BaseCohere):
"""`Cohere` chat large language models.

@ -81,7 +81,7 @@ def convert_dict_to_message(_dict: Any) -> BaseMessage:
@deprecated(
since="0.0.26",
removal="0.2",
removal="0.3",
alternative_import="langchain_fireworks.ChatFireworks",
)
class ChatFireworks(BaseChatModel):

@ -145,7 +145,7 @@ def _convert_delta_to_message_chunk(
@deprecated(
since="0.0.10", removal="0.2.0", alternative_import="langchain_openai.ChatOpenAI"
since="0.0.10", removal="0.3.0", alternative_import="langchain_openai.ChatOpenAI"
)
class ChatOpenAI(BaseChatModel):
"""`OpenAI` Chat large language models API.

@ -11,7 +11,7 @@ from langchain_community.llms.solar import SOLAR_SERVICE_URL_BASE, SolarCommon
@deprecated(
since="0.0.34", removal="0.2.0", alternative_import="langchain_upstage.ChatUpstage"
since="0.0.34", removal="0.3.0", alternative_import="langchain_upstage.ChatUpstage"
)
class SolarChat(SolarCommon, ChatOpenAI):
"""Wrapper around Solar large language models.

@ -205,7 +205,7 @@ def _get_question(messages: List[BaseMessage]) -> HumanMessage:
@deprecated(
since="0.0.12",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_vertexai.ChatVertexAI",
)
class ChatVertexAI(_VertexAICommon, BaseChatModel):

@ -27,7 +27,7 @@ logger = logging.getLogger(__name__)
@deprecated(
since="0.0.29",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_astradb.AstraDBLoader",
)
class AstraDBLoader(BaseLoader):

@ -14,7 +14,7 @@ if TYPE_CHECKING:
@deprecated(
since="0.0.32",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_community.BigQueryLoader",
)
class BigQueryLoader(BaseLoader):

@ -29,7 +29,7 @@ logger = logging.getLogger(__name__)
@deprecated(
since="0.0.24",
removal="0.2.0",
removal="0.3.0",
alternative_import="docugami_langchain.DocugamiLoader",
)
class DocugamiLoader(BaseLoader, BaseModel):

@ -13,7 +13,7 @@ logger = logging.getLogger(__name__)
@deprecated(
since="0.0.32",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_community.GCSDirectoryLoader",
)
class GCSDirectoryLoader(BaseLoader):

@ -12,7 +12,7 @@ from langchain_community.utilities.vertexai import get_client_info
@deprecated(
since="0.0.32",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_community.GCSFileLoader",
)
class GCSFileLoader(BaseLoader):

@ -15,7 +15,7 @@ if TYPE_CHECKING:
@deprecated(
since="0.0.32",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_community.SpeechToTextLoader",
)
class GoogleSpeechToTextLoader(BaseLoader):

@ -22,7 +22,7 @@ SCOPES = ["https://www.googleapis.com/auth/drive.readonly"]
@deprecated(
since="0.0.32",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_community.GoogleDriveLoader",
)
class GoogleDriveLoader(BaseLoader, BaseModel):

@ -36,7 +36,7 @@ class DocAIParsingResults:
@deprecated(
since="0.0.32",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_community.DocAIParser",
)
class DocAIParser(BaseBlobParser):

@ -8,7 +8,7 @@ from langchain_community.utilities.vertexai import get_client_info
@deprecated(
since="0.0.32",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_community.DocAIParser",
)
class GoogleTranslateTransformer(BaseDocumentTransformer):

@ -16,7 +16,7 @@ from langchain_community.utils.openai import is_openai_v1
@deprecated(
since="0.0.9",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_openai.AzureOpenAIEmbeddings",
)
class AzureOpenAIEmbeddings(OpenAIEmbeddings):

@ -10,7 +10,7 @@ from langchain_community.llms.cohere import _create_retry_decorator
@deprecated(
since="0.0.30",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_cohere.CohereEmbeddings",
)
class CohereEmbeddings(BaseModel, Embeddings):

@ -140,7 +140,7 @@ async def async_embed_with_retry(embeddings: OpenAIEmbeddings, **kwargs: Any) ->
@deprecated(
since="0.0.9",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_openai.OpenAIEmbeddings",
)
class OpenAIEmbeddings(BaseModel, Embeddings):

@ -46,7 +46,7 @@ def embed_with_retry(embeddings: SolarEmbeddings, *args: Any, **kwargs: Any) ->
@deprecated(
since="0.0.34", removal="0.2.0", alternative_import="langchain_upstage.ChatUpstage"
since="0.0.34", removal="0.3.0", alternative_import="langchain_upstage.ChatUpstage"
)
class SolarEmbeddings(BaseModel, Embeddings):
"""Solar's embedding service.

@ -22,7 +22,7 @@ _MIN_BATCH_SIZE = 5
@deprecated(
since="0.0.12",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_vertexai.VertexAIEmbeddings",
)
class VertexAIEmbeddings(_VertexAICommon, Embeddings):

@ -61,7 +61,7 @@ def embed_with_retry(embeddings: VoyageEmbeddings, **kwargs: Any) -> Any:
@deprecated(
since="0.0.29",
removal="0.2",
removal="0.3",
alternative_import="langchain_voyageai.VoyageAIEmbeddings",
)
class VoyageEmbeddings(BaseModel, Embeddings):

@ -172,7 +172,7 @@ def _import_databricks() -> Type[BaseLLM]:
def _import_databricks_chat() -> Any:
warn_deprecated(
since="0.0.22",
removal="0.2",
removal="0.3",
alternative_import="langchain_community.chat_models.ChatDatabricks",
)
from langchain_community.chat_models.databricks import ChatDatabricks
@ -342,7 +342,7 @@ def _import_mlflow() -> Type[BaseLLM]:
def _import_mlflow_chat() -> Any:
warn_deprecated(
since="0.0.22",
removal="0.2",
removal="0.3",
alternative_import="langchain_community.chat_models.ChatMlflow",
)
from langchain_community.chat_models.mlflow import ChatMlflow

@ -150,7 +150,7 @@ class _AnthropicCommon(BaseLanguageModel):
@deprecated(
since="0.0.28",
removal="0.2",
removal="0.3",
alternative_import="langchain_anthropic.AnthropicLLM",
)
class Anthropic(LLM, _AnthropicCommon):

@ -71,7 +71,7 @@ def acompletion_with_retry(llm: Cohere, **kwargs: Any) -> Any:
@deprecated(
since="0.0.30", removal="0.2.0", alternative_import="langchain_cohere.BaseCohere"
since="0.0.30", removal="0.3.0", alternative_import="langchain_cohere.BaseCohere"
)
class BaseCohere(Serializable):
"""Base class for Cohere models."""
@ -122,7 +122,7 @@ class BaseCohere(Serializable):
@deprecated(
since="0.1.14", removal="0.2.0", alternative_import="langchain_cohere.Cohere"
since="0.1.14", removal="0.3.0", alternative_import="langchain_cohere.Cohere"
)
class Cohere(LLM, BaseCohere):
"""Cohere large language models.

@ -29,7 +29,7 @@ def _stream_response_to_generation_chunk(
@deprecated(
since="0.0.26",
removal="0.2",
removal="0.3",
alternative_import="langchain_fireworks.Fireworks",
)
class Fireworks(BaseLLM):

@ -20,7 +20,7 @@ VALID_TASKS_DICT = {
}
@deprecated("0.0.21", removal="0.2.0", alternative="HuggingFaceEndpoint")
@deprecated("0.0.21", removal="0.3.0", alternative="HuggingFaceEndpoint")
class HuggingFaceHub(LLM):
"""HuggingFaceHub models.
! This class is deprecated, you should use HuggingFaceEndpoint instead.

@ -14,7 +14,7 @@ from langchain_core.utils import get_pydantic_field_names
logger = logging.getLogger(__name__)
@deprecated("0.0.21", removal="0.2.0", alternative="HuggingFaceEndpoint")
@deprecated("0.0.21", removal="0.3.0", alternative="HuggingFaceEndpoint")
class HuggingFaceTextGenInference(LLM):
"""
HuggingFace text generation API.

@ -726,7 +726,7 @@ class BaseOpenAI(BaseLLM):
@deprecated(
since="0.0.10", removal="0.2.0", alternative_import="langchain_openai.OpenAI"
since="0.0.10", removal="0.3.0", alternative_import="langchain_openai.OpenAI"
)
class OpenAI(BaseOpenAI):
"""OpenAI large language models.
@ -755,7 +755,7 @@ class OpenAI(BaseOpenAI):
@deprecated(
since="0.0.10", removal="0.2.0", alternative_import="langchain_openai.AzureOpenAI"
since="0.0.10", removal="0.3.0", alternative_import="langchain_openai.AzureOpenAI"
)
class AzureOpenAI(BaseOpenAI):
"""Azure-specific OpenAI large language models.
@ -963,7 +963,7 @@ class AzureOpenAI(BaseOpenAI):
@deprecated(
since="0.0.1",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_openai.ChatOpenAI",
)
class OpenAIChat(BaseLLM):

@ -18,7 +18,7 @@ logger = logging.getLogger(__name__)
@deprecated(
since="0.0.12", removal="0.2", alternative_import="langchain_together.Together"
since="0.0.12", removal="0.3", alternative_import="langchain_together.Together"
)
class Together(LLM):
"""LLM models from `Together`.

@ -203,7 +203,7 @@ class _VertexAICommon(_VertexAIBase):
@deprecated(
since="0.0.12",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_vertexai.VertexAI",
)
class VertexAI(_VertexAICommon, BaseLLM):
@ -393,7 +393,7 @@ class VertexAI(_VertexAICommon, BaseLLM):
@deprecated(
since="0.0.12",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_vertexai.VertexAIModelGarden",
)
class VertexAIModelGarden(_VertexAIBase, BaseLLM):

@ -13,7 +13,7 @@ logger = logging.getLogger(__name__)
@deprecated(
since="0.0.18", removal="0.2", alternative_import="langchain_ibm.WatsonxLLM"
since="0.0.18", removal="0.3", alternative_import="langchain_ibm.WatsonxLLM"
)
class WatsonxLLM(BaseLLM):
"""

@ -43,7 +43,7 @@ def _get_docs(response: Any) -> List[Document]:
@deprecated(
since="0.0.30",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_cohere.CohereRagRetriever",
)
class CohereRagRetriever(BaseRetriever):

@ -24,7 +24,7 @@ if TYPE_CHECKING:
@deprecated(
since="0.0.32",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_community.DocumentAIWarehouseRetriever",
)
class GoogleDocumentAIWarehouseRetriever(BaseRetriever):

@ -198,7 +198,7 @@ class _BaseGoogleVertexAISearchRetriever(BaseModel):
@deprecated(
since="0.0.33",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_community.VertexAISearchRetriever",
)
class GoogleVertexAISearchRetriever(BaseRetriever, _BaseGoogleVertexAISearchRetriever):
@ -398,7 +398,7 @@ class GoogleVertexAISearchRetriever(BaseRetriever, _BaseGoogleVertexAISearchRetr
@deprecated(
since="0.0.33",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_community.VertexAIMultiTurnSearchRetriever",
)
class GoogleVertexAIMultiTurnSearchRetriever(

@ -99,7 +99,7 @@ class AstraDBBaseStore(Generic[V], BaseStore[str, V], ABC):
@deprecated(
since="0.0.22",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_astradb.AstraDBStore",
)
class AstraDBStore(AstraDBBaseStore[Any]):
@ -167,7 +167,7 @@ class AstraDBStore(AstraDBBaseStore[Any]):
@deprecated(
since="0.0.22",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_astradb.AstraDBByteStore",
)
class AstraDBByteStore(AstraDBBaseStore[bytes], ByteStore):

@ -39,7 +39,7 @@ def _encoding_file_extension_map(encoding: texttospeech.AudioEncoding) -> Option
@deprecated(
since="0.0.33",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_community.TextToSpeechTool",
)
class GoogleCloudTextToSpeechTool(BaseTool):

@ -18,7 +18,7 @@ class GooglePlacesSchema(BaseModel):
@deprecated(
since="0.0.33",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_community.GooglePlacesTool",
)
class GooglePlacesTool(BaseTool):

@ -11,7 +11,7 @@ from langchain_community.utilities.google_search import GoogleSearchAPIWrapper
@deprecated(
since="0.0.33",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_community.GoogleSearchRun",
)
class GoogleSearchRun(BaseTool):
@ -36,7 +36,7 @@ class GoogleSearchRun(BaseTool):
@deprecated(
since="0.0.33",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_community.GoogleSearchResults",
)
class GoogleSearchResults(BaseTool):

@ -14,7 +14,7 @@ from langchain_community.utilities.metaphor_search import MetaphorSearchAPIWrapp
@deprecated(
since="0.0.15",
removal="0.2.0",
removal="0.3.0",
alternative="langchain_exa.ExaSearchResults",
)
class MetaphorSearchResults(BaseTool):

@ -10,7 +10,7 @@ from langchain_core.utils import get_from_dict_or_env
@deprecated(
since="0.0.33",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_community.GooglePlacesAPIWrapper",
)
class GooglePlacesAPIWrapper(BaseModel):

@ -9,7 +9,7 @@ from langchain_core.utils import get_from_dict_or_env
@deprecated(
since="0.0.33",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_community.GoogleSearchAPIWrapper",
)
class GoogleSearchAPIWrapper(BaseModel):

@ -283,7 +283,7 @@ class SQLDatabase:
return sorted(self._include_tables)
return sorted(self._all_tables - self._ignore_tables)
@deprecated("0.0.1", alternative="get_usable_table_names", removal="0.2.0")
@deprecated("0.0.1", alternative="get_usable_table_names", removal="0.3.0")
def get_table_names(self) -> Iterable[str]:
"""Get names of tables available."""
return self.get_usable_table_names()

@ -67,7 +67,7 @@ def _unique_list(lst: List[T], key: Callable[[T], U]) -> List[T]:
@deprecated(
since="0.0.21",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_astradb.AstraDBVectorStore",
)
class AstraDB(VectorStore):

@ -38,7 +38,7 @@ _vector_table_lock = Lock() # process-wide BigQueryVectorSearch table lock
@deprecated(
since="0.0.33",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_community.BigQueryVectorSearch",
)
class BigQueryVectorSearch(VectorStore):

@ -28,7 +28,7 @@ logger = logging.getLogger(__name__)
@deprecated(
since="0.0.12",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_google_vertexai.VectorSearchVectorStore",
)
class MatchingEngine(VectorStore):

@ -35,7 +35,7 @@ DEFAULT_INSERT_BATCH_SIZE = 100
@deprecated(
since="0.0.25",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_mongodb.MongoDBAtlasVectorSearch",
)
class MongoDBAtlasVectorSearch(VectorStore):

@ -43,7 +43,7 @@ def _is_pinecone_v3() -> bool:
@deprecated(
since="0.0.18", removal="0.2.0", alternative_import="langchain_pinecone.Pinecone"
since="0.0.18", removal="0.3.0", alternative_import="langchain_pinecone.Pinecone"
)
class Pinecone(VectorStore):
"""`Pinecone` vector store.

@ -207,7 +207,7 @@ class BaseLanguageModel(
"""Implement this if there is a way of steering the model to generate responses that match a given schema.""" # noqa: E501
raise NotImplementedError()
@deprecated("0.1.7", alternative="invoke", removal="0.2.0")
@deprecated("0.1.7", alternative="invoke", removal="0.3.0")
@abstractmethod
def predict(
self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any
@ -228,7 +228,7 @@ class BaseLanguageModel(
Top model prediction as a string.
"""
@deprecated("0.1.7", alternative="invoke", removal="0.2.0")
@deprecated("0.1.7", alternative="invoke", removal="0.3.0")
@abstractmethod
def predict_messages(
self,
@ -253,7 +253,7 @@ class BaseLanguageModel(
Top model prediction as a message.
"""
@deprecated("0.1.7", alternative="ainvoke", removal="0.2.0")
@deprecated("0.1.7", alternative="ainvoke", removal="0.3.0")
@abstractmethod
async def apredict(
self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any
@ -274,7 +274,7 @@ class BaseLanguageModel(
Top model prediction as a string.
"""
@deprecated("0.1.7", alternative="ainvoke", removal="0.2.0")
@deprecated("0.1.7", alternative="ainvoke", removal="0.3.0")
@abstractmethod
async def apredict_messages(
self,

@ -797,7 +797,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
break
yield item # type: ignore[misc]
@deprecated("0.1.7", alternative="invoke", removal="0.2.0")
@deprecated("0.1.7", alternative="invoke", removal="0.3.0")
def __call__(
self,
messages: List[BaseMessage],
@ -829,13 +829,13 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
else:
raise ValueError("Unexpected generation type")
@deprecated("0.1.7", alternative="invoke", removal="0.2.0")
@deprecated("0.1.7", alternative="invoke", removal="0.3.0")
def call_as_llm(
self, message: str, stop: Optional[List[str]] = None, **kwargs: Any
) -> str:
return self.predict(message, stop=stop, **kwargs)
@deprecated("0.1.7", alternative="invoke", removal="0.2.0")
@deprecated("0.1.7", alternative="invoke", removal="0.3.0")
def predict(
self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any
) -> str:
@ -849,7 +849,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
else:
raise ValueError("Cannot use predict when output is not a string.")
@deprecated("0.1.7", alternative="invoke", removal="0.2.0")
@deprecated("0.1.7", alternative="invoke", removal="0.3.0")
def predict_messages(
self,
messages: List[BaseMessage],
@ -863,7 +863,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
_stop = list(stop)
return self(messages, stop=_stop, **kwargs)
@deprecated("0.1.7", alternative="ainvoke", removal="0.2.0")
@deprecated("0.1.7", alternative="ainvoke", removal="0.3.0")
async def apredict(
self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any
) -> str:
@ -879,7 +879,7 @@ class BaseChatModel(BaseLanguageModel[BaseMessage], ABC):
else:
raise ValueError("Cannot use predict when output is not a string.")
@deprecated("0.1.7", alternative="ainvoke", removal="0.2.0")
@deprecated("0.1.7", alternative="ainvoke", removal="0.3.0")
async def apredict_messages(
self,
messages: List[BaseMessage],

@ -1064,7 +1064,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
generations = [existing_prompts[i] for i in range(len(prompts))]
return LLMResult(generations=generations, llm_output=llm_output, run=run_info)
@deprecated("0.1.7", alternative="invoke", removal="0.2.0")
@deprecated("0.1.7", alternative="invoke", removal="0.3.0")
def __call__(
self,
prompt: str,
@ -1116,7 +1116,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
)
return result.generations[0][0].text
@deprecated("0.1.7", alternative="invoke", removal="0.2.0")
@deprecated("0.1.7", alternative="invoke", removal="0.3.0")
def predict(
self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any
) -> str:
@ -1126,7 +1126,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
_stop = list(stop)
return self(text, stop=_stop, **kwargs)
@deprecated("0.1.7", alternative="invoke", removal="0.2.0")
@deprecated("0.1.7", alternative="invoke", removal="0.3.0")
def predict_messages(
self,
messages: List[BaseMessage],
@ -1142,7 +1142,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
content = self(text, stop=_stop, **kwargs)
return AIMessage(content=content)
@deprecated("0.1.7", alternative="ainvoke", removal="0.2.0")
@deprecated("0.1.7", alternative="ainvoke", removal="0.3.0")
async def apredict(
self, text: str, *, stop: Optional[Sequence[str]] = None, **kwargs: Any
) -> str:
@ -1152,7 +1152,7 @@ class BaseLLM(BaseLanguageModel[str], ABC):
_stop = list(stop)
return await self._call_async(text, stop=_stop, **kwargs)
@deprecated("0.1.7", alternative="ainvoke", removal="0.2.0")
@deprecated("0.1.7", alternative="ainvoke", removal="0.3.0")
async def apredict_messages(
self,
messages: List[BaseMessage],

@ -14,7 +14,7 @@ from langchain_core.outputs import LLMResult
from langchain_core.pydantic_v1 import BaseModel, Field, root_validator
@deprecated("0.1.0", alternative="Use string instead.", removal="0.2.0")
@deprecated("0.1.0", alternative="Use string instead.", removal="0.3.0")
def RunTypeEnum() -> Type[RunTypeEnumDep]:
"""RunTypeEnum."""
warnings.warn(
@ -25,7 +25,7 @@ def RunTypeEnum() -> Type[RunTypeEnumDep]:
return RunTypeEnumDep
@deprecated("0.1.0", removal="0.2.0")
@deprecated("0.1.0", removal="0.3.0")
class TracerSessionV1Base(BaseModel):
"""Base class for TracerSessionV1."""
@ -34,33 +34,33 @@ class TracerSessionV1Base(BaseModel):
extra: Optional[Dict[str, Any]] = None
@deprecated("0.1.0", removal="0.2.0")
@deprecated("0.1.0", removal="0.3.0")
class TracerSessionV1Create(TracerSessionV1Base):
"""Create class for TracerSessionV1."""
@deprecated("0.1.0", removal="0.2.0")
@deprecated("0.1.0", removal="0.3.0")
class TracerSessionV1(TracerSessionV1Base):
"""TracerSessionV1 schema."""
id: int
@deprecated("0.1.0", removal="0.2.0")
@deprecated("0.1.0", removal="0.3.0")
class TracerSessionBase(TracerSessionV1Base):
"""Base class for TracerSession."""
tenant_id: UUID
@deprecated("0.1.0", removal="0.2.0")
@deprecated("0.1.0", removal="0.3.0")
class TracerSession(TracerSessionBase):
"""TracerSessionV1 schema for the V2 API."""
id: UUID
@deprecated("0.1.0", alternative="Run", removal="0.2.0")
@deprecated("0.1.0", alternative="Run", removal="0.3.0")
class BaseRun(BaseModel):
"""Base class for Run."""
@ -76,7 +76,7 @@ class BaseRun(BaseModel):
error: Optional[str] = None
@deprecated("0.1.0", alternative="Run", removal="0.2.0")
@deprecated("0.1.0", alternative="Run", removal="0.3.0")
class LLMRun(BaseRun):
"""Class for LLMRun."""
@ -84,7 +84,7 @@ class LLMRun(BaseRun):
response: Optional[LLMResult] = None
@deprecated("0.1.0", alternative="Run", removal="0.2.0")
@deprecated("0.1.0", alternative="Run", removal="0.3.0")
class ChainRun(BaseRun):
"""Class for ChainRun."""
@ -95,7 +95,7 @@ class ChainRun(BaseRun):
child_tool_runs: List[ToolRun] = Field(default_factory=list)
@deprecated("0.1.0", alternative="Run", removal="0.2.0")
@deprecated("0.1.0", alternative="Run", removal="0.3.0")
class ToolRun(BaseRun):
"""Class for ToolRun."""

@ -78,7 +78,7 @@ def _rm_titles(kv: dict, prev_key: str = "") -> dict:
@deprecated(
"0.1.16",
alternative="langchain_core.utils.function_calling.convert_to_openai_function()",
removal="0.2.0",
removal="0.3.0",
)
def convert_pydantic_to_openai_function(
model: Type[BaseModel],
@ -102,7 +102,7 @@ def convert_pydantic_to_openai_function(
@deprecated(
"0.1.16",
alternative="langchain_core.utils.function_calling.convert_to_openai_tool()",
removal="0.2.0",
removal="0.3.0",
)
def convert_pydantic_to_openai_tool(
model: Type[BaseModel],
@ -213,7 +213,7 @@ def _get_python_function_required_args(function: Callable) -> List[str]:
@deprecated(
"0.1.16",
alternative="langchain_core.utils.function_calling.convert_to_openai_function()",
removal="0.2.0",
removal="0.3.0",
)
def convert_python_function_to_openai_function(
function: Callable,
@ -239,7 +239,7 @@ def convert_python_function_to_openai_function(
@deprecated(
"0.1.16",
alternative="langchain_core.utils.function_calling.convert_to_openai_function()",
removal="0.2.0",
removal="0.3.0",
)
def format_tool_to_openai_function(tool: BaseTool) -> FunctionDescription:
"""Format tool into the OpenAI function API."""
@ -269,7 +269,7 @@ def format_tool_to_openai_function(tool: BaseTool) -> FunctionDescription:
@deprecated(
"0.1.16",
alternative="langchain_core.utils.function_calling.convert_to_openai_tool()",
removal="0.2.0",
removal="0.3.0",
)
def format_tool_to_openai_tool(tool: BaseTool) -> ToolDescription:
"""Format tool into the OpenAI function API."""

@ -8,7 +8,7 @@ from langchain_core._api.deprecation import deprecated
@deprecated(
since="0.1.30",
removal="0.2",
removal="0.3",
message=(
"Using the hwchase17/langchain-hub "
"repo for prompts is deprecated. Please use "

@ -126,7 +126,7 @@ def _destrip(tool_input: Any) -> Any:
@deprecated(
since="0.0.54",
removal="0.2",
removal="0.3",
alternative_import="langchain_anthropic.experimental.ChatAnthropicTools",
)
class AnthropicFunctions(BaseChatModel):

@ -1,8 +1,7 @@
import importlib
import warnings
from typing import Any, Callable, Dict, Optional
from langchain_core._api import LangChainDeprecationWarning
from langchain_core._api import warn_deprecated
from langchain._api.interactive_env import is_interactive_env
@ -13,6 +12,33 @@ ALLOWED_TOP_LEVEL_PKGS = {
}
# For 0.1 releases keep this here
# Remove for 0.2 release so that deprecation warnings will
# be raised for all the new namespaces.
_NAMESPACES_WITH_DEPRECATION_WARNINGS_IN_0_1 = {
"langchain",
"langchain.adapters.openai",
"langchain.agents.agent_toolkits",
"langchain.callbacks",
"langchain.chat_models",
"langchain.docstore",
"langchain.document_loaders",
"langchain.document_transformers",
"langchain.embeddings",
"langchain.llms",
"langchain.memory.chat_message_histories",
"langchain.storage",
"langchain.tools",
"langchain.utilities",
"langchain.vectorstores",
}
def _should_deprecate_for_package(package: str) -> bool:
"""Should deprecate for this package?"""
return bool(package in _NAMESPACES_WITH_DEPRECATION_WARNINGS_IN_0_1)
def create_importer(
package: str,
*,
@ -83,12 +109,19 @@ def create_importer(
not is_interactive_env()
and deprecated_lookups
and name in deprecated_lookups
and _should_deprecate_for_package(package)
):
warnings.warn(
f"Importing {name} from {package} is deprecated. "
"Please replace the import with the following:\n"
f"from {new_module} import {name}",
category=LangChainDeprecationWarning,
warn_deprecated(
since="0.1",
pending=False,
removal="0.4",
message=(
f"Importing {name} from {package} is deprecated."
f"Please replace imports that look like:"
f"`from {package} import {name}`\n"
"with the following:\n "
f"from {new_module} import {name}"
),
)
return result
except Exception as e:
@ -100,12 +133,18 @@ def create_importer(
try:
module = importlib.import_module(fallback_module)
result = getattr(module, name)
if not is_interactive_env():
warnings.warn(
f"Importing {name} from {package} is deprecated. "
"Please replace the import with the following:\n"
f"from {fallback_module} import {name}",
category=LangChainDeprecationWarning,
if not is_interactive_env() and _should_deprecate_for_package(package):
warn_deprecated(
since="0.1",
pending=False,
removal="0.4",
message=(
f"Importing {name} from {package} is deprecated."
f"Please replace imports that look like:"
f"`from {package} import {name}`\n"
"with the following:\n "
f"from {fallback_module} import {name}"
),
)
return result

@ -571,7 +571,7 @@ class RunnableMultiActionAgent(BaseMultiActionAgent):
"Use new agent constructor methods like create_react_agent, create_json_agent, "
"create_structured_chat_agent, etc."
),
removal="0.2.0",
removal="0.3.0",
)
class LLMSingleActionAgent(BaseSingleActionAgent):
"""Base class for single action agents."""
@ -661,7 +661,7 @@ class LLMSingleActionAgent(BaseSingleActionAgent):
"Use new agent constructor methods like create_react_agent, create_json_agent, "
"create_structured_chat_agent, etc."
),
removal="0.2.0",
removal="0.3.0",
)
class Agent(BaseSingleActionAgent):
"""Agent that calls the language model and deciding the action.

@ -1,11 +1,18 @@
"""Toolkit for interacting with a vector store."""
from typing import List
from langchain_community.agent_toolkits.base import BaseToolkit
from langchain_community.llms.openai import OpenAI
from langchain_community.tools.vectorstore.tool import (
VectorStoreQATool,
VectorStoreQAWithSourcesTool,
)
from langchain_core.language_models import BaseLanguageModel
from langchain_core.pydantic_v1 import BaseModel, Field
from langchain_core.tools import BaseTool, BaseToolkit
from langchain_core.vectorstores import VectorStore
from langchain.tools import BaseTool
class VectorStoreInfo(BaseModel):
"""Information about a VectorStore."""
@ -24,7 +31,7 @@ class VectorStoreToolkit(BaseToolkit):
"""Toolkit for interacting with a Vector Store."""
vectorstore_info: VectorStoreInfo = Field(exclude=True)
llm: BaseLanguageModel
llm: BaseLanguageModel = Field(default_factory=lambda: OpenAI(temperature=0))
class Config:
"""Configuration for this pydantic object."""
@ -33,15 +40,6 @@ class VectorStoreToolkit(BaseToolkit):
def get_tools(self) -> List[BaseTool]:
"""Get the tools in the toolkit."""
try:
from langchain_community.tools.vectorstore.tool import (
VectorStoreQATool,
VectorStoreQAWithSourcesTool,
)
except ImportError:
raise ImportError(
"You need to install langchain-community to use this toolkit."
)
description = VectorStoreQATool.get_description(
self.vectorstore_info.name, self.vectorstore_info.description
)
@ -67,7 +65,7 @@ class VectorStoreRouterToolkit(BaseToolkit):
"""Toolkit for routing between Vector Stores."""
vectorstores: List[VectorStoreInfo] = Field(exclude=True)
llm: BaseLanguageModel
llm: BaseLanguageModel = Field(default_factory=lambda: OpenAI(temperature=0))
class Config:
"""Configuration for this pydantic object."""
@ -77,14 +75,6 @@ class VectorStoreRouterToolkit(BaseToolkit):
def get_tools(self) -> List[BaseTool]:
"""Get the tools in the toolkit."""
tools: List[BaseTool] = []
try:
from langchain_community.tools.vectorstore.tool import (
VectorStoreQATool,
)
except ImportError:
raise ImportError(
"You need to install langchain-community to use this toolkit."
)
for vectorstore_info in self.vectorstores:
description = VectorStoreQATool.get_description(
vectorstore_info.name, vectorstore_info.description

@ -10,7 +10,7 @@ from langchain_core._api import deprecated
"Use new agent constructor methods like create_react_agent, create_json_agent, "
"create_structured_chat_agent, etc."
),
removal="0.2.0",
removal="0.3.0",
)
class AgentType(str, Enum):
"""An enum for agent types.

@ -25,7 +25,7 @@ from langchain.agents.utils import validate_tools_single_input
from langchain.chains.llm import LLMChain
@deprecated("0.1.0", alternative="create_react_agent", removal="0.2.0")
@deprecated("0.1.0", alternative="create_react_agent", removal="0.3.0")
class ChatAgent(Agent):
"""Chat Agent."""

@ -18,7 +18,7 @@ from langchain.agents.utils import validate_tools_single_input
from langchain.chains import LLMChain
@deprecated("0.1.0", alternative="create_react_agent", removal="0.2.0")
@deprecated("0.1.0", alternative="create_react_agent", removal="0.3.0")
class ConversationalAgent(Agent):
"""An agent that holds a conversation in addition to using tools."""

@ -30,7 +30,7 @@ from langchain.agents.utils import validate_tools_single_input
from langchain.chains import LLMChain
@deprecated("0.1.0", alternative="create_json_chat_agent", removal="0.2.0")
@deprecated("0.1.0", alternative="create_json_chat_agent", removal="0.3.0")
class ConversationalChatAgent(Agent):
"""An agent designed to hold a conversation in addition to using tools."""

@ -17,7 +17,7 @@ from langchain.agents.loading import AGENT_TO_CLASS, load_agent
"Use new agent constructor methods like create_react_agent, create_json_agent, "
"create_structured_chat_agent, etc."
),
removal="0.2.0",
removal="0.3.0",
)
def initialize_agent(
tools: Sequence[BaseTool],

@ -31,7 +31,7 @@ def _load_agent_from_tools(
return agent_cls.from_llm_and_tools(llm, tools, **combined_config)
@deprecated("0.1.0", removal="0.2.0")
@deprecated("0.1.0", removal="0.3.0")
def load_agent_from_config(
config: dict,
llm: Optional[BaseLanguageModel] = None,
@ -87,7 +87,7 @@ def load_agent_from_config(
return agent_cls(**combined_config) # type: ignore
@deprecated("0.1.0", removal="0.2.0")
@deprecated("0.1.0", removal="0.3.0")
def load_agent(
path: Union[str, Path], **kwargs: Any
) -> Union[BaseSingleActionAgent, BaseMultiActionAgent]:

@ -33,7 +33,7 @@ class ChainConfig(NamedTuple):
action_description: str
@deprecated("0.1.0", alternative="create_react_agent", removal="0.2.0")
@deprecated("0.1.0", alternative="create_react_agent", removal="0.3.0")
class ZeroShotAgent(Agent):
"""Agent for the MRKL chain."""
@ -139,7 +139,7 @@ class ZeroShotAgent(Agent):
super()._validate_tools(tools)
@deprecated("0.1.0", removal="0.2.0")
@deprecated("0.1.0", removal="0.3.0")
class MRKLChain(AgentExecutor):
"""[Deprecated] Chain that implements the MRKL system."""

@ -30,7 +30,7 @@ from langchain.agents.output_parsers.openai_functions import (
)
@deprecated("0.1.0", alternative="create_openai_functions_agent", removal="0.2.0")
@deprecated("0.1.0", alternative="create_openai_functions_agent", removal="0.3.0")
class OpenAIFunctionsAgent(BaseSingleActionAgent):
"""An Agent driven by OpenAIs function powered API.

@ -93,7 +93,7 @@ def _parse_ai_message(message: BaseMessage) -> Union[List[AgentAction], AgentFin
)
@deprecated("0.1.0", alternative="create_openai_tools_agent", removal="0.2.0")
@deprecated("0.1.0", alternative="create_openai_tools_agent", removal="0.3.0")
class OpenAIMultiFunctionsAgent(BaseMultiActionAgent):
"""An Agent driven by OpenAIs function powered API.

@ -21,7 +21,7 @@ if TYPE_CHECKING:
from langchain_community.docstore.base import Docstore
@deprecated("0.1.0", removal="0.2.0")
@deprecated("0.1.0", removal="0.3.0")
class ReActDocstoreAgent(Agent):
"""Agent for the ReAct chain."""
@ -68,7 +68,7 @@ class ReActDocstoreAgent(Agent):
return "Thought:"
@deprecated("0.1.0", removal="0.2.0")
@deprecated("0.1.0", removal="0.3.0")
class DocstoreExplorer:
"""Class to assist with exploration of a document store."""
@ -118,7 +118,7 @@ class DocstoreExplorer:
return self.document.page_content.split("\n\n")
@deprecated("0.1.0", removal="0.2.0")
@deprecated("0.1.0", removal="0.3.0")
class ReActTextWorldAgent(ReActDocstoreAgent):
"""Agent for the ReAct TextWorld chain."""
@ -138,7 +138,7 @@ class ReActTextWorldAgent(ReActDocstoreAgent):
raise ValueError(f"Tool name should be Play, got {tool_names}")
@deprecated("0.1.0", removal="0.2.0")
@deprecated("0.1.0", removal="0.3.0")
class ReActChain(AgentExecutor):
"""[Deprecated] Chain that implements the ReAct paper."""

@ -23,7 +23,7 @@ if TYPE_CHECKING:
from langchain_community.utilities.serpapi import SerpAPIWrapper
@deprecated("0.1.0", alternative="create_self_ask_with_search", removal="0.2.0")
@deprecated("0.1.0", alternative="create_self_ask_with_search", removal="0.3.0")
class SelfAskWithSearchAgent(Agent):
"""Agent for the self-ask-with-search paper."""
@ -66,7 +66,7 @@ class SelfAskWithSearchAgent(Agent):
return ""
@deprecated("0.1.0", removal="0.2.0")
@deprecated("0.1.0", removal="0.3.0")
class SelfAskWithSearchChain(AgentExecutor):
"""[Deprecated] Chain that does self-ask with search."""

@ -28,7 +28,7 @@ from langchain.tools.render import ToolsRenderer, render_text_description_and_ar
HUMAN_MESSAGE_TEMPLATE = "{input}\n\n{agent_scratchpad}"
@deprecated("0.1.0", alternative="create_structured_chat_agent", removal="0.2.0")
@deprecated("0.1.0", alternative="create_structured_chat_agent", removal="0.3.0")
class StructuredChatAgent(Agent):
"""Structured Chat Agent."""

@ -17,7 +17,7 @@ from langchain.chains.llm import LLMChain
from langchain.tools.render import ToolsRenderer, render_text_description
@deprecated("0.1.0", alternative="create_xml_agent", removal="0.2.0")
@deprecated("0.1.0", alternative="create_xml_agent", removal="0.3.0")
class XMLAgent(BaseSingleActionAgent):
"""Agent that uses XML tags.

@ -331,7 +331,7 @@ class Chain(RunnableSerializable[Dict[str, Any], Dict[str, Any]], ABC):
None, self._call, inputs, run_manager.get_sync() if run_manager else None
)
@deprecated("0.1.0", alternative="invoke", removal="0.2.0")
@deprecated("0.1.0", alternative="invoke", removal="0.3.0")
def __call__(
self,
inputs: Union[Dict[str, Any], Any],
@ -382,7 +382,7 @@ class Chain(RunnableSerializable[Dict[str, Any], Dict[str, Any]], ABC):
include_run_info=include_run_info,
)
@deprecated("0.1.0", alternative="ainvoke", removal="0.2.0")
@deprecated("0.1.0", alternative="ainvoke", removal="0.3.0")
async def acall(
self,
inputs: Union[Dict[str, Any], Any],
@ -541,7 +541,7 @@ class Chain(RunnableSerializable[Dict[str, Any], Dict[str, Any]], ABC):
)
return self.output_keys[0]
@deprecated("0.1.0", alternative="invoke", removal="0.2.0")
@deprecated("0.1.0", alternative="invoke", removal="0.3.0")
def run(
self,
*args: Any,
@ -612,7 +612,7 @@ class Chain(RunnableSerializable[Dict[str, Any], Dict[str, Any]], ABC):
f" but not both. Got args: {args} and kwargs: {kwargs}."
)
@deprecated("0.1.0", alternative="ainvoke", removal="0.2.0")
@deprecated("0.1.0", alternative="ainvoke", removal="0.3.0")
async def arun(
self,
*args: Any,
@ -750,7 +750,7 @@ class Chain(RunnableSerializable[Dict[str, Any], Dict[str, Any]], ABC):
else:
raise ValueError(f"{save_path} must be json or yaml")
@deprecated("0.1.0", alternative="batch", removal="0.2.0")
@deprecated("0.1.0", alternative="batch", removal="0.3.0")
def apply(
self, input_list: List[Dict[str, Any]], callbacks: Callbacks = None
) -> List[Dict[str, str]]:

@ -5,6 +5,7 @@ from abc import abstractmethod
from typing import Any, Dict, List, Optional, Sequence, Tuple
import numpy as np
from langchain_community.llms.openai import OpenAI
from langchain_core.callbacks import (
CallbackManagerForChainRun,
)
@ -55,7 +56,11 @@ class _ResponseChain(LLMChain):
class _OpenAIResponseChain(_ResponseChain):
"""Chain that generates responses from user input and context."""
llm: BaseLanguageModel
llm: OpenAI = Field(
default_factory=lambda: OpenAI(
max_tokens=32, model_kwargs={"logprobs": 1}, temperature=0
)
)
def _extract_tokens_and_log_probs(
self, generations: List[Generation]
@ -113,7 +118,7 @@ class FlareChain(Chain):
question_generator_chain: QuestionGeneratorChain
"""Chain that generates questions from uncertain spans."""
response_chain: _ResponseChain
response_chain: _ResponseChain = Field(default_factory=_OpenAIResponseChain)
"""Chain that generates responses from user input and context."""
output_parser: FinishedOutputParser = Field(default_factory=FinishedOutputParser)
"""Parser that determines whether the chain is finished."""
@ -250,14 +255,6 @@ class FlareChain(Chain):
Returns:
FlareChain class with the given language model.
"""
try:
from langchain_openai import OpenAI
except ImportError:
raise ImportError(
"OpenAI is required for FlareChain. "
"Please install langchain-openai."
"pip install langchain-openai"
)
question_gen_chain = QuestionGeneratorChain(llm=llm)
response_llm = OpenAI(
max_tokens=max_generation_len, model_kwargs={"logprobs": 1}, temperature=0

@ -4,6 +4,7 @@ from __future__ import annotations
import warnings
from typing import Any, Dict, List, Optional
from langchain_community.llms.openai import OpenAI
from langchain_core.callbacks import CallbackManagerForChainRun
from langchain_core.language_models import BaseLanguageModel
from langchain_core.pydantic_v1 import Extra, root_validator
@ -67,11 +68,8 @@ class NatBotChain(Chain):
@classmethod
def from_default(cls, objective: str, **kwargs: Any) -> NatBotChain:
"""Load with default LLMChain."""
raise NotImplementedError(
"This method is no longer implemented. Please use from_llm."
"llm = OpenAI(temperature=0.5, best_of=10, n=3, max_tokens=50)"
"For example, NatBotChain.from_llm(llm, objective)"
)
llm = OpenAI(temperature=0.5, best_of=10, n=3, max_tokens=50)
return cls.from_llm(llm, objective, **kwargs)
@classmethod
def from_llm(

@ -42,7 +42,7 @@ __all__ = [
]
@deprecated(since="0.1.1", removal="0.2.0", alternative="create_openai_fn_runnable")
@deprecated(since="0.1.1", removal="0.3.0", alternative="create_openai_fn_runnable")
def create_openai_fn_chain(
functions: Sequence[Union[Dict[str, Any], Type[BaseModel], Callable]],
llm: BaseLanguageModel,
@ -144,7 +144,7 @@ def create_openai_fn_chain(
@deprecated(
since="0.1.1", removal="0.2.0", alternative="ChatOpenAI.with_structured_output"
since="0.1.1", removal="0.3.0", alternative="ChatOpenAI.with_structured_output"
)
def create_structured_output_chain(
output_schema: Union[Dict[str, Any], Type[BaseModel]],

@ -6,6 +6,8 @@ from collections import defaultdict
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
import requests
from langchain_community.chat_models import ChatOpenAI
from langchain_community.utilities.openapi import OpenAPISpec
from langchain_core.callbacks import CallbackManagerForChainRun
from langchain_core.language_models import BaseLanguageModel
from langchain_core.output_parsers.openai_functions import JsonOutputFunctionsParser
@ -18,7 +20,6 @@ from langchain.chains.llm import LLMChain
from langchain.chains.sequential import SequentialChain
if TYPE_CHECKING:
from langchain_community.utilities.openapi import OpenAPISpec
from openapi_pydantic import Parameter
@ -262,13 +263,6 @@ def get_openapi_chain(
prompt: Main prompt template to use.
request_chain: Chain for taking the functions output and executing the request.
"""
try:
from langchain_community.utilities.openapi import OpenAPISpec
except ImportError as e:
raise ImportError(
"Could not import langchain_community.utilities.openapi. "
"Please install it with `pip install langchain-community`."
) from e
if isinstance(spec, str):
for conversion in (
OpenAPISpec.from_url,
@ -285,12 +279,9 @@ def get_openapi_chain(
if isinstance(spec, str):
raise ValueError(f"Unable to parse spec from source {spec}")
openai_fns, call_api_fn = openapi_spec_to_openai_fn(spec)
if not llm:
raise ValueError(
"Must provide an LLM for this chain.For example,\n"
"from langchain_openai import ChatOpenAI\n"
"llm = ChatOpenAI()\n"
)
llm = llm or ChatOpenAI(
model="gpt-3.5-turbo-0613",
)
prompt = prompt or ChatPromptTemplate.from_template(
"Use the provided API's to respond to this user query:\n\n{query}"
)

@ -3,6 +3,7 @@ from __future__ import annotations
from typing import Any, Dict, List, Mapping, Optional
from langchain_community.chat_models import ChatOpenAI
from langchain_core.language_models import BaseLanguageModel
from langchain_core.prompts import PromptTemplate
from langchain_core.retrievers import BaseRetriever
@ -41,8 +42,6 @@ class MultiRetrievalQAChain(MultiRouteChain):
default_retriever: Optional[BaseRetriever] = None,
default_prompt: Optional[PromptTemplate] = None,
default_chain: Optional[Chain] = None,
*,
default_chain_llm: Optional[BaseLanguageModel] = None,
**kwargs: Any,
) -> MultiRetrievalQAChain:
if default_prompt and not default_retriever:
@ -79,20 +78,8 @@ class MultiRetrievalQAChain(MultiRouteChain):
prompt = PromptTemplate(
template=prompt_template, input_variables=["history", "query"]
)
if default_chain_llm is None:
raise NotImplementedError(
"conversation_llm must be provided if default_chain is not "
"specified. This API has been changed to avoid instantiating "
"default LLMs on behalf of users."
"You can provide a conversation LLM like so:\n"
"from langchain_openai import ChatOpenAI\n"
"llm = ChatOpenAI()"
)
_default_chain = ConversationChain(
llm=default_chain_llm,
prompt=prompt,
input_key="query",
output_key="result",
llm=ChatOpenAI(), prompt=prompt, input_key="query", output_key="result"
)
return cls(
router_chain=router_chain,

@ -1,166 +1,6 @@
"""Load summarizing chains."""
from typing import Any, Mapping, Optional, Protocol
from langchain.chains.summarize.chain import (
LoadingCallable,
load_summarize_chain,
)
from langchain_core.callbacks import Callbacks
from langchain_core.language_models import BaseLanguageModel
from langchain_core.prompts import BasePromptTemplate
from langchain.chains.combine_documents.base import BaseCombineDocumentsChain
from langchain.chains.combine_documents.map_reduce import MapReduceDocumentsChain
from langchain.chains.combine_documents.reduce import ReduceDocumentsChain
from langchain.chains.combine_documents.refine import RefineDocumentsChain
from langchain.chains.combine_documents.stuff import StuffDocumentsChain
from langchain.chains.llm import LLMChain
from langchain.chains.summarize import map_reduce_prompt, refine_prompts, stuff_prompt
class LoadingCallable(Protocol):
"""Interface for loading the combine documents chain."""
def __call__(
self, llm: BaseLanguageModel, **kwargs: Any
) -> BaseCombineDocumentsChain:
"""Callable to load the combine documents chain."""
def _load_stuff_chain(
llm: BaseLanguageModel,
prompt: BasePromptTemplate = stuff_prompt.PROMPT,
document_variable_name: str = "text",
verbose: Optional[bool] = None,
**kwargs: Any,
) -> StuffDocumentsChain:
llm_chain = LLMChain(llm=llm, prompt=prompt, verbose=verbose) # type: ignore[arg-type]
# TODO: document prompt
return StuffDocumentsChain(
llm_chain=llm_chain,
document_variable_name=document_variable_name,
verbose=verbose, # type: ignore[arg-type]
**kwargs,
)
def _load_map_reduce_chain(
llm: BaseLanguageModel,
map_prompt: BasePromptTemplate = map_reduce_prompt.PROMPT,
combine_prompt: BasePromptTemplate = map_reduce_prompt.PROMPT,
combine_document_variable_name: str = "text",
map_reduce_document_variable_name: str = "text",
collapse_prompt: Optional[BasePromptTemplate] = None,
reduce_llm: Optional[BaseLanguageModel] = None,
collapse_llm: Optional[BaseLanguageModel] = None,
verbose: Optional[bool] = None,
token_max: int = 3000,
callbacks: Callbacks = None,
*,
collapse_max_retries: Optional[int] = None,
**kwargs: Any,
) -> MapReduceDocumentsChain:
map_chain = LLMChain(
llm=llm,
prompt=map_prompt,
verbose=verbose, # type: ignore[arg-type]
callbacks=callbacks, # type: ignore[arg-type]
)
_reduce_llm = reduce_llm or llm
reduce_chain = LLMChain(
llm=_reduce_llm,
prompt=combine_prompt,
verbose=verbose, # type: ignore[arg-type]
callbacks=callbacks, # type: ignore[arg-type]
)
# TODO: document prompt
combine_documents_chain = StuffDocumentsChain(
llm_chain=reduce_chain,
document_variable_name=combine_document_variable_name,
verbose=verbose, # type: ignore[arg-type]
callbacks=callbacks,
)
if collapse_prompt is None:
collapse_chain = None
if collapse_llm is not None:
raise ValueError(
"collapse_llm provided, but collapse_prompt was not: please "
"provide one or stop providing collapse_llm."
)
else:
_collapse_llm = collapse_llm or llm
collapse_chain = StuffDocumentsChain(
llm_chain=LLMChain(
llm=_collapse_llm,
prompt=collapse_prompt,
verbose=verbose, # type: ignore[arg-type]
callbacks=callbacks,
),
document_variable_name=combine_document_variable_name,
)
reduce_documents_chain = ReduceDocumentsChain(
combine_documents_chain=combine_documents_chain,
collapse_documents_chain=collapse_chain,
token_max=token_max,
verbose=verbose, # type: ignore[arg-type]
callbacks=callbacks,
collapse_max_retries=collapse_max_retries,
)
return MapReduceDocumentsChain(
llm_chain=map_chain,
reduce_documents_chain=reduce_documents_chain,
document_variable_name=map_reduce_document_variable_name,
verbose=verbose, # type: ignore[arg-type]
callbacks=callbacks,
**kwargs,
)
def _load_refine_chain(
llm: BaseLanguageModel,
question_prompt: BasePromptTemplate = refine_prompts.PROMPT,
refine_prompt: BasePromptTemplate = refine_prompts.REFINE_PROMPT,
document_variable_name: str = "text",
initial_response_name: str = "existing_answer",
refine_llm: Optional[BaseLanguageModel] = None,
verbose: Optional[bool] = None,
**kwargs: Any,
) -> RefineDocumentsChain:
initial_chain = LLMChain(llm=llm, prompt=question_prompt, verbose=verbose) # type: ignore[arg-type]
_refine_llm = refine_llm or llm
refine_chain = LLMChain(llm=_refine_llm, prompt=refine_prompt, verbose=verbose) # type: ignore[arg-type]
return RefineDocumentsChain(
initial_llm_chain=initial_chain,
refine_llm_chain=refine_chain,
document_variable_name=document_variable_name,
initial_response_name=initial_response_name,
verbose=verbose, # type: ignore[arg-type]
**kwargs,
)
def load_summarize_chain(
llm: BaseLanguageModel,
chain_type: str = "stuff",
verbose: Optional[bool] = None,
**kwargs: Any,
) -> BaseCombineDocumentsChain:
"""Load summarizing chain.
Args:
llm: Language Model to use in the chain.
chain_type: Type of document combining chain to use. Should be one of "stuff",
"map_reduce", and "refine".
verbose: Whether chains should be run in verbose mode or not. Note that this
applies to all chains that make up the final chain.
Returns:
A chain to use for summarizing.
"""
loader_mapping: Mapping[str, LoadingCallable] = {
"stuff": _load_stuff_chain,
"map_reduce": _load_map_reduce_chain,
"refine": _load_refine_chain,
}
if chain_type not in loader_mapping:
raise ValueError(
f"Got unsupported chain type: {chain_type}. "
f"Should be one of {loader_mapping.keys()}"
)
return loader_mapping[chain_type](llm, verbose=verbose, **kwargs)
__all__ = ["LoadingCallable", "load_summarize_chain"]

@ -0,0 +1,166 @@
"""Load summarizing chains."""
from typing import Any, Mapping, Optional, Protocol
from langchain_core.callbacks import Callbacks
from langchain_core.language_models import BaseLanguageModel
from langchain_core.prompts import BasePromptTemplate
from langchain.chains.combine_documents.base import BaseCombineDocumentsChain
from langchain.chains.combine_documents.map_reduce import MapReduceDocumentsChain
from langchain.chains.combine_documents.reduce import ReduceDocumentsChain
from langchain.chains.combine_documents.refine import RefineDocumentsChain
from langchain.chains.combine_documents.stuff import StuffDocumentsChain
from langchain.chains.llm import LLMChain
from langchain.chains.summarize import map_reduce_prompt, refine_prompts, stuff_prompt
class LoadingCallable(Protocol):
"""Interface for loading the combine documents chain."""
def __call__(
self, llm: BaseLanguageModel, **kwargs: Any
) -> BaseCombineDocumentsChain:
"""Callable to load the combine documents chain."""
def _load_stuff_chain(
llm: BaseLanguageModel,
prompt: BasePromptTemplate = stuff_prompt.PROMPT,
document_variable_name: str = "text",
verbose: Optional[bool] = None,
**kwargs: Any,
) -> StuffDocumentsChain:
llm_chain = LLMChain(llm=llm, prompt=prompt, verbose=verbose) # type: ignore[arg-type]
# TODO: document prompt
return StuffDocumentsChain(
llm_chain=llm_chain,
document_variable_name=document_variable_name,
verbose=verbose, # type: ignore[arg-type]
**kwargs,
)
def _load_map_reduce_chain(
llm: BaseLanguageModel,
map_prompt: BasePromptTemplate = map_reduce_prompt.PROMPT,
combine_prompt: BasePromptTemplate = map_reduce_prompt.PROMPT,
combine_document_variable_name: str = "text",
map_reduce_document_variable_name: str = "text",
collapse_prompt: Optional[BasePromptTemplate] = None,
reduce_llm: Optional[BaseLanguageModel] = None,
collapse_llm: Optional[BaseLanguageModel] = None,
verbose: Optional[bool] = None,
token_max: int = 3000,
callbacks: Callbacks = None,
*,
collapse_max_retries: Optional[int] = None,
**kwargs: Any,
) -> MapReduceDocumentsChain:
map_chain = LLMChain(
llm=llm,
prompt=map_prompt,
verbose=verbose, # type: ignore[arg-type]
callbacks=callbacks, # type: ignore[arg-type]
)
_reduce_llm = reduce_llm or llm
reduce_chain = LLMChain(
llm=_reduce_llm,
prompt=combine_prompt,
verbose=verbose, # type: ignore[arg-type]
callbacks=callbacks, # type: ignore[arg-type]
)
# TODO: document prompt
combine_documents_chain = StuffDocumentsChain(
llm_chain=reduce_chain,
document_variable_name=combine_document_variable_name,
verbose=verbose, # type: ignore[arg-type]
callbacks=callbacks,
)
if collapse_prompt is None:
collapse_chain = None
if collapse_llm is not None:
raise ValueError(
"collapse_llm provided, but collapse_prompt was not: please "
"provide one or stop providing collapse_llm."
)
else:
_collapse_llm = collapse_llm or llm
collapse_chain = StuffDocumentsChain(
llm_chain=LLMChain(
llm=_collapse_llm,
prompt=collapse_prompt,
verbose=verbose, # type: ignore[arg-type]
callbacks=callbacks,
),
document_variable_name=combine_document_variable_name,
)
reduce_documents_chain = ReduceDocumentsChain(
combine_documents_chain=combine_documents_chain,
collapse_documents_chain=collapse_chain,
token_max=token_max,
verbose=verbose, # type: ignore[arg-type]
callbacks=callbacks,
collapse_max_retries=collapse_max_retries,
)
return MapReduceDocumentsChain(
llm_chain=map_chain,
reduce_documents_chain=reduce_documents_chain,
document_variable_name=map_reduce_document_variable_name,
verbose=verbose, # type: ignore[arg-type]
callbacks=callbacks,
**kwargs,
)
def _load_refine_chain(
llm: BaseLanguageModel,
question_prompt: BasePromptTemplate = refine_prompts.PROMPT,
refine_prompt: BasePromptTemplate = refine_prompts.REFINE_PROMPT,
document_variable_name: str = "text",
initial_response_name: str = "existing_answer",
refine_llm: Optional[BaseLanguageModel] = None,
verbose: Optional[bool] = None,
**kwargs: Any,
) -> RefineDocumentsChain:
initial_chain = LLMChain(llm=llm, prompt=question_prompt, verbose=verbose) # type: ignore[arg-type]
_refine_llm = refine_llm or llm
refine_chain = LLMChain(llm=_refine_llm, prompt=refine_prompt, verbose=verbose) # type: ignore[arg-type]
return RefineDocumentsChain(
initial_llm_chain=initial_chain,
refine_llm_chain=refine_chain,
document_variable_name=document_variable_name,
initial_response_name=initial_response_name,
verbose=verbose, # type: ignore[arg-type]
**kwargs,
)
def load_summarize_chain(
llm: BaseLanguageModel,
chain_type: str = "stuff",
verbose: Optional[bool] = None,
**kwargs: Any,
) -> BaseCombineDocumentsChain:
"""Load summarizing chain.
Args:
llm: Language Model to use in the chain.
chain_type: Type of document combining chain to use. Should be one of "stuff",
"map_reduce", and "refine".
verbose: Whether chains should be run in verbose mode or not. Note that this
applies to all chains that make up the final chain.
Returns:
A chain to use for summarizing.
"""
loader_mapping: Mapping[str, LoadingCallable] = {
"stuff": _load_stuff_chain,
"map_reduce": _load_map_reduce_chain,
"refine": _load_refine_chain,
}
if chain_type not in loader_mapping:
raise ValueError(
f"Got unsupported chain type: {chain_type}. "
f"Should be one of {loader_mapping.keys()}"
)
return loader_mapping[chain_type](llm, verbose=verbose, **kwargs)

@ -1,6 +1,9 @@
from typing import Any, Dict, List, Optional, Type
from langchain_core.document_loaders import BaseLoader
from langchain_community.document_loaders.base import BaseLoader
from langchain_community.embeddings.openai import OpenAIEmbeddings
from langchain_community.llms.openai import OpenAI
from langchain_community.vectorstores.inmemory import InMemoryVectorStore
from langchain_core.documents import Document
from langchain_core.embeddings import Embeddings
from langchain_core.language_models import BaseLanguageModel
@ -35,14 +38,7 @@ class VectorStoreIndexWrapper(BaseModel):
**kwargs: Any,
) -> str:
"""Query the vectorstore."""
if llm is None:
raise NotImplementedError(
"This API has been changed to require an LLM. "
"Please provide an llm to use for querying the vectorstore.\n"
"For example,\n"
"from langchain_openai import OpenAI\n"
"llm = OpenAI(temperature=0)"
)
llm = llm or OpenAI(temperature=0)
retriever_kwargs = retriever_kwargs or {}
chain = RetrievalQA.from_chain_type(
llm, retriever=self.vectorstore.as_retriever(**retriever_kwargs), **kwargs
@ -57,14 +53,7 @@ class VectorStoreIndexWrapper(BaseModel):
**kwargs: Any,
) -> str:
"""Query the vectorstore."""
if llm is None:
raise NotImplementedError(
"This API has been changed to require an LLM. "
"Please provide an llm to use for querying the vectorstore.\n"
"For example,\n"
"from langchain_openai import OpenAI\n"
"llm = OpenAI(temperature=0)"
)
llm = llm or OpenAI(temperature=0)
retriever_kwargs = retriever_kwargs or {}
chain = RetrievalQA.from_chain_type(
llm, retriever=self.vectorstore.as_retriever(**retriever_kwargs), **kwargs
@ -79,14 +68,7 @@ class VectorStoreIndexWrapper(BaseModel):
**kwargs: Any,
) -> dict:
"""Query the vectorstore and get back sources."""
if llm is None:
raise NotImplementedError(
"This API has been changed to require an LLM. "
"Please provide an llm to use for querying the vectorstore.\n"
"For example,\n"
"from langchain_openai import OpenAI\n"
"llm = OpenAI(temperature=0)"
)
llm = llm or OpenAI(temperature=0)
retriever_kwargs = retriever_kwargs or {}
chain = RetrievalQAWithSourcesChain.from_chain_type(
llm, retriever=self.vectorstore.as_retriever(**retriever_kwargs), **kwargs
@ -101,14 +83,7 @@ class VectorStoreIndexWrapper(BaseModel):
**kwargs: Any,
) -> dict:
"""Query the vectorstore and get back sources."""
if llm is None:
raise NotImplementedError(
"This API has been changed to require an LLM. "
"Please provide an llm to use for querying the vectorstore.\n"
"For example,\n"
"from langchain_openai import OpenAI\n"
"llm = OpenAI(temperature=0)"
)
llm = llm or OpenAI(temperature=0)
retriever_kwargs = retriever_kwargs or {}
chain = RetrievalQAWithSourcesChain.from_chain_type(
llm, retriever=self.vectorstore.as_retriever(**retriever_kwargs), **kwargs
@ -116,31 +91,11 @@ class VectorStoreIndexWrapper(BaseModel):
return await chain.ainvoke({chain.question_key: question})
def _get_in_memory_vectorstore() -> Type[VectorStore]:
"""Get the InMemoryVectorStore."""
import warnings
try:
from langchain_community.vectorstores.inmemory import InMemoryVectorStore
except ImportError:
raise ImportError(
"Please install langchain-community to use the InMemoryVectorStore."
)
warnings.warn(
"Using InMemoryVectorStore as the default vectorstore."
"This memory store won't persist data. You should explicitly"
"specify a vectorstore when using VectorstoreIndexCreator"
)
return InMemoryVectorStore
class VectorstoreIndexCreator(BaseModel):
"""Logic for creating indexes."""
vectorstore_cls: Type[VectorStore] = Field(
default_factory=_get_in_memory_vectorstore
)
embedding: Embeddings
vectorstore_cls: Type[VectorStore] = InMemoryVectorStore
embedding: Embeddings = Field(default_factory=OpenAIEmbeddings)
text_splitter: TextSplitter = Field(default_factory=_get_default_text_splitter)
vectorstore_kwargs: dict = Field(default_factory=dict)

@ -13,7 +13,7 @@ from langchain.retrievers.document_compressors.base import BaseDocumentCompresso
@deprecated(
since="0.0.30", removal="0.2.0", alternative_import="langchain_cohere.CohereRerank"
since="0.0.30", removal="0.3.0", alternative_import="langchain_cohere.CohereRerank"
)
class CohereRerank(BaseDocumentCompressor):
"""Document compressor that uses `Cohere Rerank API`."""

@ -0,0 +1,30 @@
from typing import TYPE_CHECKING, Any
from langchain._api import create_importer
if TYPE_CHECKING:
from langchain_community.tools import AINAppOps
from langchain_community.tools.ainetwork.app import AppOperationType, AppSchema
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"AppOperationType": "langchain_community.tools.ainetwork.app",
"AppSchema": "langchain_community.tools.ainetwork.app",
"AINAppOps": "langchain_community.tools",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"AppOperationType",
"AppSchema",
"AINAppOps",
]

@ -0,0 +1,27 @@
from typing import TYPE_CHECKING, Any
from langchain._api import create_importer
if TYPE_CHECKING:
from langchain_community.tools.ainetwork.base import AINBaseTool, OperationType
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"OperationType": "langchain_community.tools.ainetwork.base",
"AINBaseTool": "langchain_community.tools.ainetwork.base",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"OperationType",
"AINBaseTool",
]

@ -0,0 +1,28 @@
from typing import TYPE_CHECKING, Any
from langchain._api import create_importer
if TYPE_CHECKING:
from langchain_community.tools import AINOwnerOps
from langchain_community.tools.ainetwork.owner import RuleSchema
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"RuleSchema": "langchain_community.tools.ainetwork.owner",
"AINOwnerOps": "langchain_community.tools",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"RuleSchema",
"AINOwnerOps",
]

@ -0,0 +1,28 @@
from typing import TYPE_CHECKING, Any
from langchain._api import create_importer
if TYPE_CHECKING:
from langchain_community.tools import AINRuleOps
from langchain_community.tools.ainetwork.rule import RuleSchema
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"RuleSchema": "langchain_community.tools.ainetwork.rule",
"AINRuleOps": "langchain_community.tools",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"RuleSchema",
"AINRuleOps",
]

@ -0,0 +1,28 @@
from typing import TYPE_CHECKING, Any
from langchain._api import create_importer
if TYPE_CHECKING:
from langchain_community.tools import AINTransfer
from langchain_community.tools.ainetwork.transfer import TransferSchema
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"TransferSchema": "langchain_community.tools.ainetwork.transfer",
"AINTransfer": "langchain_community.tools",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"TransferSchema",
"AINTransfer",
]

@ -0,0 +1,28 @@
from typing import TYPE_CHECKING, Any
from langchain._api import create_importer
if TYPE_CHECKING:
from langchain_community.tools import AINValueOps
from langchain_community.tools.ainetwork.value import ValueSchema
# Create a way to dynamically look up deprecated imports.
# Used to consolidate logic for raising deprecation warnings and
# handling optional imports.
DEPRECATED_LOOKUP = {
"ValueSchema": "langchain_community.tools.ainetwork.value",
"AINValueOps": "langchain_community.tools",
}
_import_attribute = create_importer(__package__, deprecated_lookups=DEPRECATED_LOOKUP)
def __getattr__(name: str) -> Any:
"""Look up attributes dynamically."""
return _import_attribute(name)
__all__ = [
"ValueSchema",
"AINValueOps",
]

@ -66,15 +66,17 @@ def test_import_all_modules() -> None:
]
# This test will need to be updated if new serializable classes are added
# to community
assert filtered_modules == [
("langchain", "chat_models", "azure_openai", "AzureChatOpenAI"),
("langchain", "chat_models", "bedrock", "BedrockChat"),
("langchain", "chat_models", "anthropic", "ChatAnthropic"),
("langchain", "chat_models", "fireworks", "ChatFireworks"),
("langchain", "chat_models", "google_palm", "ChatGooglePalm"),
("langchain", "chat_models", "openai", "ChatOpenAI"),
("langchain", "chat_models", "vertexai", "ChatVertexAI"),
]
assert sorted(filtered_modules) == sorted(
[
("langchain", "chat_models", "azure_openai", "AzureChatOpenAI"),
("langchain", "chat_models", "bedrock", "BedrockChat"),
("langchain", "chat_models", "anthropic", "ChatAnthropic"),
("langchain", "chat_models", "fireworks", "ChatFireworks"),
("langchain", "chat_models", "google_palm", "ChatGooglePalm"),
("langchain", "chat_models", "openai", "ChatOpenAI"),
("langchain", "chat_models", "vertexai", "ChatVertexAI"),
]
)
@pytest.mark.community

@ -756,6 +756,6 @@ def _lc_tool_calls_to_anthropic_tool_use_blocks(
return blocks
@deprecated(since="0.1.0", removal="0.2.0", alternative="ChatAnthropic")
@deprecated(since="0.1.0", removal="0.3.0", alternative="ChatAnthropic")
class ChatAnthropicMessages(ChatAnthropic):
pass

@ -145,7 +145,7 @@ def _xml_to_tool_calls(elem: Any, tools: List[Dict]) -> List[Dict[str, Any]]:
@deprecated(
"0.1.5",
removal="0.2.0",
removal="0.3.0",
alternative="ChatAnthropic",
message=(
"Tool-calling is now officially supported by the Anthropic API so this "

@ -360,6 +360,6 @@ class AnthropicLLM(LLM, _AnthropicCommon):
return self.count_tokens(text)
@deprecated(since="0.1.0", removal="0.2.0", alternative="AnthropicLLM")
@deprecated(since="0.1.0", removal="0.3.0", alternative="AnthropicLLM")
class Anthropic(AnthropicLLM):
pass

@ -494,7 +494,7 @@ class PineconeVectorStore(VectorStore):
return None
@deprecated(since="0.0.3", removal="0.2.0", alternative="PineconeVectorStore")
@deprecated(since="0.0.3", removal="0.3.0", alternative="PineconeVectorStore")
class Pinecone(PineconeVectorStore):
"""Deprecated. Use PineconeVectorStore instead."""

@ -110,7 +110,7 @@ class UpstageGroundednessCheck(BaseTool):
@deprecated(
since="0.1.3",
removal="0.2.0",
removal="0.3.0",
alternative_import="langchain_upstage.UpstageGroundednessCheck",
)
class GroundednessCheck(UpstageGroundednessCheck):

Loading…
Cancel
Save