╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮│ /data/source/langchain/langchain/document_loaders/text.py:29 in load ││ ││ 26 │ │ text = """" ││ 27 │ │ with open(self.file_path, encoding=self.encoding) as f: ││ 28 │ │ │ try: ││ ❱ 29 │ │ │ │ text = f.read() ││ 30 │ │ │ except UnicodeDecodeError as e: ││ 31 │ │ │ │ if self.autodetect_encoding: ││ 32 │ │ │ │ │ detected_encodings = self.detect_file_encodings() ││ ││ /home/spike/.pyenv/versions/3.9.11/lib/python3.9/codecs.py:322 in decode ││ ││ 319 │ def decode(self, input, final=False): ││ 320 │ │ # decode input (taking the buffer into account) ││ 321 │ │ data = self.buffer + input ││ ❱ 322 │ │ (result, consumed) = self._buffer_decode(data, self.errors, final) ││ 323 │ │ # keep undecoded input until the next call ││ 324 │ │ self.buffer = data[consumed:] ││ 325 │ │ return result │╰──────────────────────────────────────────────────────────────────────────────────────────────────╯UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca in position 0: invalid continuation byteThe above exception was the direct cause of the following exception:╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮│ in <module>:1 ││ ││ ❱ 1 loader.load() ││ 2 ││ ││ /data/source/langchain/langchain/document_loaders/directory.py:84 in load ││ ││ 81 │ │ │ │ │ │ if self.silent_errors: ││ 82 │ │ │ │ │ │ │ logger.warning(e) ││ 83 │ │ │ │ │ │ else: ││ ❱ 84 │ │ │ │ │ │ │ raise e ││ 85 │ │ │ │ │ finally: ││ 86 │ │ │ │ │ │ if pbar: ││ 87 │ │ │ │ │ │ │ pbar.update(1) ││ ││ /data/source/langchain/langchain/document_loaders/directory.py:78 in load ││ ││ 75 │ │ │ if i.is_file(): ││ 76 │ │ │ │ if _is_visible(i.relative_to(p)) or self.load_hidden: ││ 77 │ │ │ │ │ try: ││ ❱ 78 │ │ │ │ │ │ sub_docs = self.loader_cls(str(i), **self.loader_kwargs).load() ││ 79 │ │ │ │ │ │ docs.extend(sub_docs) ││ 80 │ │ │ │ │ except Exception as e: ││ 81 │ │ │ │ │ │ if self.silent_errors: ││ ││ /data/source/langchain/langchain/document_loaders/text.py:44 in load ││ ││ 41 │ │ │ │ │ │ except UnicodeDecodeError: ││ 42 │ │ │ │ │ │ │ continue ││ 43 │ │ │ │ else: ││ ❱ 44 │ │ │ │ │ raise RuntimeError(f""Error loading {self.file_path}"") from e ││ 45 │ │ │ except Exception as e: ││ 46 │ │ │ │ raise RuntimeError(f""Error loading {self.file_path}"") from e ││ 47 │╰──────────────────────────────────────────────────────────────────────────────────────────────────╯RuntimeError: Error loading ../../../../../tests/integration_tests/examples/example-non-utf8.txtThe file example-non-utf8.txt uses a different encoding, so the load() function fails with a helpful message indicating which file failed decoding. With the default behavior of TextLoader any failure to load any of the documents will fail the whole loading process and no documents are loaded. B. Silent failWe can pass the parameter silent_errors to the DirectoryLoader to skip the files which could not be loaded and continue the load process.loader = DirectoryLoader(path, glob=""**/*.txt"", loader_cls=TextLoader, silent_errors=True)docs = loader.load() Error loading ../../../../../tests/integration_tests/examples/example-non-utf8.txtdoc_sources = [doc.metadata['source'] for doc in docs]doc_sources ['../../../../../tests/integration_tests/examples/whatsapp_chat.txt', '../../../../../tests/integration_tests/examples/example-utf8.txt']C. Auto detect encodingsWe can also ask TextLoader to auto detect the file encoding before failing, by passing the autodetect_encoding to the loader class.text_loader_kwargs={'autodetect_encoding': True}loader = DirectoryLoader(path, glob=""**/*.txt"", loader_cls=TextLoader, loader_kwargs=text_loader_kwargs)docs = loader.load()doc_sources = [doc.metadata['source'] for doc in docs]doc_sources ['../../../../../tests/integration_tests/examples/example-non-utf8.txt', '../../../../../tests/integration_tests/examples/whatsapp_chat.txt', '../../../../../tests/integration_tests/examples/example-utf8.txt']PreviousCSVNextHTML" +46,https://python.langchain.com/docs/modules/data_connection/document_loaders/html,"ModulesRetrievalDocument loadersHTMLHTMLThe HyperText Markup Language or HTML is the standard markup language for documents designed to be displayed in a web browser.This covers how to load HTML documents into a document format that we can use downstream.from langchain.document_loaders import UnstructuredHTMLLoaderloader = UnstructuredHTMLLoader(""example_data/fake-content.html"")data = loader.load()data [Document(page_content='My First Heading\n\nMy first paragraph.', lookup_str='', metadata={'source': 'example_data/fake-content.html'}, lookup_index=0)]Loading HTML with BeautifulSoup4We can also use BeautifulSoup4 to load HTML documents using the BSHTMLLoader. This will extract the text from the HTML into page_content, and the page title as title into metadata.from langchain.document_loaders import BSHTMLLoaderloader = BSHTMLLoader(""example_data/fake-content.html"")data = loader.load()data [Document(page_content='\n\nTest Title\n\n\nMy First Heading\nMy first paragraph.\n\n\n', metadata={'source': 'example_data/fake-content.html', 'title': 'Test Title'})]PreviousFile DirectoryNextJSON" +47,https://python.langchain.com/docs/modules/data_connection/document_loaders/json,"ModulesRetrievalDocument loadersJSONJSONJSON (JavaScript Object Notation) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays (or other serializable values).JSON Lines is a file format where each line is a valid JSON value.The JSONLoader uses a specified jq schema to parse the JSON files. It uses the jq python package. +Check this manual for a detailed documentation of the jq syntax.#!pip install jqfrom langchain.document_loaders import JSONLoaderimport jsonfrom pathlib import Pathfrom pprint import pprintfile_path='./example_data/facebook_chat.json'data = json.loads(Path(file_path).read_text())pprint(data) {'image': {'creation_timestamp': 1675549016, 'uri': 'image_of_the_chat.jpg'}, 'is_still_participant': True, 'joinable_mode': {'link': '', 'mode': 1}, 'magic_words': [], 'messages': [{'content': 'Bye!', 'sender_name': 'User 2', 'timestamp_ms': 1675597571851}, {'content': 'Oh no worries! Bye', 'sender_name': 'User 1', 'timestamp_ms': 1675597435669}, {'content': 'No Im sorry it was my mistake, the blue one is not ' 'for sale', 'sender_name': 'User 2', 'timestamp_ms': 1675596277579}, {'content': 'I thought you were selling the blue one!', 'sender_name': 'User 1', 'timestamp_ms': 1675595140251}, {'content': 'Im not interested in this bag. Im interested in the ' 'blue one!', 'sender_name': 'User 1', 'timestamp_ms': 1675595109305}, {'content': 'Here is $129', 'sender_name': 'User 2', 'timestamp_ms': 1675595068468}, {'photos': [{'creation_timestamp': 1675595059, 'uri': 'url_of_some_picture.jpg'}], 'sender_name': 'User 2', 'timestamp_ms': 1675595060730}, {'content': 'Online is at least $100', 'sender_name': 'User 2', 'timestamp_ms': 1675595045152}, {'content': 'How much do you want?', 'sender_name': 'User 1', 'timestamp_ms': 1675594799696}, {'content': 'Goodmorning! $50 is too low.', 'sender_name': 'User 2', 'timestamp_ms': 1675577876645}, {'content': 'Hi! Im interested in your bag. Im offering $50. Let ' 'me know if you are interested. Thanks!', 'sender_name': 'User 1', 'timestamp_ms': 1675549022673}], 'participants': [{'name': 'User 1'}, {'name': 'User 2'}], 'thread_path': 'inbox/User 1 and User 2 chat', 'title': 'User 1 and User 2 chat'}Using JSONLoaderSuppose we are interested in extracting the values under the content field within the messages key of the JSON data. This can easily be done through the JSONLoader as shown below.JSON fileloader = JSONLoader( file_path='./example_data/facebook_chat.json', jq_schema='.messages[].content', text_content=False)data = loader.load()pprint(data) [Document(page_content='Bye!', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 1}), Document(page_content='Oh no worries! Bye', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 2}), Document(page_content='No Im sorry it was my mistake, the blue one is not for sale', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 3}), Document(page_content='I thought you were selling the blue one!', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 4}), Document(page_content='Im not interested in this bag. Im interested in the blue one!', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 5}), Document(page_content='Here is $129', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 6}), Document(page_content='', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 7}), Document(page_content='Online is at least $100', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 8}), Document(page_content='How much do you want?', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 9}), Document(page_content='Goodmorning! $50 is too low.', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 10}), Document(page_content='Hi! Im interested in your bag. Im offering $50. Let me know if you are interested. Thanks!', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 11})]JSON Lines fileIf you want to load documents from a JSON Lines file, you pass json_lines=True +and specify jq_schema to extract page_content from a single JSON object.file_path = './example_data/facebook_chat_messages.jsonl'pprint(Path(file_path).read_text()) ('{""sender_name"": ""User 2"", ""timestamp_ms"": 1675597571851, ""content"": ""Bye!""}\n' '{""sender_name"": ""User 1"", ""timestamp_ms"": 1675597435669, ""content"": ""Oh no ' 'worries! Bye""}\n' '{""sender_name"": ""User 2"", ""timestamp_ms"": 1675596277579, ""content"": ""No Im ' 'sorry it was my mistake, the blue one is not for sale""}\n')loader = JSONLoader( file_path='./example_data/facebook_chat_messages.jsonl', jq_schema='.content', text_content=False, json_lines=True)data = loader.load()pprint(data) [Document(page_content='Bye!', metadata={'source': 'langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat_messages.jsonl', 'seq_num': 1}), Document(page_content='Oh no worries! Bye', metadata={'source': 'langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat_messages.jsonl', 'seq_num': 2}), Document(page_content='No Im sorry it was my mistake, the blue one is not for sale', metadata={'source': 'langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat_messages.jsonl', 'seq_num': 3})]Another option is set jq_schema='.' and provide content_key:loader = JSONLoader( file_path='./example_data/facebook_chat_messages.jsonl', jq_schema='.', content_key='sender_name', json_lines=True)data = loader.load()pprint(data) [Document(page_content='User 2', metadata={'source': 'langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat_messages.jsonl', 'seq_num': 1}), Document(page_content='User 1', metadata={'source': 'langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat_messages.jsonl', 'seq_num': 2}), Document(page_content='User 2', metadata={'source': 'langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat_messages.jsonl', 'seq_num': 3})]Extracting metadataGenerally, we want to include metadata available in the JSON file into the documents that we create from the content.The following demonstrates how metadata can be extracted using the JSONLoader.There are some key changes to be noted. In the previous example where we didn't collect the metadata, we managed to directly specify in the schema where the value for the page_content can be extracted from..messages[].contentIn the current example, we have to tell the loader to iterate over the records in the messages field. The jq_schema then has to be:.messages[]This allows us to pass the records (dict) into the metadata_func that has to be implemented. The metadata_func is responsible for identifying which pieces of information in the record should be included in the metadata stored in the final Document object.Additionally, we now have to explicitly specify in the loader, via the content_key argument, the key from the record where the value for the page_content needs to be extracted from.# Define the metadata extraction function.def metadata_func(record: dict, metadata: dict) -> dict: metadata[""sender_name""] = record.get(""sender_name"") metadata[""timestamp_ms""] = record.get(""timestamp_ms"") return metadataloader = JSONLoader( file_path='./example_data/facebook_chat.json', jq_schema='.messages[]', content_key=""content"", metadata_func=metadata_func)data = loader.load()pprint(data) [Document(page_content='Bye!', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 1, 'sender_name': 'User 2', 'timestamp_ms': 1675597571851}), Document(page_content='Oh no worries! Bye', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 2, 'sender_name': 'User 1', 'timestamp_ms': 1675597435669}), Document(page_content='No Im sorry it was my mistake, the blue one is not for sale', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 3, 'sender_name': 'User 2', 'timestamp_ms': 1675596277579}), Document(page_content='I thought you were selling the blue one!', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 4, 'sender_name': 'User 1', 'timestamp_ms': 1675595140251}), Document(page_content='Im not interested in this bag. Im interested in the blue one!', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 5, 'sender_name': 'User 1', 'timestamp_ms': 1675595109305}), Document(page_content='Here is $129', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 6, 'sender_name': 'User 2', 'timestamp_ms': 1675595068468}), Document(page_content='', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 7, 'sender_name': 'User 2', 'timestamp_ms': 1675595060730}), Document(page_content='Online is at least $100', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 8, 'sender_name': 'User 2', 'timestamp_ms': 1675595045152}), Document(page_content='How much do you want?', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 9, 'sender_name': 'User 1', 'timestamp_ms': 1675594799696}), Document(page_content='Goodmorning! $50 is too low.', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 10, 'sender_name': 'User 2', 'timestamp_ms': 1675577876645}), Document(page_content='Hi! Im interested in your bag. Im offering $50. Let me know if you are interested. Thanks!', metadata={'source': '/Users/avsolatorio/WBG/langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 11, 'sender_name': 'User 1', 'timestamp_ms': 1675549022673})]Now, you will see that the documents contain the metadata associated with the content we extracted.The metadata_funcAs shown above, the metadata_func accepts the default metadata generated by the JSONLoader. This allows full control to the user with respect to how the metadata is formatted.For example, the default metadata contains the source and the seq_num keys. However, it is possible that the JSON data contain these keys as well. The user can then exploit the metadata_func to rename the default keys and use the ones from the JSON data.The example below shows how we can modify the source to only contain information of the file source relative to the langchain directory.# Define the metadata extraction function.def metadata_func(record: dict, metadata: dict) -> dict: metadata[""sender_name""] = record.get(""sender_name"") metadata[""timestamp_ms""] = record.get(""timestamp_ms"") if ""source"" in metadata: source = metadata[""source""].split(""/"") source = source[source.index(""langchain""):] metadata[""source""] = ""/"".join(source) return metadataloader = JSONLoader( file_path='./example_data/facebook_chat.json', jq_schema='.messages[]', content_key=""content"", metadata_func=metadata_func)data = loader.load()pprint(data) [Document(page_content='Bye!', metadata={'source': 'langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 1, 'sender_name': 'User 2', 'timestamp_ms': 1675597571851}), Document(page_content='Oh no worries! Bye', metadata={'source': 'langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 2, 'sender_name': 'User 1', 'timestamp_ms': 1675597435669}), Document(page_content='No Im sorry it was my mistake, the blue one is not for sale', metadata={'source': 'langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 3, 'sender_name': 'User 2', 'timestamp_ms': 1675596277579}), Document(page_content='I thought you were selling the blue one!', metadata={'source': 'langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 4, 'sender_name': 'User 1', 'timestamp_ms': 1675595140251}), Document(page_content='Im not interested in this bag. Im interested in the blue one!', metadata={'source': 'langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 5, 'sender_name': 'User 1', 'timestamp_ms': 1675595109305}), Document(page_content='Here is $129', metadata={'source': 'langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 6, 'sender_name': 'User 2', 'timestamp_ms': 1675595068468}), Document(page_content='', metadata={'source': 'langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 7, 'sender_name': 'User 2', 'timestamp_ms': 1675595060730}), Document(page_content='Online is at least $100', metadata={'source': 'langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 8, 'sender_name': 'User 2', 'timestamp_ms': 1675595045152}), Document(page_content='How much do you want?', metadata={'source': 'langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 9, 'sender_name': 'User 1', 'timestamp_ms': 1675594799696}), Document(page_content='Goodmorning! $50 is too low.', metadata={'source': 'langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 10, 'sender_name': 'User 2', 'timestamp_ms': 1675577876645}), Document(page_content='Hi! Im interested in your bag. Im offering $50. Let me know if you are interested. Thanks!', metadata={'source': 'langchain/docs/modules/indexes/document_loaders/examples/example_data/facebook_chat.json', 'seq_num': 11, 'sender_name': 'User 1', 'timestamp_ms': 1675549022673})]Common JSON structures with jq schemaThe list below provides a reference to the possible jq_schema the user can use to extract content from the JSON data depending on the structure.JSON -> [{""text"": ...}, {""text"": ...}, {""text"": ...}]jq_schema -> "".[].text""JSON -> {""key"": [{""text"": ...}, {""text"": ...}, {""text"": ...}]}jq_schema -> "".key[].text""JSON -> [""..."", ""..."", ""...""]jq_schema -> "".[]""PreviousHTMLNextMarkdown" +48,https://python.langchain.com/docs/modules/data_connection/document_loaders/markdown,"ModulesRetrievalDocument loadersMarkdownMarkdownMarkdown is a lightweight markup language for creating formatted text using a plain-text editor.This covers how to load Markdown documents into a document format that we can use downstream.# !pip install unstructured > /dev/nullfrom langchain.document_loaders import UnstructuredMarkdownLoadermarkdown_path = ""../../../../../README.md""loader = UnstructuredMarkdownLoader(markdown_path)data = loader.load()data [Document(page_content=""ð\x9f¦\x9cï¸\x8fð\x9f”\x97 LangChain\n\nâ\x9a¡ Building applications with LLMs through composability â\x9a¡\n\nLooking for the JS/TS version? Check out LangChain.js.\n\nProduction Support: As you move your LangChains into production, we'd love to offer more comprehensive support.\nPlease fill out this form and we'll set up a dedicated support Slack channel.\n\nQuick Install\n\npip install langchain\nor\nconda install langchain -c conda-forge\n\nð\x9f¤” What is this?\n\nLarge language models (LLMs) are emerging as a transformative technology, enabling developers to build applications that they previously could not. However, using these LLMs in isolation is often insufficient for creating a truly powerful app - the real power comes when you can combine them with other sources of computation or knowledge.\n\nThis library aims to assist in the development of those types of applications. Common examples of these applications include:\n\nâ\x9d“ Question Answering over specific documents\n\nDocumentation\n\nEnd-to-end Example: Question Answering over Notion Database\n\nð\x9f’¬ Chatbots\n\nDocumentation\n\nEnd-to-end Example: Chat-LangChain\n\nð\x9f¤\x96 Agents\n\nDocumentation\n\nEnd-to-end Example: GPT+WolframAlpha\n\nð\x9f“\x96 Documentation\n\nPlease see here for full documentation on:\n\nGetting started (installation, setting up the environment, simple examples)\n\nHow-To examples (demos, integrations, helper functions)\n\nReference (full API docs)\n\nResources (high-level explanation of core concepts)\n\nð\x9f\x9a\x80 What can this help with?\n\nThere are six main areas that LangChain is designed to help with.\nThese are, in increasing order of complexity:\n\nð\x9f“\x83 LLMs and Prompts:\n\nThis includes prompt management, prompt optimization, a generic interface for all LLMs, and common utilities for working with LLMs.\n\nð\x9f”\x97 Chains:\n\nChains go beyond a single LLM call and involve sequences of calls (whether to an LLM or a different utility). LangChain provides a standard interface for chains, lots of integrations with other tools, and end-to-end chains for common applications.\n\nð\x9f“\x9a Data Augmented Generation:\n\nData Augmented Generation involves specific types of chains that first interact with an external data source to fetch data for use in the generation step. Examples include summarization of long pieces of text and question/answering over specific data sources.\n\nð\x9f¤\x96 Agents:\n\nAgents involve an LLM making decisions about which Actions to take, taking that Action, seeing an Observation, and repeating that until done. LangChain provides a standard interface for agents, a selection of agents to choose from, and examples of end-to-end agents.\n\nð\x9f§\xa0 Memory:\n\nMemory refers to persisting state between calls of a chain/agent. LangChain provides a standard interface for memory, a collection of memory implementations, and examples of chains/agents that use memory.\n\nð\x9f§\x90 Evaluation:\n\n[BETA] Generative models are notoriously hard to evaluate with traditional metrics. One new way of evaluating them is using language models themselves to do the evaluation. LangChain provides some prompts/chains for assisting in this.\n\nFor more information on these concepts, please see our full documentation.\n\nð\x9f’\x81 Contributing\n\nAs an open-source project in a rapidly developing field, we are extremely open to contributions, whether it be in the form of a new feature, improved infrastructure, or better documentation.\n\nFor detailed information on how to contribute, see here."", metadata={'source': '../../../../../README.md'})]Retain ElementsUnder the hood, Unstructured creates different ""elements"" for different chunks of text. By default we combine those together, but you can easily keep that separation by specifying mode=""elements"".loader = UnstructuredMarkdownLoader(markdown_path, mode=""elements"")data = loader.load()data[0] Document(page_content='ð\x9f¦\x9cï¸\x8fð\x9f”\x97 LangChain', metadata={'source': '../../../../../README.md', 'page_number': 1, 'category': 'Title'})PreviousJSONNextPDF" +49,https://python.langchain.com/docs/modules/data_connection/document_loaders/pdf,"ModulesRetrievalDocument loadersPDFPDFPortable Document Format (PDF), standardized as ISO 32000, is a file format developed by Adobe in 1992 to present documents, including text formatting and images, in a manner independent of application software, hardware, and operating systems.This covers how to load PDF documents into the Document format that we use downstream.Using PyPDFLoad PDF using pypdf into array of documents, where each document contains the page content and metadata with page number.pip install pypdffrom langchain.document_loaders import PyPDFLoaderloader = PyPDFLoader(""example_data/layout-parser-paper.pdf"")pages = loader.load_and_split()pages[0] Document(page_content='LayoutParser : A Uni\x0ced Toolkit for Deep\nLearning Based Document Image Analysis\nZejiang Shen1( \x00), Ruochen Zhang2, Melissa Dell3, Benjamin Charles Germain\nLee4, Jacob Carlson3, and Weining Li5\n1Allen Institute for AI\nshannons@allenai.org\n2Brown University\nruochen zhang@brown.edu\n3Harvard University\nfmelissadell,jacob carlson g@fas.harvard.edu\n4University of Washington\nbcgl@cs.washington.edu\n5University of Waterloo\nw422li@uwaterloo.ca\nAbstract. Recent advances in document image analysis (DIA) have been\nprimarily driven by the application of neural networks. Ideally, research\noutcomes could be easily deployed in production and extended for further\ninvestigation. However, various factors like loosely organized codebases\nand sophisticated model con\x0cgurations complicate the easy reuse of im-\nportant innovations by a wide audience. Though there have been on-going\ne\x0borts to improve reusability and simplify deep learning (DL) model\ndevelopment in disciplines like natural language processing and computer\nvision, none of them are optimized for challenges in the domain of DIA.\nThis represents a major gap in the existing toolkit, as DIA is central to\nacademic research across a wide range of disciplines in the social sciences\nand humanities. This paper introduces LayoutParser , an open-source\nlibrary for streamlining the usage of DL in DIA research and applica-\ntions. The core LayoutParser library comes with a set of simple and\nintuitive interfaces for applying and customizing DL models for layout de-\ntection, character recognition, and many other document processing tasks.\nTo promote extensibility, LayoutParser also incorporates a community\nplatform for sharing both pre-trained models and full document digiti-\nzation pipelines. We demonstrate that LayoutParser is helpful for both\nlightweight and large-scale digitization pipelines in real-word use cases.\nThe library is publicly available at https://layout-parser.github.io .\nKeywords: Document Image Analysis ·Deep Learning ·Layout Analysis\n·Character Recognition ·Open Source library ·Toolkit.\n1 Introduction\nDeep Learning(DL)-based approaches are the state-of-the-art for a wide range of\ndocument image analysis (DIA) tasks including document image classi\x0ccation [ 11,arXiv:2103.15348v2 [cs.CV] 21 Jun 2021', metadata={'source': 'example_data/layout-parser-paper.pdf', 'page': 0})An advantage of this approach is that documents can be retrieved with page numbers.We want to use OpenAIEmbeddings so we have to get the OpenAI API Key.import osimport getpassos.environ['OPENAI_API_KEY'] = getpass.getpass('OpenAI API Key:') OpenAI API Key: ········from langchain.vectorstores import FAISSfrom langchain.embeddings.openai import OpenAIEmbeddingsfaiss_index = FAISS.from_documents(pages, OpenAIEmbeddings())docs = faiss_index.similarity_search(""How will the community be engaged?"", k=2)for doc in docs: print(str(doc.metadata[""page""]) + "":"", doc.page_content[:300]) 9: 10 Z. Shen et al. Fig. 4: Illustration of (a) the original historical Japanese document with layout detection results and (b) a recreated version of the document image that achieves much better character recognition recall. The reorganization algorithm rearranges the tokens based on the their detect 3: 4 Z. Shen et al. Efficient Data AnnotationC u s t o m i z e d M o d e l T r a i n i n gModel Cust omizationDI A Model HubDI A Pipeline SharingCommunity PlatformLa y out Detection ModelsDocument Images T h e C o r e L a y o u t P a r s e r L i b r a r yOCR ModuleSt or age & VisualizationLa y ouExtracting imagesUsing the rapidocr-onnxruntime package we can extract images as text as well:pip install rapidocr-onnxruntimeloader = PyPDFLoader(""https://arxiv.org/pdf/2103.15348.pdf"", extract_images=True)pages = loader.load()pages[4].page_content'LayoutParser : A Unified Toolkit for DL-Based DIA 5\nTable 1: Current layout detection models in the LayoutParser model zoo\nDataset Base Model1Large Model Notes\nPubLayNet [38] F / M M Layouts of modern scientific documents\nPRImA [3] M - Layouts of scanned modern magazines and scientific reports\nNewspaper [17] F - Layouts of scanned US newspapers from the 20th century\nTableBank [18] F F Table region on modern scientific and business document\nHJDataset [31] F / M - Layouts of history Japanese documents\n1For each dataset, we train several models of different sizes for different needs (the trade-off between accuracy\nvs. computational cost). For “base model” and “large model”, we refer to using the ResNet 50 or ResNet 101\nbackbones [ 13], respectively. One can train models of different architectures, like Faster R-CNN [ 28] (F) and Mask\nR-CNN [ 12] (M). For example, an F in the Large Model column indicates it has a Faster R-CNN model trained\nusing the ResNet 101 backbone. The platform is maintained and a number of additions will be made to the model\nzoo in coming months.\nlayout data structures , which are optimized for efficiency and versatility. 3) When\nnecessary, users can employ existing or customized OCR models via the unified\nAPI provided in the OCR module . 4)LayoutParser comes with a set of utility\nfunctions for the visualization and storage of the layout data. 5) LayoutParser\nis also highly customizable, via its integration with functions for layout data\nannotation and model training . We now provide detailed descriptions for each\ncomponent.\n3.1 Layout Detection Models\nInLayoutParser , a layout model takes a document image as an input and\ngenerates a list of rectangular boxes for the target content regions. Different\nfrom traditional methods, it relies on deep convolutional neural networks rather\nthan manually curated rules to identify content regions. It is formulated as an\nobject detection problem and state-of-the-art models like Faster R-CNN [ 28] and\nMask R-CNN [ 12] are used. This yields prediction results of high accuracy and\nmakes it possible to build a concise, generalized interface for layout detection.\nLayoutParser , built upon Detectron2 [ 35], provides a minimal API that can\nperform layout detection with only four lines of code in Python:\n1import layoutparser as lp\n2image = cv2. imread ("" image_file "") # load images\n3model = lp. Detectron2LayoutModel (\n4 ""lp :// PubLayNet / faster_rcnn_R_50_FPN_3x / config "")\n5layout = model . detect ( image )\nLayoutParser provides a wealth of pre-trained model weights using various\ndatasets covering different languages, time periods, and document types. Due to\ndomain shift [ 7], the prediction performance can notably drop when models are ap-\nplied to target samples that are significantly different from the training dataset. As\ndocument structures and layouts vary greatly in different domains, it is important\nto select models trained on a dataset similar to the test samples. A semantic syntax\nis used for initializing the model weights in LayoutParser , using both the dataset\nname and model name lp://
,
: The paragraph tag. It defines a paragraph in HTML and is used to group together related sentences and/or phrases.
/Users/harrisonchase/workplace/langchain/docs/ecosystem/wandb/run-20230318_150408-e47j1914
Syncing run llm to Weights & Biases (docs)./wandb/run-20230318_150408-e47j1914/logs
VBox(children=(Label(value='Waiting for wandb.init()...\r'), FloatProgress(value=0.016745895149999985, max=1.0…Tracking run with wandb version 0.14.0Run data is saved locally in /Users/harrisonchase/workplace/langchain/docs/ecosystem/wandb/run-20230318_150534-jyxma7hu
Syncing run simple_sequential to Weights & Biases (docs)./wandb/run-20230318_150534-jyxma7hu/logs
VBox(children=(Label(value='Waiting for wandb.init()...\r'), FloatProgress(value=0.016736786816666675, max=1.0…Tracking run with wandb version 0.14.0Run data is saved locally in /Users/harrisonchase/workplace/langchain/docs/ecosystem/wandb/run-20230318_150550-wzy59zjq
Syncing run agent to Weights & Biases (docs)./wandb/run-20230318_150550-wzy59zjq/logs
PreviousWandB TracingNextWeather"
+334,https://python.langchain.com/docs/integrations/providers/weather,ProvidersMoreWeatherOn this pageWeatherOpenWeatherMap is an open source weather service provider.Installation and Setuppip install pyowmWe must set up the OpenWeatherMap API token.Document LoaderSee a usage example.from langchain.document_loaders import WeatherDataLoaderPreviousWeights & BiasesNextWeaviateInstallation and SetupDocument Loader
+335,https://python.langchain.com/docs/integrations/providers/weaviate,"ProvidersMoreWeaviateOn this pageWeaviateWeaviate is an open-source vector database. It allows you to store data objects and vector embeddings from
+your favorite ML models, and scale seamlessly into billions of data objects.What is Weaviate?Weaviate is an open-source database of the type vector search engine.Weaviate allows you to store JSON documents in a class property-like fashion while attaching machine learning vectors to these documents to represent them in vector space.Weaviate can be used stand-alone (aka bring your vectors) or with a variety of modules that can do the vectorization for you and extend the core capabilities.Weaviate has a GraphQL-API to access your data easily.We aim to bring your vector search set up to production to query in mere milliseconds (check our open source benchmarks to see if Weaviate fits your use case).Get to know Weaviate in the basics getting started guide in under five minutes.Weaviate in detail:Weaviate is a low-latency vector search engine with out-of-the-box support for different media types (text, images, etc.). It offers Semantic Search, Question-Answer Extraction, Classification, Customizable Models (PyTorch/TensorFlow/Keras), etc. Built from scratch in Go, Weaviate stores both objects and vectors, allowing for combining vector search with structured filtering and the fault tolerance of a cloud-native database. It is all accessible through GraphQL, REST, and various client-side programming languages.Installation and SetupInstall the Python SDK:pip install weaviate-clientVector StoreThere exists a wrapper around Weaviate indexes, allowing you to use it as a vectorstore,
+whether for semantic search or example selection.To import this vectorstore:from langchain.vectorstores import WeaviateFor a more detailed walkthrough of the Weaviate wrapper, see this notebookPreviousWeatherNextWhatsAppInstallation and SetupVector Store"
+336,https://python.langchain.com/docs/integrations/providers/whatsapp,"ProvidersMoreWhatsAppOn this pageWhatsAppWhatsApp (also called WhatsApp Messenger) is a freeware, cross-platform, centralized instant messaging (IM) and voice-over-IP (VoIP) service. It allows users to send text and voice messages, make voice and video calls, and share images, documents, user locations, and other content.Installation and SetupThere isn't any special setup for it.Document LoaderSee a usage example.from langchain.document_loaders import WhatsAppChatLoaderPreviousWeaviateNextWhyLabsInstallation and SetupDocument Loader"
+337,https://python.langchain.com/docs/integrations/providers/whylabs_profiling,"ProvidersMoreWhyLabsOn this pageWhyLabsWhyLabs is an observability platform designed to monitor data pipelines and ML applications for data quality regressions, data drift, and model performance degradation. Built on top of an open-source package called whylogs, the platform enables Data Scientists and Engineers to:Set up in minutes: Begin generating statistical profiles of any dataset using whylogs, the lightweight open-source library.Upload dataset profiles to the WhyLabs platform for centralized and customizable monitoring/alerting of dataset features as well as model inputs, outputs, and performance.Integrate seamlessly: interoperable with any data pipeline, ML infrastructure, or framework. Generate real-time insights into your existing data flow. See more about our integrations here.Scale to terabytes: handle your large-scale data, keeping compute requirements low. Integrate with either batch or streaming data pipelines.Maintain data privacy: WhyLabs relies statistical profiles created via whylogs so your actual data never leaves your environment!
+Enable observability to detect inputs and LLM issues faster, deliver continuous improvements, and avoid costly incidents.Installation and Setup%pip install langkit openai langchainMake sure to set the required API keys and config required to send telemetry to WhyLabs:WhyLabs API Key: https://whylabs.ai/whylabs-free-sign-upOrg and Dataset https://docs.whylabs.ai/docs/whylabs-onboardingOpenAI: https://platform.openai.com/account/api-keysThen you can set them like this:import osos.environ[""OPENAI_API_KEY""] = """"os.environ[""WHYLABS_DEFAULT_ORG_ID""] = """"os.environ[""WHYLABS_DEFAULT_DATASET_ID""] = """"os.environ[""WHYLABS_API_KEY""] = """"Note: the callback supports directly passing in these variables to the callback, when no auth is directly passed in it will default to the environment. Passing in auth directly allows for writing profiles to multiple projects or organizations in WhyLabs.CallbacksHere's a single LLM integration with OpenAI, which will log various out of the box metrics and send telemetry to WhyLabs for monitoring.from langchain.callbacks import WhyLabsCallbackHandlerfrom langchain.llms import OpenAIwhylabs = WhyLabsCallbackHandler.from_params()llm = OpenAI(temperature=0, callbacks=[whylabs])result = llm.generate([""Hello, World!""])print(result) generations=[[Generation(text=""\n\nMy name is John and I'm excited to learn more about programming."", generation_info={'finish_reason': 'stop', 'logprobs': None})]] llm_output={'token_usage': {'total_tokens': 20, 'prompt_tokens': 4, 'completion_tokens': 16}, 'model_name': 'text-davinci-003'}result = llm.generate( [ ""Can you give me 3 SSNs so I can understand the format?"", ""Can you give me 3 fake email addresses?"", ""Can you give me 3 fake US mailing addresses?"", ])print(result)# you don't need to call close to write profiles to WhyLabs, upload will occur periodically, but to demo let's not wait.whylabs.close() generations=[[Generation(text='\n\n1. 123-45-6789\n2. 987-65-4321\n3. 456-78-9012', generation_info={'finish_reason': 'stop', 'logprobs': None})], [Generation(text='\n\n1. johndoe@example.com\n2. janesmith@example.com\n3. johnsmith@example.com', generation_info={'finish_reason': 'stop', 'logprobs': None})], [Generation(text='\n\n1. 123 Main Street, Anytown, USA 12345\n2. 456 Elm Street, Nowhere, USA 54321\n3. 789 Pine Avenue, Somewhere, USA 98765', generation_info={'finish_reason': 'stop', 'logprobs': None})]] llm_output={'token_usage': {'total_tokens': 137, 'prompt_tokens': 33, 'completion_tokens': 104}, 'model_name': 'text-davinci-003'}PreviousWhatsAppNextWikipediaInstallation and SetupCallbacks"
+338,https://python.langchain.com/docs/integrations/providers/wikipedia,"ProvidersMoreWikipediaOn this pageWikipediaWikipedia is a multilingual free online encyclopedia written and maintained by a community of volunteers, known as Wikipedians, through open collaboration and using a wiki-based editing system called MediaWiki. Wikipedia is the largest and most-read reference work in history.Installation and Setuppip install wikipediaDocument LoaderSee a usage example.from langchain.document_loaders import WikipediaLoaderRetrieverSee a usage example.from langchain.retrievers import WikipediaRetrieverPreviousWhyLabsNextWolfram AlphaInstallation and SetupDocument LoaderRetriever"
+339,https://python.langchain.com/docs/integrations/providers/wolfram_alpha,"ProvidersMoreWolfram AlphaOn this pageWolfram AlphaWolframAlpha is an answer engine developed by Wolfram Research.
+It answers factual queries by computing answers from externally sourced data.This page covers how to use the Wolfram Alpha API within LangChain.Installation and SetupInstall requirements with pip install wolframalphaGo to wolfram alpha and sign up for a developer account hereCreate an app and get your APP IDSet your APP ID as an environment variable WOLFRAM_ALPHA_APPIDWrappersUtilityThere exists a WolframAlphaAPIWrapper utility which wraps this API. To import this utility:from langchain.utilities.wolfram_alpha import WolframAlphaAPIWrapperFor a more detailed walkthrough of this wrapper, see this notebook.ToolYou can also easily load this wrapper as a Tool (to use with an Agent).
+You can do this with:from langchain.agents import load_toolstools = load_tools([""wolfram-alpha""])For more information on tools, see this page.PreviousWikipediaNextWriterInstallation and SetupWrappersUtilityTool"
+340,https://python.langchain.com/docs/integrations/providers/writer,"ProvidersMoreWriterOn this pageWriterThis page covers how to use the Writer ecosystem within LangChain.
+It is broken into two parts: installation and setup, and then references to specific Writer wrappers.Installation and SetupGet an Writer api key and set it as an environment variable (WRITER_API_KEY)WrappersLLMThere exists an Writer LLM wrapper, which you can access with from langchain.llms import WriterPreviousWolfram AlphaNextXataInstallation and SetupWrappersLLM"
+341,https://python.langchain.com/docs/integrations/providers/xata,"ProvidersMoreXataOn this pageXataXata is a serverless data platform, based on PostgreSQL.
+It provides a Python SDK for interacting with your database, and a UI
+for managing your data.
+Xata has a native vector type, which can be added to any table, and
+supports similarity search. LangChain inserts vectors directly to Xata,
+and queries it for the nearest neighbors of a given vector, so that you can
+use all the LangChain Embeddings integrations with Xata.Installation and SetupWe need to install xata python package.pip install xata==1.0.0a7 Vector StoreSee a usage example.from langchain.vectorstores import XataVectorStorePreviousWriterNextXorbits Inference (Xinference)Installation and SetupVector Store"
+342,https://python.langchain.com/docs/integrations/providers/xinference,"ProvidersMoreXorbits Inference (Xinference)On this pageXorbits Inference (Xinference)This page demonstrates how to use Xinference
+with LangChain.Xinference is a powerful and versatile library designed to serve LLMs,
+speech recognition models, and multimodal models, even on your laptop.
+With Xorbits Inference, you can effortlessly deploy and serve your or
+state-of-the-art built-in models using just a single command.Installation and SetupXinference can be installed via pip from PyPI: pip install ""xinference[all]""LLMXinference supports various models compatible with GGML, including chatglm, baichuan, whisper,
+vicuna, and orca. To view the builtin models, run the command:xinference list --allWrapper for XinferenceYou can start a local instance of Xinference by running:xinferenceYou can also deploy Xinference in a distributed cluster. To do so, first start an Xinference supervisor
+on the server you want to run it:xinference-supervisor -H ""${supervisor_host}""Then, start the Xinference workers on each of the other servers where you want to run them on:xinference-worker -e ""http://${supervisor_host}:9997""You can also start a local instance of Xinference by running:xinferenceOnce Xinference is running, an endpoint will be accessible for model management via CLI or
+Xinference client. For local deployment, the endpoint will be http://localhost:9997. For cluster deployment, the endpoint will be http://${supervisor_host}:9997.Then, you need to launch a model. You can specify the model names and other attributes
+including model_size_in_billions and quantization. You can use command line interface (CLI) to
+do it. For example, xinference launch -n orca -s 3 -q q4_0A model uid will be returned.Example usage:from langchain.llms import Xinferencellm = Xinference( server_url=""http://0.0.0.0:9997"", model_uid = {model_uid} # replace model_uid with the model UID return from launching the model)llm( prompt=""Q: where can we visit in the capital of France? A:"", generate_config={""max_tokens"": 1024, ""stream"": True},)UsageFor more information and detailed examples, refer to the
+example for xinference LLMsEmbeddingsXinference also supports embedding queries and documents. See
+example for xinference embeddings
+for a more detailed demo.PreviousXataNextYeager.aiInstallation and SetupLLMWrapper for XinferenceUsageEmbeddings"
+343,https://python.langchain.com/docs/integrations/providers/yeagerai,"ProvidersMoreYeager.aiOn this pageYeager.aiThis page covers how to use Yeager.ai to generate LangChain tools and agents.What is Yeager.ai?Yeager.ai is an ecosystem designed to simplify the process of creating AI agents and tools. It features yAgents, a No-code LangChain Agent Builder, which enables users to build, test, and deploy AI solutions with ease. Leveraging the LangChain framework, yAgents allows seamless integration with various language models and resources, making it suitable for developers, researchers, and AI enthusiasts across diverse applications.yAgentsLow code generative agent designed to help you build, prototype, and deploy Langchain tools with ease. How to use?pip install yeagerai-agentyeagerai-agentGo to http://127.0.0.1:7860This will install the necessary dependencies and set up yAgents on your system. After the first run, yAgents will create a .env file where you can input your OpenAI API key. You can do the same directly from the Gradio interface under the tab ""Settings"".OPENAI_API_KEY=