id
stringlengths
14
16
text
stringlengths
29
2.73k
source
stringlengths
50
116
6607a9e20659-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
6607a9e20659-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
6607a9e20659-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
6607a9e20659-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
6607a9e20659-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
6607a9e20659-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
6607a9e20659-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
6607a9e20659-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
6607a9e20659-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
6607a9e20659-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
015d3ed426dc-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
015d3ed426dc-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
015d3ed426dc-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
015d3ed426dc-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
015d3ed426dc-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
015d3ed426dc-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
9fa7168b2a14-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
a7ae5da05b20-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
a7ae5da05b20-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
a7ae5da05b20-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
be48eff5109e-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
ed436be83145-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
1103ecdbcbeb-0
Source code for langchain.output_parsers.structured from __future__ import annotations import json from typing import Any, List from pydantic import BaseModel from langchain.output_parsers.format_instructions import STRUCTURED_FORMAT_INSTRUCTIONS from langchain.schema import BaseOutputParser, OutputParserException line...
https:///python.langchain.com/en/latest/_modules/langchain/output_parsers/structured.html
1103ecdbcbeb-1
) -> StructuredOutputParser: return cls(response_schemas=response_schemas) [docs] def get_format_instructions(self) -> str: schema_str = "\n".join( [_get_sub_string(schema) for schema in self.response_schemas] ) return STRUCTURED_FORMAT_INSTRUCTIONS.format(format=schema_st...
https:///python.langchain.com/en/latest/_modules/langchain/output_parsers/structured.html
65cbe39b8b7c-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
195afb2a4aa0-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
195afb2a4aa0-1
@property def _type(self) -> str: return "pydantic" By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https:///python.langchain.com/en/latest/_modules/langchain/output_parsers/pydantic.html
f236870699f4-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
eed98336cbda-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
034b0e788a8d-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
fe97a1fe4d22-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
fe97a1fe4d22-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
fe97a1fe4d22-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
fe97a1fe4d22-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
fe97a1fe4d22-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
cf90ad095927-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
cf90ad095927-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
cf90ad095927-2
# Get the examples to use. examples = self._get_examples(**kwargs) # Format the examples. example_strings = [ self.example_prompt.format(**example) for example in examples ] # Create the overall template. pieces = [self.prefix, *example_strings, self.suffix] ...
https:///python.langchain.com/en/latest/_modules/langchain/prompts/few_shot.html
febc24f7b8be-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
febc24f7b8be-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
febc24f7b8be-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
236c67df35b2-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
236c67df35b2-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
236c67df35b2-2
config = _load_template("suffix", config) 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 " ...
https:///python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
236c67df35b2-3
# Load from either json or yaml. if file_path.suffix == ".json": 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...
https:///python.langchain.com/en/latest/_modules/langchain/prompts/loading.html
bc451df98ecd-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
bc451df98ecd-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
bc451df98ecd-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
bc451df98ecd-3
if self.example_selector: raise ValueError("Saving an example selector is not currently supported") return super().dict(**kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https:///python.langchain.com/en/latest/_modules/langchain/prompts/few_shot_with_templates.html
e1b143c509fc-0
Source code for langchain.prompts.chat """Chat prompt template.""" from __future__ import annotations from abc import ABC, abstractmethod from pathlib import Path from typing import Any, Callable, List, Sequence, Tuple, Type, Union from pydantic import BaseModel, Field from langchain.memory.buffer import get_buffer_str...
https:///python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
e1b143c509fc-1
def input_variables(self) -> List[str]: """Input variables for this prompt template.""" return [self.variable_name] class BaseStringMessagePromptTemplate(BaseMessagePromptTemplate, ABC): prompt: StringPromptTemplate additional_kwargs: dict = Field(default_factory=dict) @classmethod def f...
https:///python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
e1b143c509fc-2
text = self.prompt.format(**kwargs) return SystemMessage(content=text, additional_kwargs=self.additional_kwargs) class ChatPromptValue(PromptValue): messages: List[BaseMessage] def to_string(self) -> str: """Return prompt as string.""" return get_buffer_string(self.messages) def to_m...
https:///python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
e1b143c509fc-3
for role, template in string_messages ] return cls.from_messages(messages) @classmethod def from_messages( cls, messages: Sequence[Union[BaseMessagePromptTemplate, BaseMessage]] ) -> ChatPromptTemplate: input_vars = set() for message in messages: if isinst...
https:///python.langchain.com/en/latest/_modules/langchain/prompts/chat.html
1e228322c399-0
Source code for langchain.prompts.example_selector.semantic_similarity """Example selector that selects examples based on SemanticSimilarity.""" from __future__ import annotations from typing import Any, Dict, List, Optional, Type from pydantic import BaseModel, Extra from langchain.embeddings.base import Embeddings fr...
https:///python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
1e228322c399-1
return ids[0] [docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]: """Select which examples to use based on semantic similarity.""" # Get the docs with the highest similarity. if self.input_keys: input_variables = {key: input_variables[key] for key in s...
https:///python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
1e228322c399-2
instead of all variables. vectorstore_cls_kwargs: optional kwargs containing url for vector store Returns: The ExampleSelector instantiated, backed by a vector store. """ if input_keys: string_examples = [ " ".join(sorted_values({k: eg[k] for k...
https:///python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
1e228322c399-3
examples = [dict(e.metadata) for e in example_docs] # If example keys are provided, filter examples to those keys. if self.example_keys: examples = [{k: eg[k] for k in self.example_keys} for eg in examples] return examples [docs] @classmethod def from_examples( cls, ...
https:///python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
1e228322c399-4
string_examples, embeddings, metadatas=examples, **vectorstore_cls_kwargs ) return cls(vectorstore=vectorstore, k=k, fetch_k=fetch_k, input_keys=input_keys) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https:///python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/semantic_similarity.html
f2abe3a384c2-0
Source code for langchain.prompts.example_selector.length_based """Select examples based on length.""" import re from typing import Callable, Dict, List from pydantic import BaseModel, validator from langchain.prompts.example_selector.base import BaseExampleSelector from langchain.prompts.prompt import PromptTemplate d...
https:///python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html
f2abe3a384c2-1
get_text_length = values["get_text_length"] string_examples = [example_prompt.format(**eg) for eg in values["examples"]] return [get_text_length(eg) for eg in string_examples] [docs] def select_examples(self, input_variables: Dict[str, str]) -> List[dict]: """Select which examples to use base...
https:///python.langchain.com/en/latest/_modules/langchain/prompts/example_selector/length_based.html
b586ef22c35c-0
Source code for langchain.document_loaders.airbyte_json """Loader that loads local airbyte json files.""" import json from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.utils import stringify_dict [docs]class AirbyteJSONLoader(B...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/airbyte_json.html
164edfff6a5f-0
Source code for langchain.document_loaders.diffbot """Loader that uses Diffbot to load webpages in text format.""" import logging from typing import Any, List import requests from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader logger = logging.getLogger(__name__) [doc...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/diffbot.html
164edfff6a5f-1
text = data["objects"][0]["text"] if "objects" in data else "" metadata = {"source": url} docs.append(Document(page_content=text, metadata=metadata)) except Exception as e: if self.continue_on_failure: logger.error(f"Error fetching or proce...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/diffbot.html
60039327ea1f-0
Source code for langchain.document_loaders.modern_treasury """Loader that fetches data from Modern Treasury""" import json import urllib.request from base64 import b64encode from typing import List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from lan...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/modern_treasury.html
60039327ea1f-1
self, resource: str, organization_id: Optional[str] = None, api_key: Optional[str] = None, ) -> None: self.resource = resource organization_id = organization_id or get_from_env( "organization_id", "MODERN_TREASURY_ORGANIZATION_ID" ) api_key = api_k...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/modern_treasury.html
03e45db6a586-0
Source code for langchain.document_loaders.bigquery from typing import List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class BigQueryLoader(BaseLoader): """Loads a query result from BigQuery into a list of documents. Each document repr...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/bigquery.html
03e45db6a586-1
metadata_columns = [] for row in query_result: page_content = "\n".join( f"{k}: {v}" for k, v in row.items() if k in page_content_columns ) metadata = {k: v for k, v in row.items() if k in metadata_columns} doc = Document(page_content=page_content,...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/bigquery.html
601861e2306b-0
Source code for langchain.document_loaders.readthedocs """Loader that loads ReadTheDocs documentation directory dump.""" from pathlib import Path from typing import Any, List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class ReadTheDocsLoader(B...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/readthedocs.html
601861e2306b-1
text = text[0].get_text() else: text = "" return "\n".join([t for t in text.split("\n") if t]) docs = [] for p in Path(self.file_path).rglob("*"): if p.is_dir(): continue with open(p, encoding=self.encoding, errors=self.erro...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/readthedocs.html
799e30e4fe4a-0
Source code for langchain.document_loaders.chatgpt """Load conversations from ChatGPT data export""" import datetime import json from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader def concatenate_rows(message: dict, title: str) -> str: if ...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/chatgpt.html
799e30e4fe4a-1
documents.append(Document(page_content=text, metadata=metadata)) return documents By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/chatgpt.html
87c48192991a-0
Source code for langchain.document_loaders.powerpoint """Loader that loads powerpoint files.""" import os from typing import List from langchain.document_loaders.unstructured import UnstructuredFileLoader [docs]class UnstructuredPowerPointLoader(UnstructuredFileLoader): """Loader that uses unstructured to load powe...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html
87c48192991a-1
return partition_pptx(filename=self.file_path, **self.unstructured_kwargs) By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on May 02, 2023.
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/powerpoint.html
e7780cf76cd5-0
Source code for langchain.document_loaders.epub """Loader that loads EPub files.""" from typing import List from langchain.document_loaders.unstructured import ( UnstructuredFileLoader, satisfies_min_unstructured_version, ) [docs]class UnstructuredEPubLoader(UnstructuredFileLoader): """Loader that uses unst...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/epub.html
ba171a18b925-0
Source code for langchain.document_loaders.python import tokenize from langchain.document_loaders.text import TextLoader [docs]class PythonLoader(TextLoader): """ Load Python files, respecting any non-default encoding if specified. """ def __init__(self, file_path: str): with open(file_path, "rb...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/python.html
faef20befc5d-0
Source code for langchain.document_loaders.azure_blob_storage_file """Loading logic for loading documents from an Azure Blob Storage file.""" import os import tempfile from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.document_...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/azure_blob_storage_file.html
cf7f7f3356e1-0
Source code for langchain.document_loaders.git import os from typing import Callable, List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class GitLoader(BaseLoader): """Loads files from a Git repository into a list of documents. Repositor...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/git.html
cf7f7f3356e1-1
else: repo = Repo(self.repo_path) repo.git.checkout(self.branch) docs: List[Document] = [] for item in repo.tree().traverse(): if not isinstance(item, Blob): continue file_path = os.path.join(self.repo_path, item.path) ignored_f...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/git.html
b025a69f3fbe-0
Source code for langchain.document_loaders.text from typing import List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class TextLoader(BaseLoader): """Load text files.""" def __init__(self, file_path: str, encoding: Optional[str] = None):...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/text.html
290bdf020951-0
Source code for langchain.document_loaders.image """Loader that loads image files.""" from typing import List from langchain.document_loaders.unstructured import UnstructuredFileLoader [docs]class UnstructuredImageLoader(UnstructuredFileLoader): """Loader that uses unstructured to load image files, such as PNGs and...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/image.html
07f20d10e310-0
Source code for langchain.document_loaders.srt """Loader for .srt (subtitle) files.""" from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class SRTLoader(BaseLoader): """Loader for .srt (subtitle) files.""" def __init__(self, fil...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/srt.html
944be3304458-0
Source code for langchain.document_loaders.url_selenium """Loader that uses Selenium to load a page, then uses unstructured to load the html. """ import logging from typing import TYPE_CHECKING, List, Literal, Optional, Union if TYPE_CHECKING: from selenium.webdriver import Chrome, Firefox from langchain.docstore.d...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/url_selenium.html
944be3304458-1
raise ValueError( "unstructured package not found, please install it with " "`pip install unstructured`" ) self.urls = urls self.continue_on_failure = continue_on_failure self.browser = browser self.executable_path = executable_path sel...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/url_selenium.html
944be3304458-2
"""Load the specified URLs using Selenium and create Document instances. Returns: List[Document]: A list of Document instances with loaded content. """ from unstructured.partition.html import partition_html docs: List[Document] = list() driver = self._get_driver() ...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/url_selenium.html
6e15690eb8d2-0
Source code for langchain.document_loaders.notion """Loader that loads Notion directory dump.""" from pathlib import Path from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader [docs]class NotionDirectoryLoader(BaseLoader): """Loader that load...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/notion.html
cd4ae848bd75-0
Source code for langchain.document_loaders.evernote """Load documents from Evernote. https://gist.github.com/foxmask/7b29c43a161e001ff04afdb2f181e31c """ import hashlib from base64 import b64decode from time import strptime from typing import Any, Dict, List from langchain.docstore.document import Document from langcha...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html
cd4ae848bd75-1
else: note_dict[elem.tag] = elem.text note_dict["resource"] = resources return note_dict def _parse_note_xml(xml_file: str) -> str: """Parse Evernote xml.""" # Without huge_tree set to True, parser may complain about huge text node # Try to recover, because there may be " ", which w...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/evernote.html
92807198b598-0
Source code for langchain.document_loaders.reddit """Reddit document loader.""" from __future__ import annotations from typing import TYPE_CHECKING, Iterable, List, Optional, Sequence from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader if TYPE_CHECKING: import pra...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/reddit.html
92807198b598-1
if self.mode == "subreddit": for search_query in self.search_queries: for category in self.categories: docs = self._subreddit_posts_loader( search_query=search_query, category=category, reddit=reddit ) result...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/reddit.html
92807198b598-2
method = getattr(user.submissions, category) cat_posts = method(limit=self.number_posts) """Format reddit posts into a string.""" for post in cat_posts: metadata = { "post_subreddit": post.subreddit_name_prefixed, "post_category": category, ...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/reddit.html
cf919d9b47b9-0
Source code for langchain.document_loaders.url_playwright """Loader that uses Playwright to load a page, then uses unstructured to load the html. """ import logging from typing import List, Optional from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader logger = logging....
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html
cf919d9b47b9-1
[docs] def load(self) -> List[Document]: """Load the specified URLs using Playwright and create Document instances. Returns: List[Document]: A list of Document instances with loaded content. """ from playwright.sync_api import sync_playwright from unstructured.part...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/url_playwright.html
2adc2373df1d-0
Source code for langchain.document_loaders.twitter """Twitter document loader.""" from __future__ import annotations from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, Sequence, Union from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader if TYPE_CHEC...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/twitter.html
2adc2373df1d-1
user = api.get_user(screen_name=username) docs = self._format_tweets(tweets, user) results.extend(docs) return results def _format_tweets( self, tweets: List[Dict[str, Any]], user_info: dict ) -> Iterable[Document]: """Format tweets into a string.""" for t...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/twitter.html
2adc2373df1d-2
access_token=access_token, access_token_secret=access_token_secret, consumer_key=consumer_key, consumer_secret=consumer_secret, ) return cls( auth_handler=auth, twitter_users=twitter_users, number_tweets=number_tweets, ) By ...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/twitter.html
5ecff278ae21-0
Source code for langchain.document_loaders.gcs_directory """Loading logic for loading documents from an GCS directory.""" from typing import List from langchain.docstore.document import Document from langchain.document_loaders.base import BaseLoader from langchain.document_loaders.gcs_file import GCSFileLoader [docs]cl...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/gcs_directory.html
0eefa3edbbb3-0
Source code for langchain.document_loaders.html """Loader that uses unstructured to load HTML files.""" from typing import List from langchain.document_loaders.unstructured import UnstructuredFileLoader [docs]class UnstructuredHTMLLoader(UnstructuredFileLoader): """Loader that uses unstructured to load HTML files."...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/html.html
f032db217422-0
Source code for langchain.document_loaders.confluence """Load Data from a Confluence Space""" import logging from typing import Any, Callable, List, Optional, Union from tenacity import ( before_sleep_log, retry, stop_after_attempt, wait_exponential, ) from langchain.docstore.document import Document fr...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
f032db217422-1
:param url: _description_ :type url: str :param api_key: _description_, defaults to None :type api_key: str, optional :param username: _description_, defaults to None :type username: str, optional :param oauth2: _description_, defaults to {} :type oauth2: dict, optional :param cloud: _de...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html
f032db217422-2
if errors: raise ValueError(f"Error(s) while validating input: {errors}") self.base_url = url self.number_of_retries = number_of_retries self.min_retry_seconds = min_retry_seconds self.max_retry_seconds = max_retry_seconds try: from atlassian import Conflu...
https:///python.langchain.com/en/latest/_modules/langchain/document_loaders/confluence.html