id
stringlengths
14
16
text
stringlengths
29
2.73k
source
stringlengths
49
117
0f22ef235fe1-8
maximal_marginal_relevance: Whether to use maximal marginal relevance. Defaults to False. fetch_k: Number of Documents to fetch to pass to MMR algorithm. Defaults to 20. return_score: Whether to return the score. Defaults to False. Returns: Lis...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
0f22ef235fe1-9
filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None. Returns: List[Tuple[Document, float]]: List of documents most similar to the query text with distance in float. """ return self._search_helper( query=query, k=k, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
0f22ef235fe1-10
self, query: str, k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any, ) -> List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity amon...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
0f22ef235fe1-11
) -> DeepLake: """Create a Deep Lake dataset from a raw documents. If a dataset_path is specified, the dataset will be persisted in that location, otherwise by default at `./deeplake` Args: path (str, pathlib.Path): - The full path to the dataset. Can be: - De...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
0f22ef235fe1-12
dataset_path=dataset_path, embedding_function=embedding, **kwargs ) deeplake_dataset.add_texts(texts=texts, metadatas=metadatas, ids=ids) return deeplake_dataset [docs] def delete( self, ids: Any[List[str], None] = None, filter: Any[Dict[str, str], None] = None, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
0f22ef235fe1-13
try: import deeplake except ImportError: raise ValueError( "Could not import deeplake python package. " "Please install it with `pip install deeplake`." ) deeplake.delete(path, large_ok=True, force=True) [docs] def delete_dataset(sel...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/deeplake.html
0a4f735a1e47-0
Source code for langchain.vectorstores.weaviate """Wrapper around weaviate vector database.""" from __future__ import annotations import datetime from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Type from uuid import uuid4 import numpy as np from langchain.docstore.document import Document from ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
0a4f735a1e47-1
if weaviate_api_key is not None else None ) client = weaviate.Client(weaviate_url, auth_client_secret=auth) return client def _default_score_normalizer(val: float) -> float: return 1 - 1 / (1 + np.exp(val)) def _json_serializable(value: Any) -> Any: if isinstance(value, datetime.datetime): ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
0a4f735a1e47-2
) if not isinstance(client, weaviate.Client): raise ValueError( f"client should be an instance of weaviate.Client, got {type(client)}" ) self._client = client self._index_name = index_name self._embedding = embedding self._text_key = text_k...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
0a4f735a1e47-3
class_name=self._index_name, uuid=_id, vector=vector, ) ids.append(_id) return ids [docs] def similarity_search( self, query: str, k: int = 4, **kwargs: Any ) -> List[Document]: """Return docs most similar to query. ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
0a4f735a1e47-4
if kwargs.get("where_filter"): query_obj = query_obj.with_where(kwargs.get("where_filter")) if kwargs.get("additional"): query_obj = query_obj.with_additional(kwargs.get("additional")) result = query_obj.with_near_text(content).with_limit(k).do() if "errors" in result: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
0a4f735a1e47-5
k: int = 4, fetch_k: int = 20, lambda_mult: float = 0.5, **kwargs: Any, ) -> List[Document]: """Return docs selected using the maximal marginal relevance. Maximal marginal relevance optimizes for similarity to query AND diversity among selected documents. Args...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
0a4f735a1e47-6
Args: embedding: Embedding to look up documents similar to. k: Number of Documents to return. Defaults to 4. fetch_k: Number of Documents to fetch to pass to MMR algorithm. lambda_mult: Number between 0 and 1 that determines the degree of diversity...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
0a4f735a1e47-7
raise ValueError( "_embedding cannot be None for similarity_search_with_score" ) content: Dict[str, Any] = {"concepts": [query]} if kwargs.get("search_distance"): content["certainty"] = kwargs.get("search_distance") query_obj = self._client.query.get(self....
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
0a4f735a1e47-8
""" if self._relevance_score_fn is None: raise ValueError( "relevance_score_fn must be provided to" " Weaviate constructor to normalize scores" ) docs_and_scores = self.similarity_search_with_score(query, k=k, **kwargs) return [ ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
0a4f735a1e47-9
text_key = "text" schema = _default_schema(index_name) attributes = list(metadatas[0].keys()) if metadatas else None # check whether the index already exists if not client.schema.contains(schema): client.schema.create_class(schema) with client.batch as batch: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
0a4f735a1e47-10
relevance_score_fn=relevance_score_fn, by_text=by_text, ) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 29, 2023.
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/weaviate.html
23d0298bdaff-0
Source code for langchain.vectorstores.typesense """Wrapper around Typesense vector search""" from __future__ import annotations import uuid from typing import TYPE_CHECKING, Any, Iterable, List, Optional, Tuple, Union from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings fro...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
23d0298bdaff-1
*, typesense_collection_name: Optional[str] = None, text_key: str = "text", ): """Initialize with Typesense client.""" try: from typesense import Client except ImportError: raise ValueError( "Could not import typesense python package. "...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
23d0298bdaff-2
] def _create_collection(self, num_dim: int) -> None: fields = [ {"name": "vec", "type": "float[]", "num_dim": num_dim}, {"name": f"{self._text_key}", "type": "string"}, {"name": ".*", "type": "auto"}, ] self._typesense_client.collections.create( ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
23d0298bdaff-3
self, query: str, k: int = 4, filter: Optional[str] = "", ) -> List[Tuple[Document, float]]: """Return typesense documents most similar to query, along with scores. Args: query: Text to look up documents similar to. k: Number of Documents to return. De...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
23d0298bdaff-4
k: Number of Documents to return. Defaults to 4. filter: typesense filter_by expression to filter documents on Returns: List of Documents most similar to the query and score for each """ docs_and_score = self.similarity_search_with_score(query, k=k, filter=filter) ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
23d0298bdaff-5
} typesense_api_key = typesense_api_key or get_from_env( "typesense_api_key", "TYPESENSE_API_KEY" ) client_config = { "nodes": [node], "api_key": typesense_api_key, "connection_timeout_seconds": connection_timeout_seconds, } return ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/typesense.html
04e04b46f0cc-0
Source code for langchain.vectorstores.analyticdb """VectorStore wrapper around a Postgres/PGVector database.""" from __future__ import annotations import logging import uuid from typing import Any, Dict, Iterable, List, Optional, Tuple import sqlalchemy from sqlalchemy import REAL, Index from sqlalchemy.dialects.postg...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
04e04b46f0cc-1
""" Get or create a collection. Returns [Collection, bool] where the bool is True if the collection was created. """ created = False collection = cls.get_by_name(session, name) if collection: return collection, created collection = cls(name=name, cmeta...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
04e04b46f0cc-2
""" VectorStore implementation using AnalyticDB. AnalyticDB is a distributed full PostgresSQL syntax cloud-native database. - `connection_string` is a postgres connection string. - `embedding_function` any embedding function implementing `langchain.embeddings.base.Embeddings` interface. - `c...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
04e04b46f0cc-3
engine = sqlalchemy.create_engine(self.connection_string) conn = engine.connect() return conn [docs] def create_tables_if_not_exists(self) -> None: Base.metadata.create_all(self._conn) [docs] def drop_tables(self) -> None: Base.metadata.drop_all(self._conn) [docs] def create_col...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
04e04b46f0cc-4
""" if ids is None: ids = [str(uuid.uuid1()) for _ in texts] embeddings = self.embedding_function.embed_documents(list(texts)) if not metadatas: metadatas = [{} for _ in texts] with Session(self._conn) as session: collection = self.get_collection(sessi...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
04e04b46f0cc-5
k: int = 4, filter: Optional[dict] = None, ) -> List[Tuple[Document, float]]: """Return docs most similar to query. Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter (Optional[Dict[str, str]]): Filte...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
04e04b46f0cc-6
.order_by(EmbeddingStore.embedding.op("<->")(embedding)) .join( CollectionStore, EmbeddingStore.collection_id == CollectionStore.uuid, ) .limit(k) .all() ) docs = [ ( Document( ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
04e04b46f0cc-7
**kwargs: Any, ) -> AnalyticDB: """ Return VectorStore initialized from texts and embeddings. Postgres connection string is required Either pass it as a parameter or set the PGVECTOR_CONNECTION_STRING environment variable. """ connection_string = cls.get_conne...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
04e04b46f0cc-8
""" texts = [d.page_content for d in documents] metadatas = [d.metadata for d in documents] connection_string = cls.get_connection_string(kwargs) kwargs["connection_string"] = connection_string return cls.from_texts( texts=texts, pre_delete_collection=pre_...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/analyticdb.html
8466eb6284f5-0
Source code for langchain.vectorstores.elastic_vector_search """Wrapper around Elasticsearch vector database.""" from __future__ import annotations import uuid from abc import ABC from typing import Any, Dict, Iterable, List, Optional, Tuple from langchain.docstore.document import Document from langchain.embeddings.bas...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
8466eb6284f5-1
# and attributes. [docs]class ElasticVectorSearch(VectorStore, ABC): """Wrapper around Elasticsearch as a vector database. To connect to an Elasticsearch instance that does not require login credentials, pass the Elasticsearch URL and index name along with the embedding object to the constructor. Ex...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
8466eb6284f5-2
Example: .. code-block:: python from langchain import ElasticVectorSearch from langchain.embeddings import OpenAIEmbeddings embedding = OpenAIEmbeddings() elastic_host = "cluster_id.region_id.gcp.cloud.es.io" elasticsearch_url = f"https://username:pass...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
8466eb6284f5-3
except ValueError as e: raise ValueError( f"Your elasticsearch client string is mis-formatted. Got error: {e} " ) [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, refresh_indices: bool = True, **k...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
8466eb6284f5-4
request = { "_op_type": "index", "_index": self.index_name, "vector": embeddings[i], "text": text, "metadata": metadata, "_id": _id, } ids.append(_id) requests.append(request) bulk...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
8466eb6284f5-5
response = self.client.search(index=self.index_name, query=script_query, size=k) hits = [hit for hit in response["hits"]["hits"]] docs_and_scores = [ ( Document( page_content=hit["_source"]["text"], metadata=hit["_source"]["metadata"], ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
8466eb6284f5-6
) index_name = index_name or uuid.uuid4().hex vectorsearch = cls(elasticsearch_url, index_name, embedding, **kwargs) vectorsearch.add_texts( texts, metadatas=metadatas, refresh_indices=refresh_indices ) return vectorsearch By Harrison Chase © Copyright 2023...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/elastic_vector_search.html
9d69c3bb5bdc-0
Source code for langchain.vectorstores.pinecone """Wrapper around Pinecone vector database.""" from __future__ import annotations import logging import uuid from typing import Any, Callable, Iterable, List, Optional, Tuple from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
9d69c3bb5bdc-1
f"got {type(index)}" ) self._index = index self._embedding_function = embedding_function self._text_key = text_key self._namespace = namespace [docs] def add_texts( self, texts: Iterable[str], metadatas: Optional[List[dict]] = None, ids: Opt...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
9d69c3bb5bdc-2
k: int = 4, filter: Optional[dict] = None, namespace: Optional[str] = None, ) -> List[Tuple[Document, float]]: """Return pinecone documents most similar to query, along with scores. Args: query: Text to look up documents similar to. k: Number of Documents to r...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
9d69c3bb5bdc-3
Args: query: Text to look up documents similar to. k: Number of Documents to return. Defaults to 4. filter: Dictionary of argument(s) to filter on metadata namespace: Namespace to search in. Default will search in '' namespace. Returns: List of Documen...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
9d69c3bb5bdc-4
pinecone = Pinecone.from_texts( texts, embeddings, index_name="langchain-demo" ) """ try: import pinecone except ImportError: raise ValueError( "Could not import pinecone python pa...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
9d69c3bb5bdc-5
for j, line in enumerate(lines_batch): metadata[j][text_key] = line to_upsert = zip(ids_batch, embeds, metadata) # upsert to Pinecone index.upsert(vectors=list(to_upsert), namespace=namespace) return cls(index, embedding.embed_query, text_key, namespace) [docs...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/pinecone.html
9fe057b59278-0
Source code for langchain.vectorstores.myscale """Wrapper around MyScale vector database.""" from __future__ import annotations import json import logging from hashlib import sha1 from threading import Thread from typing import Any, Dict, Iterable, List, Optional, Tuple from pydantic import BaseSettings from langchain....
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
9fe057b59278-1
.. code-block:: python { 'id': 'text_id', 'vector': 'text_embedding', 'text': 'text_plain', 'metadata': 'metadata_dictionary_in_json', }...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
9fe057b59278-2
config: Optional[MyScaleSettings] = None, **kwargs: Any, ) -> None: """MyScale Wrapper to LangChain embedding_function (Embeddings): config (MyScaleSettings): Configuration to MyScale Client Other keyword arguments will pass into [clickhouse-connect](https://docs....
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
9fe057b59278-3
CREATE TABLE IF NOT EXISTS {self.config.database}.{self.config.table}( {self.config.column_map['id']} String, {self.config.column_map['text']} String, {self.config.column_map['vector']} Array(Float32), {self.config.column_map['metadata']} JSON, ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
9fe057b59278-4
_data.append(f"({n})") i_str = f""" INSERT INTO TABLE {self.config.database}.{self.config.table}({ks}) VALUES {','.join(_data)} """ return i_str def _insert(self, transac: Iterable, column_names: Iterable[str]) -> N...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
9fe057b59278-5
column_names[colmap_["metadata"]] = map(json.dumps, metadatas) assert len(set(colmap_) - set(column_names)) >= 0 keys, values = zip(*column_names.items()) try: t = None for v in self.pgbar( zip(*values), desc="Inserting data...", total=len(metadatas) ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
9fe057b59278-6
texts (Iterable[str]): List or tuple of strings to be added config (MyScaleSettings, Optional): Myscale configuration text_ids (Optional[Iterable], optional): IDs for the texts. Defaults to None. batch_size (int, optional): Batchsi...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
9fe057b59278-7
).named_results(): _repr += ( f"|\033[94m{r['name']:24s}\033[0m|\033[96m{r['type']:24s}\033[0m|\n" ) _repr += "-" * 51 + "\n" return _repr def _build_qstr( self, q_emb: List[float], topk: int, where_str: Optional[str] = None ) -> str: q_emb...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
9fe057b59278-8
of SQL injection. When dealing with metadatas, remember to use `{self.metadata_column}.attribute` instead of `attribute` alone. The default name for it is `metadata`. Returns: List[Document]: List of Documents """ return self.similarity_search_by_v...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
9fe057b59278-9
] except Exception as e: logger.error(f"\033[91m\033[1m{type(e)}\033[0m \033[95m{str(e)}\033[0m") return [] [docs] def similarity_search_with_relevance_scores( self, query: str, k: int = 4, where_str: Optional[str] = None, **kwargs: Any ) -> List[Tuple[Document, float]]: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
9fe057b59278-10
return [] [docs] def drop(self) -> None: """ Helper function: Drop data """ self.client.command( f"DROP TABLE IF EXISTS {self.config.database}.{self.config.table}" ) @property def metadata_column(self) -> str: return self.config.column_map["metadata...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/myscale.html
16942036c972-0
Source code for langchain.vectorstores.tair """Wrapper around Tair Vector.""" from __future__ import annotations import json import logging import uuid from typing import Any, Iterable, List, Optional, Type from langchain.docstore.document import Document from langchain.embeddings.base import Embeddings from langchain....
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
16942036c972-1
data_type: str, **kwargs: Any, ) -> bool: index = self.client.tvs_get_index(self.index_name) if index is not None: logger.info("Index already exists") return False self.client.tvs_create_index( self.index_name, dim, distance...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
16942036c972-2
Args: query (str): The query text for which to find similar documents. k (int): The number of documents to return. Default is 4. Returns: List[Document]: A list of documents that are most similar to the query text. """ # Creates embedding vector from user quer...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
16942036c972-3
if "tair_url" in kwargs: kwargs.pop("tair_url") distance_type = tairvector.DistanceMetric.InnerProduct if "distance_type" in kwargs: distance_type = kwargs.pop("distance_typ") index_type = tairvector.IndexType.HNSW if "index_type" in kwargs: index_type...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
16942036c972-4
cls, documents: List[Document], embedding: Embeddings, metadatas: Optional[List[dict]] = None, index_name: str = "langchain", content_key: str = "content", metadata_key: str = "metadata", **kwargs: Any, ) -> Tair: texts = [d.page_content for d in docum...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
16942036c972-5
# index not exist logger.info("Index does not exist") return False return True [docs] @classmethod def from_existing_index( cls, embedding: Embeddings, index_name: str = "langchain", content_key: str = "content", metadata_key: str = "metadat...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/tair.html
c96311448f84-0
Source code for langchain.vectorstores.docarray.hnsw """Wrapper around Hnswlib store.""" from __future__ import annotations from typing import Any, List, Literal, Optional from langchain.embeddings.base import Embeddings from langchain.vectorstores.docarray.base import ( DocArrayIndex, _check_docarray_import, )...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html
c96311448f84-1
"cosine", "ip", and "l2". Defaults to "cosine". max_elements (int): Maximum number of vectors that can be stored. Defaults to 1024. index (bool): Whether an index should be built for this field. Defaults to True. ef_construction (int): defines a constr...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html
c96311448f84-2
work_dir: Optional[str] = None, n_dim: Optional[int] = None, **kwargs: Any, ) -> DocArrayHnswSearch: """Create an DocArrayHnswSearch store and insert data. Args: texts (List[str]): Text data. embedding (Embeddings): Embedding function. metadatas (O...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/hnsw.html
f930bd92d905-0
Source code for langchain.vectorstores.docarray.in_memory """Wrapper around in-memory storage.""" from __future__ import annotations from typing import Any, Dict, List, Literal, Optional from langchain.embeddings.base import Embeddings from langchain.vectorstores.docarray.base import ( DocArrayIndex, _check_doc...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html
f930bd92d905-1
[docs] @classmethod def from_texts( cls, texts: List[str], embedding: Embeddings, metadatas: Optional[List[Dict[Any, Any]]] = None, **kwargs: Any, ) -> DocArrayInMemorySearch: """Create an DocArrayInMemorySearch store and insert data. Args: ...
https://python.langchain.com/en/latest/_modules/langchain/vectorstores/docarray/in_memory.html
9bcdccd5e806-0
Source code for langchain.output_parsers.regex from __future__ import annotations import re from typing import Dict, List, Optional from langchain.schema import BaseOutputParser [docs]class RegexParser(BaseOutputParser): """Class to parse the output into a dictionary.""" regex: str output_keys: List[str] ...
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/regex.html
b9068afa51ec-0
Source code for langchain.output_parsers.retry from __future__ import annotations from typing import TypeVar from langchain.base_language import BaseLanguageModel from langchain.chains.llm import LLMChain from langchain.prompts.base import BasePromptTemplate from langchain.prompts.prompt import PromptTemplate from lang...
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html
b9068afa51ec-1
chain = LLMChain(llm=llm, prompt=prompt) return cls(parser=parser, retry_chain=chain) [docs] def parse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T: try: parsed_completion = self.parser.parse(completion) except OutputParserException: new_completio...
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html
b9068afa51ec-2
) -> RetryWithErrorOutputParser[T]: chain = LLMChain(llm=llm, prompt=prompt) return cls(parser=parser, retry_chain=chain) [docs] def parse_with_prompt(self, completion: str, prompt_value: PromptValue) -> T: try: parsed_completion = self.parser.parse(completion) except Outp...
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/retry.html
322c3e94dcd0-0
Source code for langchain.output_parsers.rail_parser from __future__ import annotations from typing import Any, Dict from langchain.schema import BaseOutputParser [docs]class GuardrailsOutputParser(BaseOutputParser): guard: Any @property def _type(self) -> str: return "guardrails" [docs] @classme...
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/rail_parser.html
cd0f6b77400d-0
Source code for langchain.output_parsers.list from __future__ import annotations from abc import abstractmethod from typing import List from langchain.schema import BaseOutputParser [docs]class ListOutputParser(BaseOutputParser): """Class to parse the output of an LLM call to a list.""" @property def _type(...
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/list.html
4d9c918f70c3-0
Source code for langchain.output_parsers.structured from __future__ import annotations from typing import Any, List from pydantic import BaseModel from langchain.output_parsers.format_instructions import STRUCTURED_FORMAT_INSTRUCTIONS from langchain.output_parsers.json import parse_and_check_json_markdown from langchai...
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/structured.html
03fa06d6e4d2-0
Source code for langchain.output_parsers.fix from __future__ import annotations from typing import TypeVar from langchain.base_language import BaseLanguageModel from langchain.chains.llm import LLMChain from langchain.output_parsers.prompts import NAIVE_FIX_PROMPT from langchain.prompts.base import BasePromptTemplate f...
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/fix.html
143def13812c-0
Source code for langchain.output_parsers.pydantic import json import re from typing import Type, TypeVar from pydantic import BaseModel, ValidationError from langchain.output_parsers.format_instructions import PYDANTIC_FORMAT_INSTRUCTIONS from langchain.schema import BaseOutputParser, OutputParserException T = TypeVar(...
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html
143def13812c-1
@property def _type(self) -> str: return "pydantic" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 29, 2023.
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html
2d54b70c0344-0
Source code for langchain.output_parsers.regex_dict from __future__ import annotations import re from typing import Dict, Optional from langchain.schema import BaseOutputParser [docs]class RegexDictParser(BaseOutputParser): """Class to parse the output into a dictionary.""" regex_pattern: str = r"{}:\s?([^.'\n'...
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/regex_dict.html
7610c1b5670d-0
Source code for langchain.output_parsers.datetime import random from datetime import datetime, timedelta from typing import List from langchain.schema import BaseOutputParser, OutputParserException from langchain.utils import comma_list def _generate_random_datetime_strings( pattern: str, n: int = 3, start_...
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/datetime.html
7610c1b5670d-1
) from e @property def _type(self) -> str: return "datetime" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 29, 2023.
https://python.langchain.com/en/latest/_modules/langchain/output_parsers/datetime.html
b241347a1a50-0
Source code for langchain.docstore.wikipedia """Wrapper around wikipedia API.""" from typing import Union from langchain.docstore.base import Docstore from langchain.docstore.document import Document [docs]class Wikipedia(Docstore): """Wrapper around wikipedia API.""" def __init__(self) -> None: """Chec...
https://python.langchain.com/en/latest/_modules/langchain/docstore/wikipedia.html
8bc3a609d7fb-0
Source code for langchain.docstore.in_memory """Simple in memory docstore in the form of a dict.""" from typing import Dict, Union from langchain.docstore.base import AddableMixin, Docstore from langchain.docstore.document import Document [docs]class InMemoryDocstore(Docstore, AddableMixin): """Simple in memory doc...
https://python.langchain.com/en/latest/_modules/langchain/docstore/in_memory.html
f844aeb30e69-0
Source code for langchain.prompts.base """BasePrompt schema definition.""" from __future__ import annotations import json from abc import ABC, abstractmethod from pathlib import Path from typing import Any, Callable, Dict, List, Mapping, Optional, Set, Union import yaml from pydantic import BaseModel, Extra, Field, roo...
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
f844aeb30e69-1
"jinja2 not installed, which is needed to use the jinja2_formatter. " "Please install it with `pip install jinja2`." ) env = Environment() ast = env.parse(template) variables = meta.find_undeclared_variables(ast) return variables DEFAULT_FORMATTER_MAPPING: Dict[str, Callable] = { ...
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
f844aeb30e69-2
"""Base class for all prompt templates, returning a prompt.""" input_variables: List[str] """A list of the names of the variables the prompt template expects.""" output_parser: Optional[BaseOutputParser] = None """How to parse the output of calling an LLM on this formatted prompt.""" partial_variabl...
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
f844aeb30e69-3
prompt_dict["input_variables"] = list( set(self.input_variables).difference(kwargs) ) prompt_dict["partial_variables"] = {**self.partial_variables, **kwargs} return type(self)(**prompt_dict) def _merge_partial_and_user_variables(self, **kwargs: Any) -> Dict[str, Any]: # G...
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
f844aeb30e69-4
# Convert file to Path object. if isinstance(file_path, str): save_path = Path(file_path) else: save_path = file_path directory_path = save_path.parent directory_path.mkdir(parents=True, exist_ok=True) # Fetch dictionary to save prompt_dict = self....
https://python.langchain.com/en/latest/_modules/langchain/prompts/base.html
c754afbb2e16-0
Source code for langchain.prompts.few_shot """Prompt template that contains few shot examples.""" from typing import Any, Dict, List, Optional from pydantic import Extra, root_validator from langchain.prompts.base import ( DEFAULT_FORMATTER_MAPPING, StringPromptTemplate, check_valid_template, ) from langcha...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
c754afbb2e16-1
"""Check that one and only one of examples/example_selector are provided.""" examples = values.get("examples", None) example_selector = values.get("example_selector", None) if examples and example_selector: raise ValueError( "Only one of 'examples' and 'example_select...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
c754afbb2e16-2
# Get the examples to use. examples = self._get_examples(**kwargs) examples = [ {k: e[k] for k in self.example_prompt.input_variables} for e in examples ] # Format the examples. example_strings = [ self.example_prompt.format(**example) for example in examp...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
93d739e70e01-0
Source code for langchain.prompts.prompt """Prompt schema definition.""" from __future__ import annotations from pathlib import Path from string import Formatter from typing import Any, Dict, List, Union from pydantic import Extra, root_validator from langchain.prompts.base import ( DEFAULT_FORMATTER_MAPPING, S...
https://python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
93d739e70e01-1
""" kwargs = self._merge_partial_and_user_variables(**kwargs) return DEFAULT_FORMATTER_MAPPING[self.template_format](self.template, **kwargs) @root_validator() def template_is_valid(cls, values: Dict) -> Dict: """Check that template and input variables are consistent.""" if value...
https://python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
93d739e70e01-2
[docs] @classmethod def from_file( cls, template_file: Union[str, Path], input_variables: List[str], **kwargs: Any ) -> PromptTemplate: """Load a prompt from a file. Args: template_file: The path to the file containing the prompt template. input_variables: A li...
https://python.langchain.com/en/latest/_modules/langchain/prompts/prompt.html
83369d295909-0
Source code for langchain.prompts.loading """Load prompts from disk.""" import importlib import json import logging from pathlib import Path from typing import Union import yaml from langchain.output_parsers.regex import RegexParser from langchain.prompts.base import BasePromptTemplate from langchain.prompts.few_shot i...
https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
83369d295909-1
if template_path.suffix == ".txt": with open(template_path) as f: template = f.read() else: raise ValueError # Set the template variable to the extracted variable. config[var_name] = template return config def _load_examples(config: dict) -> dict: ...
https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
83369d295909-2
config = _load_template("prefix", config) # Load the example prompt. if "example_prompt_path" in config: if "example_prompt" in config: raise ValueError( "Only one of example_prompt and example_prompt_path should " "be specified." ) config[...
https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
83369d295909-3
with open(file_path) as f: config = json.load(f) elif file_path.suffix == ".yaml": with open(file_path, "r") as f: config = yaml.safe_load(f) elif file_path.suffix == ".py": spec = importlib.util.spec_from_loader( "prompt", loader=None, origin=str(file_path) ...
https://python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
15423f9eb833-0
Source code for langchain.prompts.few_shot_with_templates """Prompt template that contains few shot examples.""" from typing import Any, Dict, List, Optional from pydantic import Extra, root_validator from langchain.prompts.base import DEFAULT_FORMATTER_MAPPING, StringPromptTemplate from langchain.prompts.example_selec...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
15423f9eb833-1
examples = values.get("examples", None) example_selector = values.get("example_selector", None) if examples and example_selector: raise ValueError( "Only one of 'examples' and 'example_selector' should be provided" ) if examples is None and example_selecto...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
15423f9eb833-2
kwargs: Any arguments to be passed to the prompt template. Returns: A formatted string. Example: .. code-block:: python prompt.format(variable1="foo") """ kwargs = self._merge_partial_and_user_variables(**kwargs) # Get the examples to use. ...
https://python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html