langchain 0.2.11__py3-none-any.whl → 0.2.13__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. langchain/agents/agent.py +5 -9
  2. langchain/agents/agent_toolkits/vectorstore/base.py +114 -2
  3. langchain/agents/agent_toolkits/vectorstore/toolkit.py +0 -6
  4. langchain/agents/chat/output_parser.py +2 -2
  5. langchain/agents/initialize.py +1 -1
  6. langchain/agents/loading.py +2 -2
  7. langchain/agents/mrkl/base.py +1 -1
  8. langchain/agents/openai_assistant/base.py +2 -2
  9. langchain/agents/openai_functions_agent/base.py +1 -1
  10. langchain/agents/openai_functions_multi_agent/base.py +1 -1
  11. langchain/agents/output_parsers/react_json_single_input.py +2 -2
  12. langchain/agents/structured_chat/output_parser.py +2 -2
  13. langchain/chains/__init__.py +1 -0
  14. langchain/chains/api/base.py +121 -1
  15. langchain/chains/base.py +0 -2
  16. langchain/chains/combine_documents/map_reduce.py +2 -4
  17. langchain/chains/combine_documents/map_rerank.py +4 -6
  18. langchain/chains/combine_documents/reduce.py +1 -4
  19. langchain/chains/combine_documents/refine.py +2 -4
  20. langchain/chains/combine_documents/stuff.py +12 -4
  21. langchain/chains/conversation/base.py +2 -4
  22. langchain/chains/conversational_retrieval/base.py +4 -6
  23. langchain/chains/elasticsearch_database/base.py +16 -20
  24. langchain/chains/example_generator.py +3 -4
  25. langchain/chains/flare/base.py +1 -1
  26. langchain/chains/hyde/base.py +1 -4
  27. langchain/chains/llm.py +2 -4
  28. langchain/chains/llm_checker/base.py +12 -4
  29. langchain/chains/llm_math/base.py +2 -4
  30. langchain/chains/llm_summarization_checker/base.py +12 -4
  31. langchain/chains/loading.py +17 -0
  32. langchain/chains/mapreduce.py +12 -4
  33. langchain/chains/natbot/base.py +2 -4
  34. langchain/chains/openai_functions/__init__.py +2 -0
  35. langchain/chains/openai_functions/citation_fuzzy_match.py +54 -1
  36. langchain/chains/openai_functions/openapi.py +88 -1
  37. langchain/chains/openai_functions/qa_with_structure.py +19 -0
  38. langchain/chains/openai_functions/tagging.py +81 -0
  39. langchain/chains/qa_with_sources/base.py +21 -4
  40. langchain/chains/qa_with_sources/loading.py +16 -0
  41. langchain/chains/query_constructor/base.py +8 -2
  42. langchain/chains/query_constructor/schema.py +0 -2
  43. langchain/chains/question_answering/chain.py +15 -0
  44. langchain/chains/retrieval_qa/base.py +30 -6
  45. langchain/chains/router/base.py +1 -4
  46. langchain/chains/router/embedding_router.py +1 -4
  47. langchain/chains/router/llm_router.py +76 -1
  48. langchain/chains/router/multi_prompt.py +76 -1
  49. langchain/chains/sequential.py +3 -7
  50. langchain/chains/structured_output/base.py +1 -1
  51. langchain/chat_models/base.py +26 -3
  52. langchain/evaluation/agents/trajectory_eval_chain.py +3 -6
  53. langchain/evaluation/comparison/eval_chain.py +2 -4
  54. langchain/evaluation/criteria/eval_chain.py +2 -4
  55. langchain/evaluation/embedding_distance/base.py +3 -4
  56. langchain/evaluation/parsing/json_schema.py +1 -1
  57. langchain/evaluation/qa/eval_chain.py +2 -7
  58. langchain/evaluation/schema.py +8 -8
  59. langchain/evaluation/scoring/eval_chain.py +2 -4
  60. langchain/evaluation/string_distance/base.py +7 -6
  61. langchain/hub.py +60 -26
  62. langchain/indexes/vectorstore.py +3 -7
  63. langchain/memory/buffer.py +2 -2
  64. langchain/memory/entity.py +0 -2
  65. langchain/memory/summary.py +12 -2
  66. langchain/memory/summary_buffer.py +2 -2
  67. langchain/output_parsers/combining.py +2 -2
  68. langchain/output_parsers/enum.py +2 -2
  69. langchain/output_parsers/fix.py +4 -5
  70. langchain/output_parsers/retry.py +3 -3
  71. langchain/retrievers/contextual_compression.py +0 -2
  72. langchain/retrievers/document_compressors/base.py +0 -2
  73. langchain/retrievers/document_compressors/chain_filter.py +1 -1
  74. langchain/retrievers/document_compressors/cohere_rerank.py +2 -4
  75. langchain/retrievers/document_compressors/cross_encoder_rerank.py +1 -4
  76. langchain/retrievers/document_compressors/embeddings_filter.py +3 -4
  77. langchain/retrievers/document_compressors/listwise_rerank.py +1 -1
  78. langchain/retrievers/multi_query.py +4 -2
  79. langchain/retrievers/re_phraser.py +1 -1
  80. langchain/retrievers/self_query/base.py +11 -3
  81. langchain/retrievers/time_weighted_retriever.py +0 -2
  82. {langchain-0.2.11.dist-info → langchain-0.2.13.dist-info}/METADATA +2 -2
  83. {langchain-0.2.11.dist-info → langchain-0.2.13.dist-info}/RECORD +86 -86
  84. {langchain-0.2.11.dist-info → langchain-0.2.13.dist-info}/LICENSE +0 -0
  85. {langchain-0.2.11.dist-info → langchain-0.2.13.dist-info}/WHEEL +0 -0
  86. {langchain-0.2.11.dist-info → langchain-0.2.13.dist-info}/entry_points.txt +0 -0
@@ -102,6 +102,13 @@ def init_chat_model(
102
102
 
103
103
  .. versionchanged:: 0.2.8
104
104
 
105
+ Support for ``configurable_fields`` and ``config_prefix`` added.
106
+
107
+ .. versionchanged:: 0.2.12
108
+
109
+ Support for Ollama via langchain-ollama package added. Previously
110
+ langchain-community version of Ollama (now deprecated) was installed by default.
111
+
105
112
  Args:
106
113
  model: The name of the model, e.g. "gpt-4o", "claude-3-opus-20240229".
107
114
  model_provider: The model provider. Supported model_provider values and the
@@ -118,7 +125,7 @@ def init_chat_model(
118
125
  - mistralai (langchain-mistralai)
119
126
  - huggingface (langchain-huggingface)
120
127
  - groq (langchain-groq)
121
- - ollama (langchain-community)
128
+ - ollama (langchain-ollama) [support added in langchain==0.2.12]
122
129
 
123
130
  Will attempt to infer model_provider from model if not specified. The
124
131
  following providers will be inferred based on these model prefixes:
@@ -336,8 +343,18 @@ def _init_chat_model_helper(
336
343
 
337
344
  return ChatFireworks(model=model, **kwargs)
338
345
  elif model_provider == "ollama":
339
- _check_pkg("langchain_community")
340
- from langchain_community.chat_models import ChatOllama
346
+ try:
347
+ _check_pkg("langchain_ollama")
348
+ from langchain_ollama import ChatOllama
349
+ except ImportError:
350
+ # For backwards compatibility
351
+ try:
352
+ _check_pkg("langchain_community")
353
+ from langchain_community.chat_models import ChatOllama
354
+ except ImportError:
355
+ # If both langchain-ollama and langchain-community aren't available,
356
+ # raise an error related to langchain-ollama
357
+ _check_pkg("langchain_ollama")
341
358
 
342
359
  return ChatOllama(model=model, **kwargs)
343
360
  elif model_provider == "together":
@@ -366,6 +383,11 @@ def _init_chat_model_helper(
366
383
 
367
384
  # TODO: update to use model= once ChatBedrock supports
368
385
  return ChatBedrock(model_id=model, **kwargs)
386
+ elif model_provider == "bedrock_converse":
387
+ _check_pkg("langchain_aws")
388
+ from langchain_aws import ChatBedrockConverse
389
+
390
+ return ChatBedrockConverse(model=model, **kwargs)
369
391
  else:
370
392
  supported = ", ".join(_SUPPORTED_PROVIDERS)
371
393
  raise ValueError(
@@ -388,6 +410,7 @@ _SUPPORTED_PROVIDERS = {
388
410
  "huggingface",
389
411
  "groq",
390
412
  "bedrock",
413
+ "bedrock_converse",
391
414
  }
392
415
 
393
416
 
@@ -28,7 +28,7 @@ from langchain_core.exceptions import OutputParserException
28
28
  from langchain_core.language_models import BaseLanguageModel
29
29
  from langchain_core.language_models.chat_models import BaseChatModel
30
30
  from langchain_core.output_parsers import BaseOutputParser
31
- from langchain_core.pydantic_v1 import Extra, Field
31
+ from langchain_core.pydantic_v1 import Field
32
32
  from langchain_core.tools import BaseTool
33
33
 
34
34
  from langchain.chains.llm import LLMChain
@@ -157,9 +157,7 @@ class TrajectoryEvalChain(AgentTrajectoryEvaluator, LLMEvalChain):
157
157
  """DEPRECATED. Reasoning always returned."""
158
158
 
159
159
  class Config:
160
- """Configuration for the QAEvalChain."""
161
-
162
- extra = Extra.ignore
160
+ extra = "ignore"
163
161
 
164
162
  @property
165
163
  def requires_reference(self) -> bool:
@@ -283,8 +281,7 @@ The following is the expected answer. Use this to measure correctness:
283
281
 
284
282
  def prep_inputs(self, inputs: Union[Dict[str, Any], Any]) -> Dict[str, str]:
285
283
  """Validate and prep inputs."""
286
- if "reference" not in inputs:
287
- inputs["reference"] = self._format_reference(inputs.get("reference"))
284
+ inputs["reference"] = self._format_reference(inputs.get("reference"))
288
285
  return super().prep_inputs(inputs)
289
286
 
290
287
  def _call(
@@ -10,7 +10,7 @@ from langchain_core.callbacks.manager import Callbacks
10
10
  from langchain_core.language_models import BaseLanguageModel
11
11
  from langchain_core.output_parsers import BaseOutputParser
12
12
  from langchain_core.prompts.prompt import PromptTemplate
13
- from langchain_core.pydantic_v1 import Extra, Field
13
+ from langchain_core.pydantic_v1 import Field
14
14
 
15
15
  from langchain.chains.constitutional_ai.models import ConstitutionalPrinciple
16
16
  from langchain.chains.llm import LLMChain
@@ -192,9 +192,7 @@ class PairwiseStringEvalChain(PairwiseStringEvaluator, LLMEvalChain, LLMChain):
192
192
  return False
193
193
 
194
194
  class Config:
195
- """Configuration for the PairwiseStringEvalChain."""
196
-
197
- extra = Extra.ignore
195
+ extra = "ignore"
198
196
 
199
197
  @property
200
198
  def requires_reference(self) -> bool:
@@ -8,7 +8,7 @@ from langchain_core.callbacks.manager import Callbacks
8
8
  from langchain_core.language_models import BaseLanguageModel
9
9
  from langchain_core.output_parsers import BaseOutputParser
10
10
  from langchain_core.prompts import BasePromptTemplate
11
- from langchain_core.pydantic_v1 import Extra, Field
11
+ from langchain_core.pydantic_v1 import Field
12
12
 
13
13
  from langchain.chains.constitutional_ai.models import ConstitutionalPrinciple
14
14
  from langchain.chains.llm import LLMChain
@@ -237,9 +237,7 @@ class CriteriaEvalChain(StringEvaluator, LLMEvalChain, LLMChain):
237
237
  return False
238
238
 
239
239
  class Config:
240
- """Configuration for the QAEvalChain."""
241
-
242
- extra = Extra.ignore
240
+ extra = "ignore"
243
241
 
244
242
  @property
245
243
  def requires_reference(self) -> bool:
@@ -10,7 +10,8 @@ from langchain_core.callbacks.manager import (
10
10
  Callbacks,
11
11
  )
12
12
  from langchain_core.embeddings import Embeddings
13
- from langchain_core.pydantic_v1 import Field, root_validator
13
+ from langchain_core.pydantic_v1 import Field
14
+ from langchain_core.utils import pre_init
14
15
 
15
16
  from langchain.chains.base import Chain
16
17
  from langchain.evaluation.schema import PairwiseStringEvaluator, StringEvaluator
@@ -68,7 +69,7 @@ class _EmbeddingDistanceChainMixin(Chain):
68
69
  embeddings: Embeddings = Field(default_factory=_embedding_factory)
69
70
  distance_metric: EmbeddingDistance = Field(default=EmbeddingDistance.COSINE)
70
71
 
71
- @root_validator(pre=False)
72
+ @pre_init
72
73
  def _validate_tiktoken_installed(cls, values: Dict[str, Any]) -> Dict[str, Any]:
73
74
  """Validate that the TikTok library is installed.
74
75
 
@@ -113,8 +114,6 @@ class _EmbeddingDistanceChainMixin(Chain):
113
114
  return values
114
115
 
115
116
  class Config:
116
- """Permit embeddings to go unvalidated."""
117
-
118
117
  arbitrary_types_allowed: bool = True
119
118
 
120
119
  @property
@@ -36,7 +36,7 @@ class JsonSchemaEvaluator(StringEvaluator):
36
36
  """Initializes the JsonSchemaEvaluator.
37
37
 
38
38
  Args:
39
- **kwargs: Additional keyword arguments.
39
+ kwargs: Additional keyword arguments.
40
40
 
41
41
  Raises:
42
42
  ImportError: If the jsonschema package is not installed.
@@ -9,7 +9,6 @@ from typing import Any, List, Optional, Sequence, Tuple
9
9
  from langchain_core.callbacks.manager import Callbacks
10
10
  from langchain_core.language_models import BaseLanguageModel
11
11
  from langchain_core.prompts import PromptTemplate
12
- from langchain_core.pydantic_v1 import Extra
13
12
 
14
13
  from langchain.chains.llm import LLMChain
15
14
  from langchain.evaluation.qa.eval_prompt import CONTEXT_PROMPT, COT_PROMPT, PROMPT
@@ -74,9 +73,7 @@ class QAEvalChain(LLMChain, StringEvaluator, LLMEvalChain):
74
73
  output_key: str = "results" #: :meta private:
75
74
 
76
75
  class Config:
77
- """Configuration for the QAEvalChain."""
78
-
79
- extra = Extra.ignore
76
+ extra = "ignore"
80
77
 
81
78
  @classmethod
82
79
  def is_lc_serializable(cls) -> bool:
@@ -224,9 +221,7 @@ class ContextQAEvalChain(LLMChain, StringEvaluator, LLMEvalChain):
224
221
  return True
225
222
 
226
223
  class Config:
227
- """Configuration for the QAEvalChain."""
228
-
229
- extra = Extra.ignore
224
+ extra = "ignore"
230
225
 
231
226
  @classmethod
232
227
  def _validate_input_vars(cls, prompt: PromptTemplate) -> None:
@@ -158,7 +158,7 @@ class StringEvaluator(_EvalArgsMixin, ABC):
158
158
  prediction (str): The LLM or chain prediction to evaluate.
159
159
  reference (Optional[str], optional): The reference label to evaluate against.
160
160
  input (Optional[str], optional): The input to consider during evaluation.
161
- **kwargs: Additional keyword arguments, including callbacks, tags, etc.
161
+ kwargs: Additional keyword arguments, including callbacks, tags, etc.
162
162
  Returns:
163
163
  dict: The evaluation results containing the score or value.
164
164
  It is recommended that the dictionary contain the following keys:
@@ -181,7 +181,7 @@ class StringEvaluator(_EvalArgsMixin, ABC):
181
181
  prediction (str): The LLM or chain prediction to evaluate.
182
182
  reference (Optional[str], optional): The reference label to evaluate against.
183
183
  input (Optional[str], optional): The input to consider during evaluation.
184
- **kwargs: Additional keyword arguments, including callbacks, tags, etc.
184
+ kwargs: Additional keyword arguments, including callbacks, tags, etc.
185
185
  Returns:
186
186
  dict: The evaluation results containing the score or value.
187
187
  It is recommended that the dictionary contain the following keys:
@@ -212,7 +212,7 @@ class StringEvaluator(_EvalArgsMixin, ABC):
212
212
  prediction (str): The LLM or chain prediction to evaluate.
213
213
  reference (Optional[str], optional): The reference label to evaluate against.
214
214
  input (Optional[str], optional): The input to consider during evaluation.
215
- **kwargs: Additional keyword arguments, including callbacks, tags, etc.
215
+ kwargs: Additional keyword arguments, including callbacks, tags, etc.
216
216
  Returns:
217
217
  dict: The evaluation results containing the score or value.
218
218
  """ # noqa: E501
@@ -235,7 +235,7 @@ class StringEvaluator(_EvalArgsMixin, ABC):
235
235
  prediction (str): The LLM or chain prediction to evaluate.
236
236
  reference (Optional[str], optional): The reference label to evaluate against.
237
237
  input (Optional[str], optional): The input to consider during evaluation.
238
- **kwargs: Additional keyword arguments, including callbacks, tags, etc.
238
+ kwargs: Additional keyword arguments, including callbacks, tags, etc.
239
239
  Returns:
240
240
  dict: The evaluation results containing the score or value.
241
241
  """ # noqa: E501
@@ -265,7 +265,7 @@ class PairwiseStringEvaluator(_EvalArgsMixin, ABC):
265
265
  prediction_b (str): The output string from the second model.
266
266
  reference (Optional[str], optional): The expected output / reference string.
267
267
  input (Optional[str], optional): The input string.
268
- **kwargs: Additional keyword arguments, such as callbacks and optional reference strings.
268
+ kwargs: Additional keyword arguments, such as callbacks and optional reference strings.
269
269
  Returns:
270
270
  dict: A dictionary containing the preference, scores, and/or other information.
271
271
  """ # noqa: E501
@@ -286,7 +286,7 @@ class PairwiseStringEvaluator(_EvalArgsMixin, ABC):
286
286
  prediction_b (str): The output string from the second model.
287
287
  reference (Optional[str], optional): The expected output / reference string.
288
288
  input (Optional[str], optional): The input string.
289
- **kwargs: Additional keyword arguments, such as callbacks and optional reference strings.
289
+ kwargs: Additional keyword arguments, such as callbacks and optional reference strings.
290
290
  Returns:
291
291
  dict: A dictionary containing the preference, scores, and/or other information.
292
292
  """ # noqa: E501
@@ -316,7 +316,7 @@ class PairwiseStringEvaluator(_EvalArgsMixin, ABC):
316
316
  prediction_b (str): The output string from the second model.
317
317
  reference (Optional[str], optional): The expected output / reference string.
318
318
  input (Optional[str], optional): The input string.
319
- **kwargs: Additional keyword arguments, such as callbacks and optional reference strings.
319
+ kwargs: Additional keyword arguments, such as callbacks and optional reference strings.
320
320
  Returns:
321
321
  dict: A dictionary containing the preference, scores, and/or other information.
322
322
  """ # noqa: E501
@@ -345,7 +345,7 @@ class PairwiseStringEvaluator(_EvalArgsMixin, ABC):
345
345
  prediction_b (str): The output string from the second model.
346
346
  reference (Optional[str], optional): The expected output / reference string.
347
347
  input (Optional[str], optional): The input string.
348
- **kwargs: Additional keyword arguments, such as callbacks and optional reference strings.
348
+ kwargs: Additional keyword arguments, such as callbacks and optional reference strings.
349
349
  Returns:
350
350
  dict: A dictionary containing the preference, scores, and/or other information.
351
351
  """ # noqa: E501
@@ -10,7 +10,7 @@ from langchain_core.callbacks.manager import Callbacks
10
10
  from langchain_core.language_models import BaseLanguageModel
11
11
  from langchain_core.output_parsers import BaseOutputParser
12
12
  from langchain_core.prompts.prompt import PromptTemplate
13
- from langchain_core.pydantic_v1 import Extra, Field
13
+ from langchain_core.pydantic_v1 import Field
14
14
 
15
15
  from langchain.chains.constitutional_ai.models import ConstitutionalPrinciple
16
16
  from langchain.chains.llm import LLMChain
@@ -180,9 +180,7 @@ class ScoreStringEvalChain(StringEvaluator, LLMEvalChain, LLMChain):
180
180
  """The name of the criterion being evaluated."""
181
181
 
182
182
  class Config:
183
- """Configuration for the ScoreStringEvalChain."""
184
-
185
- extra = Extra.ignore
183
+ extra = "ignore"
186
184
 
187
185
  @classmethod
188
186
  def is_lc_serializable(cls) -> bool:
@@ -8,7 +8,8 @@ from langchain_core.callbacks.manager import (
8
8
  CallbackManagerForChainRun,
9
9
  Callbacks,
10
10
  )
11
- from langchain_core.pydantic_v1 import Field, root_validator
11
+ from langchain_core.pydantic_v1 import Field
12
+ from langchain_core.utils import pre_init
12
13
 
13
14
  from langchain.chains.base import Chain
14
15
  from langchain.evaluation.schema import PairwiseStringEvaluator, StringEvaluator
@@ -63,7 +64,7 @@ class _RapidFuzzChainMixin(Chain):
63
64
  """Whether to normalize the score to a value between 0 and 1.
64
65
  Applies only to the Levenshtein and Damerau-Levenshtein distances."""
65
66
 
66
- @root_validator
67
+ @pre_init
67
68
  def validate_dependencies(cls, values: Dict[str, Any]) -> Dict[str, Any]:
68
69
  """
69
70
  Validate that the rapidfuzz library is installed.
@@ -277,7 +278,7 @@ class StringDistanceEvalChain(StringEvaluator, _RapidFuzzChainMixin):
277
278
  reference (Optional[str], optional): The reference string.
278
279
  input (Optional[str], optional): The input string.
279
280
  callbacks (Callbacks, optional): The callbacks to use.
280
- **kwargs: Additional keyword arguments.
281
+ kwargs: Additional keyword arguments.
281
282
 
282
283
  Returns:
283
284
  dict: The evaluation results containing the score.
@@ -313,7 +314,7 @@ class StringDistanceEvalChain(StringEvaluator, _RapidFuzzChainMixin):
313
314
  reference (Optional[str], optional): The reference string.
314
315
  input (Optional[str], optional): The input string.
315
316
  callbacks (Callbacks, optional): The callbacks to use.
316
- **kwargs: Additional keyword arguments.
317
+ kwargs: Additional keyword arguments.
317
318
 
318
319
  Returns:
319
320
  dict: The evaluation results containing the score.
@@ -411,7 +412,7 @@ class PairwiseStringDistanceEvalChain(PairwiseStringEvaluator, _RapidFuzzChainMi
411
412
  callbacks (Callbacks, optional): The callbacks to use.
412
413
  tags (List[str], optional): Tags to apply to traces.
413
414
  metadata (Dict[str, Any], optional): Metadata to apply to traces.
414
- **kwargs: Additional keyword arguments.
415
+ kwargs: Additional keyword arguments.
415
416
 
416
417
  Returns:
417
418
  dict: The evaluation results containing the score.
@@ -445,7 +446,7 @@ class PairwiseStringDistanceEvalChain(PairwiseStringEvaluator, _RapidFuzzChainMi
445
446
  callbacks (Callbacks, optional): The callbacks to use.
446
447
  tags (List[str], optional): Tags to apply to traces.
447
448
  metadata (Dict[str, Any], optional): Metadata to apply to traces.
448
- **kwargs: Additional keyword arguments.
449
+ kwargs: Additional keyword arguments.
449
450
 
450
451
  Returns:
451
452
  dict: The evaluation results containing the score.
langchain/hub.py CHANGED
@@ -3,27 +3,37 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import json
6
- from typing import TYPE_CHECKING, Any, Optional
6
+ from typing import Any, Optional, Sequence
7
7
 
8
8
  from langchain_core.load.dump import dumps
9
9
  from langchain_core.load.load import loads
10
10
  from langchain_core.prompts import BasePromptTemplate
11
11
 
12
- if TYPE_CHECKING:
13
- from langchainhub import Client
14
12
 
15
-
16
- def _get_client(api_url: Optional[str] = None, api_key: Optional[str] = None) -> Client:
13
+ def _get_client(
14
+ api_key: Optional[str] = None,
15
+ api_url: Optional[str] = None,
16
+ ) -> Any:
17
17
  try:
18
- from langchainhub import Client
19
- except ImportError as e:
20
- raise ImportError(
21
- "Could not import langchainhub, please install with `pip install "
22
- "langchainhub`."
23
- ) from e
18
+ from langsmith import Client as LangSmithClient
19
+
20
+ ls_client = LangSmithClient(api_url, api_key=api_key)
21
+ if hasattr(ls_client, "push_prompt") and hasattr(ls_client, "pull_prompt"):
22
+ return ls_client
23
+ else:
24
+ from langchainhub import Client as LangChainHubClient
24
25
 
25
- # Client logic will also attempt to load URL/key from environment variables
26
- return Client(api_url, api_key=api_key)
26
+ return LangChainHubClient(api_url, api_key=api_key)
27
+ except ImportError:
28
+ try:
29
+ from langchainhub import Client as LangChainHubClient
30
+
31
+ return LangChainHubClient(api_url, api_key=api_key)
32
+ except ImportError as e:
33
+ raise ImportError(
34
+ "Could not import langsmith or langchainhub (deprecated),"
35
+ "please install with `pip install langsmith`."
36
+ ) from e
27
37
 
28
38
 
29
39
  def push(
@@ -32,27 +42,43 @@ def push(
32
42
  *,
33
43
  api_url: Optional[str] = None,
34
44
  api_key: Optional[str] = None,
35
- parent_commit_hash: Optional[str] = "latest",
36
- new_repo_is_public: bool = True,
37
- new_repo_description: str = "",
45
+ parent_commit_hash: Optional[str] = None,
46
+ new_repo_is_public: bool = False,
47
+ new_repo_description: Optional[str] = None,
48
+ readme: Optional[str] = None,
49
+ tags: Optional[Sequence[str]] = None,
38
50
  ) -> str:
39
51
  """
40
52
  Push an object to the hub and returns the URL it can be viewed at in a browser.
41
53
 
42
- :param repo_full_name: The full name of the repo to push to in the format of
43
- `owner/repo`.
54
+ :param repo_full_name: The full name of the prompt to push to in the format of
55
+ `owner/prompt_name` or `prompt_name`.
44
56
  :param object: The LangChain to serialize and push to the hub.
45
57
  :param api_url: The URL of the LangChain Hub API. Defaults to the hosted API service
46
58
  if you have an api key set, or a localhost instance if not.
47
59
  :param api_key: The API key to use to authenticate with the LangChain Hub API.
48
60
  :param parent_commit_hash: The commit hash of the parent commit to push to. Defaults
49
61
  to the latest commit automatically.
50
- :param new_repo_is_public: Whether the repo should be public. Defaults to
51
- True (Public by default).
52
- :param new_repo_description: The description of the repo. Defaults to an empty
62
+ :param new_repo_is_public: Whether the prompt should be public. Defaults to
63
+ False (Private by default).
64
+ :param new_repo_description: The description of the prompt. Defaults to an empty
53
65
  string.
54
66
  """
55
- client = _get_client(api_url=api_url, api_key=api_key)
67
+ client = _get_client(api_key=api_key, api_url=api_url)
68
+
69
+ # Then it's langsmith
70
+ if hasattr(client, "push_prompt"):
71
+ return client.push_prompt(
72
+ repo_full_name,
73
+ object=object,
74
+ parent_commit_hash=parent_commit_hash,
75
+ is_public=new_repo_is_public,
76
+ description=new_repo_description,
77
+ readme=readme,
78
+ tags=tags,
79
+ )
80
+
81
+ # Then it's langchainhub
56
82
  manifest_json = dumps(object)
57
83
  message = client.push(
58
84
  repo_full_name,
@@ -67,20 +93,28 @@ def push(
67
93
  def pull(
68
94
  owner_repo_commit: str,
69
95
  *,
96
+ include_model: Optional[bool] = None,
70
97
  api_url: Optional[str] = None,
71
98
  api_key: Optional[str] = None,
72
99
  ) -> Any:
73
100
  """
74
101
  Pull an object from the hub and returns it as a LangChain object.
75
102
 
76
- :param owner_repo_commit: The full name of the repo to pull from in the format of
77
- `owner/repo:commit_hash`.
103
+ :param owner_repo_commit: The full name of the prompt to pull from in the format of
104
+ `owner/prompt_name:commit_hash` or `owner/prompt_name`
105
+ or just `prompt_name` if it's your own prompt.
78
106
  :param api_url: The URL of the LangChain Hub API. Defaults to the hosted API service
79
107
  if you have an api key set, or a localhost instance if not.
80
108
  :param api_key: The API key to use to authenticate with the LangChain Hub API.
81
109
  """
82
- client = _get_client(api_url=api_url, api_key=api_key)
110
+ client = _get_client(api_key=api_key, api_url=api_url)
111
+
112
+ # Then it's langsmith
113
+ if hasattr(client, "pull_prompt"):
114
+ response = client.pull_prompt(owner_repo_commit, include_model=include_model)
115
+ return response
83
116
 
117
+ # Then it's langchainhub
84
118
  if hasattr(client, "pull_repo"):
85
119
  # >= 0.1.15
86
120
  res_dict = client.pull_repo(owner_repo_commit)
@@ -93,6 +127,6 @@ def pull(
93
127
  obj.metadata["lc_hub_commit_hash"] = res_dict["commit_hash"]
94
128
  return obj
95
129
 
96
- # Then it's < 0.1.15
130
+ # Then it's < 0.1.15 langchainhub
97
131
  resp: str = client.pull(owner_repo_commit)
98
132
  return loads(resp)
@@ -4,7 +4,7 @@ from langchain_core.document_loaders import BaseLoader
4
4
  from langchain_core.documents import Document
5
5
  from langchain_core.embeddings import Embeddings
6
6
  from langchain_core.language_models import BaseLanguageModel
7
- from langchain_core.pydantic_v1 import BaseModel, Extra, Field
7
+ from langchain_core.pydantic_v1 import BaseModel, Field
8
8
  from langchain_core.vectorstores import VectorStore
9
9
  from langchain_text_splitters import RecursiveCharacterTextSplitter, TextSplitter
10
10
 
@@ -22,10 +22,8 @@ class VectorStoreIndexWrapper(BaseModel):
22
22
  vectorstore: VectorStore
23
23
 
24
24
  class Config:
25
- """Configuration for this pydantic object."""
26
-
27
- extra = Extra.forbid
28
25
  arbitrary_types_allowed = True
26
+ extra = "forbid"
29
27
 
30
28
  def query(
31
29
  self,
@@ -145,10 +143,8 @@ class VectorstoreIndexCreator(BaseModel):
145
143
  vectorstore_kwargs: dict = Field(default_factory=dict)
146
144
 
147
145
  class Config:
148
- """Configuration for this pydantic object."""
149
-
150
- extra = Extra.forbid
151
146
  arbitrary_types_allowed = True
147
+ extra = "forbid"
152
148
 
153
149
  def from_loaders(self, loaders: List[BaseLoader]) -> VectorStoreIndexWrapper:
154
150
  """Create a vectorstore index from loaders."""
@@ -1,7 +1,7 @@
1
1
  from typing import Any, Dict, List, Optional
2
2
 
3
3
  from langchain_core.messages import BaseMessage, get_buffer_string
4
- from langchain_core.pydantic_v1 import root_validator
4
+ from langchain_core.utils import pre_init
5
5
 
6
6
  from langchain.memory.chat_memory import BaseChatMemory, BaseMemory
7
7
  from langchain.memory.utils import get_prompt_input_key
@@ -82,7 +82,7 @@ class ConversationStringBufferMemory(BaseMemory):
82
82
  input_key: Optional[str] = None
83
83
  memory_key: str = "history" #: :meta private:
84
84
 
85
- @root_validator()
85
+ @pre_init
86
86
  def validate_chains(cls, values: Dict) -> Dict:
87
87
  """Validate that return messages is not True."""
88
88
  if values.get("return_messages", False):
@@ -246,8 +246,6 @@ class SQLiteEntityStore(BaseEntityStore):
246
246
  conn: Any = None
247
247
 
248
248
  class Config:
249
- """Configuration for this pydantic object."""
250
-
251
249
  arbitrary_types_allowed = True
252
250
 
253
251
  def __init__(
@@ -2,17 +2,27 @@ from __future__ import annotations
2
2
 
3
3
  from typing import Any, Dict, List, Type
4
4
 
5
+ from langchain_core._api import deprecated
5
6
  from langchain_core.chat_history import BaseChatMessageHistory
6
7
  from langchain_core.language_models import BaseLanguageModel
7
8
  from langchain_core.messages import BaseMessage, SystemMessage, get_buffer_string
8
9
  from langchain_core.prompts import BasePromptTemplate
9
- from langchain_core.pydantic_v1 import BaseModel, root_validator
10
+ from langchain_core.pydantic_v1 import BaseModel
11
+ from langchain_core.utils import pre_init
10
12
 
11
13
  from langchain.chains.llm import LLMChain
12
14
  from langchain.memory.chat_memory import BaseChatMemory
13
15
  from langchain.memory.prompt import SUMMARY_PROMPT
14
16
 
15
17
 
18
+ @deprecated(
19
+ since="0.2.12",
20
+ removal="1.0",
21
+ message=(
22
+ "Refer here for how to incorporate summaries of conversation history: "
23
+ "https://langchain-ai.github.io/langgraph/how-tos/memory/add-summary-conversation-history/" # noqa: E501
24
+ ),
25
+ )
16
26
  class SummarizerMixin(BaseModel):
17
27
  """Mixin for summarizer."""
18
28
 
@@ -85,7 +95,7 @@ class ConversationSummaryMemory(BaseChatMemory, SummarizerMixin):
85
95
  buffer = self.buffer
86
96
  return {self.memory_key: buffer}
87
97
 
88
- @root_validator()
98
+ @pre_init
89
99
  def validate_prompt_input_variables(cls, values: Dict) -> Dict:
90
100
  """Validate that prompt input variables are consistent."""
91
101
  prompt_variables = values["prompt"].input_variables
@@ -1,7 +1,7 @@
1
1
  from typing import Any, Dict, List, Union
2
2
 
3
3
  from langchain_core.messages import BaseMessage, get_buffer_string
4
- from langchain_core.pydantic_v1 import root_validator
4
+ from langchain_core.utils import pre_init
5
5
 
6
6
  from langchain.memory.chat_memory import BaseChatMemory
7
7
  from langchain.memory.summary import SummarizerMixin
@@ -64,7 +64,7 @@ class ConversationSummaryBufferMemory(BaseChatMemory, SummarizerMixin):
64
64
  )
65
65
  return {self.memory_key: final_buffer}
66
66
 
67
- @root_validator()
67
+ @pre_init
68
68
  def validate_prompt_input_variables(cls, values: Dict) -> Dict:
69
69
  """Validate that prompt input variables are consistent."""
70
70
  prompt_variables = values["prompt"].input_variables
@@ -3,7 +3,7 @@ from __future__ import annotations
3
3
  from typing import Any, Dict, List
4
4
 
5
5
  from langchain_core.output_parsers import BaseOutputParser
6
- from langchain_core.pydantic_v1 import root_validator
6
+ from langchain_core.utils import pre_init
7
7
 
8
8
 
9
9
  class CombiningOutputParser(BaseOutputParser[Dict[str, Any]]):
@@ -15,7 +15,7 @@ class CombiningOutputParser(BaseOutputParser[Dict[str, Any]]):
15
15
  def is_lc_serializable(cls) -> bool:
16
16
  return True
17
17
 
18
- @root_validator()
18
+ @pre_init
19
19
  def validate_parsers(cls, values: Dict[str, Any]) -> Dict[str, Any]:
20
20
  """Validate the parsers."""
21
21
  parsers = values["parsers"]
@@ -3,7 +3,7 @@ from typing import Dict, List, Type
3
3
 
4
4
  from langchain_core.exceptions import OutputParserException
5
5
  from langchain_core.output_parsers import BaseOutputParser
6
- from langchain_core.pydantic_v1 import root_validator
6
+ from langchain_core.utils import pre_init
7
7
 
8
8
 
9
9
  class EnumOutputParser(BaseOutputParser[Enum]):
@@ -12,7 +12,7 @@ class EnumOutputParser(BaseOutputParser[Enum]):
12
12
  enum: Type[Enum]
13
13
  """The enum to parse. Its values must be strings."""
14
14
 
15
- @root_validator()
15
+ @pre_init
16
16
  def raise_deprecation(cls, values: Dict) -> Dict:
17
17
  enum = values["enum"]
18
18
  if not all(isinstance(e.value, str) for e in enum):