The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
docs: langchain docstrings updates (#21032)
Leonid Ganeline08d08d7c83d3
diff --git a/libs/langchain/langchain/chains/graph_qa/kuzu.py b/libs/langchain/langchain/chains/graph_qa/kuzu.pyindex 61b044a885..aa1b51deb1 100644--- a/libs/langchain/langchain/chains/graph_qa/kuzu.py+++ b/libs/langchain/langchain/chains/graph_qa/kuzu.py@@ -16,6 +16,15 @@ from langchain.chains.llm import LLMChaindef remove_prefix(text: str, prefix: str) -> str:+ """Remove a prefix from a text.++ Args:+ text: Text to remove the prefix from.+ prefix: Prefix to remove from the text.++ Returns:+ Text with the prefix removed.+ """if text.startswith(prefix):return text[len(prefix) :]return textdiff --git a/libs/langchain/langchain/chains/graph_qa/neptune_sparql.py b/libs/langchain/langchain/chains/graph_qa/neptune_sparql.pyindex a47053a2e3..d1e9a2f2e6 100644--- a/libs/langchain/langchain/chains/graph_qa/neptune_sparql.py+++ b/libs/langchain/langchain/chains/graph_qa/neptune_sparql.py@@ -54,6 +54,14 @@ SPARQL_GENERATION_PROMPT = PromptTemplate(def extract_sparql(query: str) -> str:+ """Extract SPARQL code from a text.++ Args:+ query: Text to extract SPARQL code from.++ Returns:+ SPARQL code extracted from the text.+ """query = query.strip()querytoks = query.split("```")if len(querytoks) == 3:diff --git a/libs/langchain/langchain/chains/openai_functions/tagging.py b/libs/langchain/langchain/chains/openai_functions/tagging.pyindex 6cc965f951..e96a138dfd 100644--- a/libs/langchain/langchain/chains/openai_functions/tagging.py+++ b/libs/langchain/langchain/chains/openai_functions/tagging.py@@ -35,7 +35,7 @@ def create_tagging_chain(prompt: Optional[ChatPromptTemplate] = None,**kwargs: Any,) -> Chain:- """Creates a chain that extracts information from a passage+ """Create a chain that extracts information from a passagebased on a schema.Args:@@ -65,7 +65,7 @@ def create_tagging_chain_pydantic(prompt: Optional[ChatPromptTemplate] = None,**kwargs: Any,) -> Chain:- """Creates a chain that extracts information from a passage+ """Create a chain that extracts information from a passagebased on a pydantic schema.Args:diff --git a/libs/langchain/langchain/chains/openai_functions/utils.py b/libs/langchain/langchain/chains/openai_functions/utils.pyindex 69f08b119c..c2db844748 100644--- a/libs/langchain/langchain/chains/openai_functions/utils.py+++ b/libs/langchain/langchain/chains/openai_functions/utils.py@@ -3,7 +3,7 @@ from typing import Any, Dictdef _resolve_schema_references(schema: Any, definitions: Dict[str, Any]) -> Any:"""- Resolves the $ref keys in a JSON schema object using the provided definitions.+ Resolve the $ref keys in a JSON schema object using the provided definitions."""if isinstance(schema, list):for i, item in enumerate(schema):@@ -29,7 +29,7 @@ def _convert_schema(schema: dict) -> dict:def get_llm_kwargs(function: dict) -> dict:- """Returns the kwargs for the LLMChain constructor.+ """Return the kwargs for the LLMChain constructor.Args:function: The function to use.diff --git a/libs/langchain/langchain/chains/query_constructor/parser.py b/libs/langchain/langchain/chains/query_constructor/parser.pyindex 04e457ddb9..af65c99ff2 100644--- a/libs/langchain/langchain/chains/query_constructor/parser.py+++ b/libs/langchain/langchain/chains/query_constructor/parser.py@@ -63,7 +63,7 @@ class ISO8601Date(TypedDict):@v_args(inline=True)class QueryTransformer(Transformer):- """Transforms a query string into an intermediate representation."""+ """Transform a query string into an intermediate representation."""def __init__(self,@@ -159,8 +159,7 @@ def get_parser(allowed_operators: Optional[Sequence[Operator]] = None,allowed_attributes: Optional[Sequence[str]] = None,) -> Lark:- """- Returns a parser for the query language.+ """Return a parser for the query language.Args:allowed_comparators: Optional[Sequence[Comparator]]diff --git a/libs/langchain/langchain/evaluation/parsing/base.py b/libs/langchain/langchain/evaluation/parsing/base.pyindex fa8bb395a3..0e25c34469 100644--- a/libs/langchain/langchain/evaluation/parsing/base.py+++ b/libs/langchain/langchain/evaluation/parsing/base.py@@ -9,7 +9,7 @@ from langchain.evaluation.schema import StringEvaluatorclass JsonValidityEvaluator(StringEvaluator):- """Evaluates whether the prediction is valid JSON.+ """Evaluate whether the prediction is valid JSON.This evaluator checks if the prediction is a valid JSON string. It does notrequire any input or reference.@@ -77,7 +77,7 @@ class JsonValidityEvaluator(StringEvaluator):class JsonEqualityEvaluator(StringEvaluator):- """Evaluates whether the prediction is equal to the reference after+ """Evaluate whether the prediction is equal to the reference afterparsing both as JSON.This evaluator checks if the prediction, after parsing as JSON, is equaldiff --git a/libs/langchain/langchain/hub.py b/libs/langchain/langchain/hub.pyindex 3dd15404d2..adaf0de05f 100644--- a/libs/langchain/langchain/hub.py+++ b/libs/langchain/langchain/hub.py@@ -37,7 +37,7 @@ def push(new_repo_description: str = "",) -> str:"""- Pushes an object to the hub and returns the URL it can be viewed at in a browser.+ Push an object to the hub and returns the URL it can be viewed at in a browser.:param repo_full_name: The full name of the repo to push to in the format of`owner/repo`.@@ -71,7 +71,7 @@ def pull(api_key: Optional[str] = None,) -> Any:"""- Pulls an object from the hub and returns it as a LangChain object.+ Pull an object from the hub and returns it as a LangChain object.:param owner_repo_commit: The full name of the repo to pull from in the format of`owner/repo:commit_hash`.diff --git a/libs/langchain/langchain/memory/readonly.py b/libs/langchain/langchain/memory/readonly.pyindex a564edb800..94aa4c12cf 100644--- a/libs/langchain/langchain/memory/readonly.py+++ b/libs/langchain/langchain/memory/readonly.py@@ -4,7 +4,7 @@ from langchain_core.memory import BaseMemoryclass ReadOnlySharedMemory(BaseMemory):- """A memory wrapper that is read-only and cannot be changed."""+ """Memory wrapper that is read-only and cannot be changed."""memory: BaseMemorydiff --git a/libs/langchain/langchain/output_parsers/fix.py b/libs/langchain/langchain/output_parsers/fix.pyindex 036fd1ee0b..7b6e5a3442 100644--- a/libs/langchain/langchain/output_parsers/fix.py+++ b/libs/langchain/langchain/output_parsers/fix.py@@ -13,7 +13,7 @@ T = TypeVar("T")class OutputFixingParser(BaseOutputParser[T]):- """Wraps a parser and tries to fix parsing errors."""+ """Wrap a parser and try to fix parsing errors."""@classmethoddef is_lc_serializable(cls) -> bool:diff --git a/libs/langchain/langchain/output_parsers/retry.py b/libs/langchain/langchain/output_parsers/retry.pyindex 15d2a1978b..571362f012 100644--- a/libs/langchain/langchain/output_parsers/retry.py+++ b/libs/langchain/langchain/output_parsers/retry.py@@ -34,7 +34,7 @@ T = TypeVar("T")class RetryOutputParser(BaseOutputParser[T]):- """Wraps a parser and tries to fix parsing errors.+ """Wrap a parser and try to fix parsing errors.Does this by passing the original prompt and the completion to anotherLLM, and telling it the completion did not satisfy criteria in the prompt.@@ -138,7 +138,7 @@ class RetryOutputParser(BaseOutputParser[T]):class RetryWithErrorOutputParser(BaseOutputParser[T]):- """Wraps a parser and tries to fix parsing errors.+ """Wrap a parser and try to fix parsing errors.Does this by passing the original prompt, the completion, AND the errorthat was raised to another language model and telling it that the completiondiff --git a/libs/langchain/langchain/output_parsers/structured.py b/libs/langchain/langchain/output_parsers/structured.pyindex 62847e1dd1..57abb7f2c8 100644--- a/libs/langchain/langchain/output_parsers/structured.py+++ b/libs/langchain/langchain/output_parsers/structured.py@@ -15,7 +15,7 @@ line_template = '\t"{name}": {type} // {description}'class ResponseSchema(BaseModel):- """A schema for a response from a structured output parser."""+ """Schema for a response from a structured output parser."""name: str"""The name of the schema."""diff --git a/libs/langchain/langchain/retrievers/ensemble.py b/libs/langchain/langchain/retrievers/ensemble.pyindex 937a5e5549..61f2bfdcb1 100644--- a/libs/langchain/langchain/retrievers/ensemble.py+++ b/libs/langchain/langchain/retrievers/ensemble.py@@ -38,6 +38,15 @@ H = TypeVar("H", bound=Hashable)def unique_by_key(iterable: Iterable[T], key: Callable[[T], H]) -> Iterator[T]:+ """Yield unique elements of an iterable based on a key function.++ Args:+ iterable: The iterable to filter.+ key: A function that returns a hashable key for each element.++ Yields:+ Unique elements of the iterable based on the key function.+ """seen = set()for e in iterable:if (k := key(e)) not in seen:diff --git a/libs/langchain/langchain/retrievers/self_query/tencentvectordb.py b/libs/langchain/langchain/retrievers/self_query/tencentvectordb.pyindex 9bed9c1cdd..b1ec31a1a2 100644--- a/libs/langchain/langchain/retrievers/self_query/tencentvectordb.py+++ b/libs/langchain/langchain/retrievers/self_query/tencentvectordb.py@@ -13,6 +13,8 @@ from langchain_core.structured_query import (class TencentVectorDBTranslator(Visitor):+ """Translate StructuredQuery to Tencent VectorDB query."""+COMPARATOR_MAP = {Comparator.EQ: "=",Comparator.NE: "!=",@@ -32,9 +34,22 @@ class TencentVectorDBTranslator(Visitor):]def __init__(self, meta_keys: Optional[Sequence[str]] = None):+ """Initialize the translator.++ Args:+ meta_keys: List of meta keys to be used in the query. Default: [].+ """self.meta_keys = meta_keys or []def visit_operation(self, operation: Operation) -> str:+ """Visit an operation node and return the translated query.++ Args:+ operation: Operation node to be visited.++ Returns:+ Translated query.+ """if operation.operator in (Operator.AND, Operator.OR):ret = f" {operation.operator.value} ".join([arg.accept(self) for arg in operation.arguments]@@ -46,6 +61,14 @@ class TencentVectorDBTranslator(Visitor):return f"not ({operation.arguments[0].accept(self)})"def visit_comparison(self, comparison: Comparison) -> str:+ """Visit a comparison node and return the translated query.++ Args:+ comparison: Comparison node to be visited.++ Returns:+ Translated query.+ """if self.meta_keys and comparison.attribute not in self.meta_keys:raise ValueError(f"Expr Filtering found Unsupported attribute: {comparison.attribute}"@@ -78,6 +101,14 @@ class TencentVectorDBTranslator(Visitor):def visit_structured_query(self, structured_query: StructuredQuery) -> Tuple[str, dict]:+ """Visit a structured query node and return the translated query.++ Args:+ structured_query: StructuredQuery node to be visited.++ Returns:+ Translated query and query kwargs.+ """if structured_query.filter is None:kwargs = {}else:diff --git a/libs/langchain/langchain/smith/evaluation/runner_utils.py b/libs/langchain/langchain/smith/evaluation/runner_utils.pyindex 0721906dfa..1df4872a8c 100644--- a/libs/langchain/langchain/smith/evaluation/runner_utils.py+++ b/libs/langchain/langchain/smith/evaluation/runner_utils.py@@ -281,6 +281,12 @@ def _get_prompt(inputs: Dict[str, Any]) -> str:class ChatModelInput(TypedDict):+ """Input for a chat model.++ Parameters:+ messages: List of chat messages.+ """+messages: List[BaseMessage]